diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..de7514324 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,55 @@ + + +## Description + +Closes: #XXXX + + + +--- + +### Author Checklist + +*All items are required. Please add a note to the item if the item is not applicable and please add links to any +relevant follow-up issues.* + +I have... + +- [ ] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) + in the PR title +- [ ] added `!` to the type prefix if API or client breaking change +- [ ] targeted the correct branch ( + see [PR Targeting](https://github.com/AssetMantle/modules/blob/master/CONTRIBUTING.md#pr-targeting)) +- [ ] provided a link to the relevant issue or specification +- [ ] followed the guidelines + for [building modules](https://github.com/AssetMantle/modules/blob/master/docs/building-modules) +- [ ] included the necessary unit and + integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) +- [ ] added a changelog entry to `CHANGELOG.md` +- [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) +- [ ] updated the relevant documentation or specification +- [ ] reviewed "Files changed" and left comments if necessary +- [ ] confirmed all CI checks have passed + +### Reviewers Checklist + +*All items are required. Please add a note if the item is not applicable and please add your handle next to the items +reviewed if you only reviewed selected items.* + +I have... + +- [ ] confirmed the + correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title +- [ ] confirmed `!` in the type prefix if API or client breaking change +- [ ] confirmed all author checklist items have been addressed +- [ ] reviewed state machine logic +- [ ] reviewed API design and naming +- [ ] reviewed documentation is accurate +- [ ] reviewed tests and test coverage +- [ ] manually tested (if applicable) \ No newline at end of file diff --git a/.github/PULL_REQUEST_TEMPLATE/docs.md b/.github/PULL_REQUEST_TEMPLATE/docs.md new file mode 100644 index 000000000..d8c351b38 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/docs.md @@ -0,0 +1,38 @@ +## Description + +Closes: #XXXX + + + +--- + +### Author Checklist + +*All items are required. Please add a note to the item if the item is not applicable and please add links to any +relevant follow-up issues.* + +I have... + +- [ ] included the correct `docs:` prefix in the PR title +- [ ] targeted the correct branch ( + see [PR Targeting](https://github.com/AssetMantle/modules/blob/master/CONTRIBUTING.md#pr-targeting)) +- [ ] provided a link to the relevant issue or specification +- [ ] followed the [documentation writing guidelines](../../docs/DOC_WRITING_GUIDELINES.md) +- [ ] reviewed "Files changed" and left comments if necessary +- [ ] confirmed all CI checks have passed + +### Reviewers Checklist + +*All items are required. Please add a note if the item is not applicable and please add your handle next to the items +reviewed if you only reviewed selected items.* + +I have... + +- [ ] confirmed the correct `docs:` prefix in the PR title +- [ ] confirmed all author checklist items have been addressed +- [ ] confirmed that this PR only changes documentation +- [ ] reviewed content for consistency +- [ ] reviewed content for thoroughness +- [ ] reviewed content for spelling and grammar +- [ ] tested instructions (if applicable) diff --git a/.github/PULL_REQUEST_TEMPLATE/other.md b/.github/PULL_REQUEST_TEMPLATE/other.md new file mode 100644 index 000000000..018f15de9 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/other.md @@ -0,0 +1,35 @@ +## Description + +Closes: #XXXX + + + +--- + +### Author Checklist + +*All items are required. Please add a note to the item if the item is not applicable and please add links to any +relevant follow-up issues.* + +I have... + +- [ ] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) + in the PR title +- [ ] targeted the correct branch ( + see [PR Targeting](https://github.com/AssetMantle/modules/blob/master/CONTRIBUTING.md#pr-targeting)) +- [ ] provided a link to the relevant issue or specification +- [ ] reviewed "Files changed" and left comments if necessary +- [ ] confirmed all CI checks have passed + +### Reviewers Checklist + +*All items are required. Please add a note if the item is not applicable and please add your handle next to the items +reviewed if you only reviewed selected items.* + +I have... + +- [ ] confirmed the + correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title +- [ ] confirmed all author checklist items have been addressed +- [ ] confirmed that this PR does not change production code \ No newline at end of file diff --git a/.github/workflows/greetings.yml b/.github/workflows/greetings.yml deleted file mode 100644 index b56614790..000000000 --- a/.github/workflows/greetings.yml +++ /dev/null @@ -1,27 +0,0 @@ -# Configuration for welcome - https://github.com/behaviorbot/welcome - -# Configuration for new-issue-welcome - https://github.com/behaviorbot/new-issue-welcome -# Comment to be posted to on first time issues - -newIssueWelcomeComment: > - Hello there!πŸ‘‹ Welcome to the project!πŸš€βš‘ - - - Thank you and congratsπŸŽ‰ for opening your very first issue in this project - -# Configuration for new-pr-welcome - https://github.com/behaviorbot/new-pr-welcome -# Comment to be posted to on PRs from first time contributors in your repository - -newPRWelcomeComment: > - Hello there!πŸ‘‹ Welcome to the project!πŸ’– - - - Thank you and congratsπŸŽ‰ for opening your first pull request. πŸ™ŒπŸ™Œ We will get back to you as soon as we can πŸ˜„. - - -# Configuration for first-pr-merge - https://github.com/behaviorbot/first-pr-merge -# Comment to be posted to on pull requests merged by a first time user - -firstPRMergeComment: > - Congrats on merging your first pull request! πŸŽ‰ All the best for your amazing open source journey ahead πŸš€. - \ No newline at end of file diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 38af58bbf..0779ae897 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -1,28 +1,24 @@ name: Lint -# Lint runs golangci-lint over the entire Gaia repository -# This workflow is run on every pull request and push to master -# The `golangci` job will pass without running if no *.{go, mod, sum} files have been modified. + on: pull_request: push: branches: - master + paths: + - "**.go" + - "**.mod" + - "**.sum" + +permissions: + contents: read + jobs: golangci: name: golangci-lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - uses: technote-space/get-diff-action@v4 + - uses: golangci/golangci-lint-action@v3 with: - PATTERN: | - .go - .mod - .sum - - uses: golangci/golangci-lint-action@v2 - with: - # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. - version: v1.42.1 - args: --timeout 10m - #github-token: ${{ secrets.LINT_TOKEN }} - if: "env.GIT_DIFF != ''" \ No newline at end of file + version: latest diff --git a/.script/protogen.sh b/.script/protogen.sh deleted file mode 100644 index e69de29bb..000000000 diff --git a/.scripts/protocgen.sh b/.scripts/protocgen.sh deleted file mode 100755 index 3f8de2f35..000000000 --- a/.scripts/protocgen.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env bash - -set -xeo pipefail - -# get protoc executions -go install github.com/regen-network/cosmos-proto/protoc-gen-gocosmos 2>/dev/null - - -# get cosmos sdk from github -go get github.com/cosmos/cosmos-sdk@v0.45.9 2>/dev/null - diff --git a/CODING_GUIDELINES.md b/CODING_GUIDELINES.md new file mode 100644 index 000000000..6137fa514 --- /dev/null +++ b/CODING_GUIDELINES.md @@ -0,0 +1,157 @@ +# Coding Guidelines + +This document is an extension to [CONTRIBUTING](./CONTRIBUTING.md) and provides more details about the coding guidelines +and requirements. + +## API & Design + +* Code must be well-structured: + * packages must have a limited responsibility (different concerns can go to different packages), + * types must be easy to compose, + * think about maintainability and testability. +* "Depend upon abstractions, [not] concretions". +* Try to limit the number of methods you are exposing. It's easier to expose something later than to hide it. +* Take advantage of `internal` package concept. +* Follow agreed-upon design patterns and naming conventions. +* publicly-exposed functions are named logically, have forward-thinking arguments and return types. +* Avoid global variables and global configurators. +* Favor composable and extensible designs. +* Minimize code duplication. +* Limit third-party dependencies. + +Performance: + +* Avoid unnecessary operations or memory allocations. + +Security: + +* Pay proper attention to exploits involving: + * gas usage + * transaction verification and signatures + * malleability + * code must be always deterministic +* Thread safety. If some functionality is not thread-safe, or uses something that is not thread-safe, then clearly + indicate the risk on each level. + +## Acceptance tests + +Start the design by defining Acceptance Tests. The purpose of Acceptance Testing is to validate that the product being +developed corresponds to the needs of the real users and is ready for launch. Hence, we often talk about **User +Acceptance Test** (UAT). It also gives a better understanding of the product and helps designing a right interface and +API. + +### Why Acceptance Testing + +* Automated acceptance tests catch serious problems that unit or component test suites could never catch. +* Automated acceptance tests deliver business value the users are expecting as they test user scenarios. +* Automated acceptance tests executed and passed on every build help improve the software delivery process. +* Testers, developers, and customers need to work closely to create suitable automated acceptance test suites. + +### How to define Acceptance Test + +The best way to define AT is by starting from the user stories and think about all positive and negative scenarios a +user can perform. + +Product Developers should collaborate with stakeholders to define AT. Functional experts and business users are both +needed for defining AT. + +A good pattern for defining AT is listing scenarios +with [GIVEN-WHEN-THEN](https://martinfowler.com/bliki/GivenWhenThen.html) format where: + +* **GIVEN**: A set of initial circumstances (e.g. bank balance) +* **WHEN**: Some event happens (e.g. customer attempts a transfer) +* **THEN**: The expected result as per the defined behavior of the system + +In other words: we define a use case input, current state and the expected outcome. Example: + +> Feature: User trades stocks. +> Scenario: User requests a sell before close of trading +> +> Given I have 100 shares of MSFT stock +> And I have 150 shares of APPL stock +> And the time is before close of trading +> +> When I ask to sell 20 shares of MSFT stock +> +> Then I should have 80 shares of MSFT stock +> And I should have 150 shares of APPL stock +> And a sell order for 20 shares of MSFT stock should have been executed + +* + +Reference: [writing acceptance tests](https://openclassrooms.com/en/courses/4544611-write-agile-documentation-user-stories-acceptance-tests/4810081-writing-acceptance-tests)* +. + +### How and where to add acceptance tests + +Acceptance tests are written in the Markdown format, using the scenario template described above, and be part of the +specification (`xx_test.md` file in *spec* directory). +Example: [`eco-credits/spec/06.test.md`](https://github.com/regen-network/regen-ledger/blob/7297783577e6cd102c5093365b573163680f36a1/x/ecocredit/spec/06_tests.md) +. + +Acceptance tests should be defined during the design phase or at an early stage of development. Moreover, they should be +defined before writing a module architecture - it will clarify the purpose and usage of the software. Automated tests +should cover all acceptance tests scenarios. + +## Automated Tests + +Make sure your code is well tested: + +* Provide unit tests for every unit of your code if possible. Unit tests are expected to comprise 70%-80% of your tests. +* Describe the test scenarios you are implementing for integration tests. +* Create integration tests for queries and msgs. +* Use both test cases and property / fuzzy testing. We use the [rapid](https://pgregory.net/rapid) Go library for + property-based and fuzzy testing. +* Do not decrease code test coverage. Explain in a PR if test coverage is decreased. + +We expect tests to use `require` or `assert` rather than `t.Skip` or `t.Fail`, unless there is a reason to do otherwise. +When testing a function under a variety of different inputs, we prefer to use +[table driven tests](https://github.com/golang/go/wiki/TableDrivenTests). Table driven test error messages should follow +the following format +`, tc #, i #`. +`` is an optional short description of what's failing, `tc` is the index within the test case table that is +failing, and `i` is when there is a loop, exactly which iteration of the loop failed. The idea is you should be able to +see the error message and figure out exactly what failed. Here is an example check: + +``` +for tcIndex, tc := range cases { + + resp, err := doSomething() + require.NoError(err) + require.Equal(t, tc.expected, resp, "should correctly perform X") +``` + +## Quality Assurance + +We are forming a QA team that will support the core AssetMantle modules team and collaborators by: + +* Improving the AssetMantle modules QA Processes +* Improving automation in QA and testing +* Defining high-quality metrics +* Maintaining and improving testing frameworks (unit tests, integration tests, and functional tests) +* Defining test scenarios. +* Verifying user experience and defining a high quality. + * We want to have **acceptance tests**! Document and list acceptance lists that are implemented and identify + acceptance tests that are still missing. + * Acceptance tests should be specified in `acceptance-tests` directory as Markdown files. +* Supporting other teams with testing frameworks, automation, and User Experience testing. +* Testing chain upgrades for every new breaking change. + * Defining automated tests that assure data integrity after an update. + +Desired outcomes: + +* QA team works with Development Team. +* QA is happening in parallel with Core AssetMantle modules development. +* Releases are more predictable. +* QA reports. Goal is to guide with new tasks and be one of the QA measures. + +As a developer, you must help the QA team by providing instructions for User Experience (UX) and functional testing. + +### QA Team to cross-check Acceptance Tests + +Once the AT are defined, the QA team will have an overview of the behavior a user can expect and: + +* validate the user experience will be good +* validate the implementation conforms the acceptance tests +* by having a broader overview of the use cases, QA team should be able to define **test suites** and test data to + efficiently automate Acceptance Tests and reuse the work. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..5469b4a87 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,313 @@ +# Contributing + +- [Contributing](#contributing) + - [Architecture Decision Records (ADR)](#architecture-decision-records-adr) + - [Development Procedure](#development-procedure) + - [Testing](#testing) + - [Pull Requests](#pull-requests) + - [Pull Request Templates](#pull-request-templates) + - [Requesting Reviews](#requesting-reviews) + - [Updating Documentation](#updating-documentation) + - [Dependencies](#dependencies) + - [Protobuf](#protobuf) + - [Branching Model and Release](#branching-model-and-release) + - [PR Targeting](#pr-targeting) + - [Code Owner Membership](#code-owner-membership) + - [Concept & Feature Approval Process](#concept--feature-approval-process) + +Thank you for considering making contributions to the AssetMantle modules and related repositories! + +Contributing to this repo can mean many things such as participating in discussion or proposing code changes. To ensure +a smooth workflow for all contributors, the general procedure for contributing has been established: + +1. Start by browsing [new issues](https://github.com/AssetMantle/modules/issues). If you are looking for something + interesting or if you have something in your mind, there is a chance it was has been discussed. + +- Looking for a good place to start contributing? How about checking out + some [good first issues](https://github.com/AssetMantle/modules/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) + ? + +1. Determine whether a GitHub issue or discussion is more appropriate for your needs: +2. If you want to propose something new that requires specification or an additional design, or you would like to change + a process, start with a [new discussion](https://github.com/AssetMantle/modules/discussions/new). With discussions, + we can better handle the design process using discussion threads. A discussion usually leads to one or more issues. +3. If the issue you want addressed is a specific proposal or a bug, then open + a [new issue](https://github.com/AssetMantle/modules/issues/new/choose). +4. Review existing [issues](https://github.com/AssetMantle/modules/issues) to find an issue you'd like to help with. +5. Participate in thoughtful discussion on that issue. +6. If you would like to contribute: + 1. Ensure that the proposal has been accepted. + 2. Ensure that nobody else has already begun working on this issue. If they have, make sure to contact them to + collaborate. + 3. If nobody has been assigned for the issue, and you would like to work on it, make a comment on the issue to + inform the community of your intentions to begin work. +7. To submit your work as a contribution to the repository follow standard GitHub best practices. + See [pull request guideline](#pull-requests) below. + +**Note: ** For very small or blatantly obvious problems such as typos, you are not required to an open issue to submit a +PR, but be aware that for more complex problems/features, if a PR is opened before an adequate design discussion has +taken place in a GitHub issue, that PR runs a high likelihood of being rejected. + +## Architecture Decision Records (ADR) + +When proposing an architecture decision for the AssetMantle modules, please start by opening +an [issue](https://github.com/AssetMantle/modules/issues/new/choose) or +a [discussion](https://github.com/AssetMantle/modules/discussions/new) with a summary of the proposal. Once the proposal +has been discussed and there is rough alignment on a high-level approach to the design, are following this process to +ensure all involved parties are in agreement before any party begins coding the proposed +the [ADR creation process](./docs/architecture/PROCESS.md) can begin the implementation. If you would like to see +examples of how these are written, please refer to the current ADR. + +## Development Procedure + +- The latest state of development is on `master`. +- `master` must never fail `make lint test test-race`. +- No `--force` onto `master` (except when reverting a broken commit, which should seldom happen). +- Create a branch to start a wok: + - Fork the repo (core developers must create a branch directly in the AssetMantle modules repo), branch from the + HEAD of `master`, make some commits, and submit a PR to `master`. + - For core developers working within the `modules` repo, follow branch name conventions to ensure a clear ownership + of branches: `{moniker}/{issue#}-branch-name`. + - See [Branching Model](#branching-model-and-release) for more details. +- Be sure to run `make format` before every commit. The easiest way to do this is to have your editor run it for you + upon saving a file (most of the editors will do it anyway using a pre-configured setup of the programming language + mode). Additionally, be sure that your code is lint compliant by running `make lint-fix`. A convenience + git `pre-commit` hook that runs the formatters automatically before each commit is available in + the `contrib/githooks/` directory. +- Follow the [CODING GUIDELINES](CODING_GUIDELINES.md), which defines criteria for designing and coding a software. + +Code is merged into master through pull request procedure. + +### Testing + +Tests can be executed by running `make test` at the top level of the AssetMantle modules repository. + +### Pull Requests + +Before submitting a pull request: + +- merge the latest master `git merge origin/master`, +- run `make lint test` to ensure that all checks and tests pass. + +Then: + +1. If you have something to show, **start with a `Draft` PR**. It's good to have early validation of your work, and we + highly recommend this practice. A Draft PR also indicates to the community that the work is in progress. Draft PRs + also helps the core team provide early feedback and ensure the work is in the right direction. +2. When the code is complete, change your PR from `Draft` to `Ready for Review`. +3. Go through the actions for each checkbox present in the PR template description. The PR actions are automatically + provided for each new PR. +4. Be sure to include a relevant changelog entry in the `Unreleased` section of `CHANGELOG.md` (see file for log format) + . + +PRs must have a category prefix that is based on the type of changes being made (for example, `fix`, `feat`, +`refactor`, `docs`, and so on). The *type* must be included in the PR title as a prefix (for example, +`fix: `). This convention ensures that all changes that are committed to the base branch follow the +[Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification. Additionally, each PR should only +address a single issue. + +Pull requests are merged automatically using [`automerge` action](https://mergify.io/features/auto-merge). + +NOTE: when merging, GitHub will squash commits and rebase on top of the master. + +### Pull Request Templates + +There are three PR templates. The [default template](./.github/PULL_REQUEST_TEMPLATE.md) is for types `fix`, `feat`, +and `refactor`. We also have a [doc template](./.github/PULL_REQUEST_TEMPLATE/docs.md) for documentation changes and +[other template](./.github/PULL_REQUEST_TEMPLATE/other.md) for changes that do not affect production code. When +previewing a PR before it has been opened, you can change the template by adding one of the following parameters to the +url: + +- `template=docs.md` +- `template=other.md` + +### Requesting Reviews + +In order to accommodate the review process, the author of the PR must complete the author checklist +(from the pull request template) +to the best of their abilities before marking the PR as "Ready for Review". If you would like to receive early feedback +on the PR, open the PR as a "Draft" and leave a comment in the PR indicating that you would like early feedback and +tagging whoever you would like to receive feedback from. + +Code-owners are marked automatically as the reviewers. + +All PRs require at least two review approvals before they can be merged (one review might be acceptable in the case of +minor changes to [docs](./.github/PULL_REQUEST_TEMPLATE/docs.md) or [other](./.github/PULL_REQUEST_TEMPLATE/other.md) +changes that do not affect production code). Each PR template has a reviewers' checklist that must be completed before +the PR can be merged. Each reviewer is responsible for all checked items unless they have indicated otherwise by leaving +their handle next to specific items. In addition, use the following review explanations: + +- `LGTM` without an explicit approval means that the changes look good, but you haven't thoroughly reviewed the reviewer + checklist items. +- `Approval` means that you have completed some or all of the reviewer checklist items. If you only reviewed selected + items, you must add your handle next to the items that you have reviewed. In addition, follow these guidelines: + - You must also think through anything which ought to be included but is not + - You must think through whether any added code could be partially combined (DRYed) with existing code + - You must think through any potential security issues or incentive-compatibility flaws introduced by the changes + - Naming must be consistent with conventions and the rest of the codebase + - Code must live in a reasonable location, considering dependency structures (for example, not importing testing + modules in production code, or including example code modules in production code). + - If you approve the PR, you are responsible for any issues mentioned here and any issues that should have been + addressed after thoroughly reviewing the reviewer checklist items in the pull request template. +- If you sat down with the PR submitter and did a pairing review, add this information in the `Approval` or your PR + comments. +- If you are only making "surface level" reviews, submit notes as a `comment` review. + +### Updating Documentation + +If you open a PR on the AssetMantle modules, it is mandatory to update the relevant documentation in `/docs`. + +- If your change relates to the core SDK (baseapp, store, ...), be sure to update the content in `docs/basics/` + , `docs/core/` and/or `docs/building-modules/` folders. +- If your changes relate to the core of the CLI (not specifically to module's CLI/Rest), then modify the content in + the `docs/run-node/` folder. +- If your changes relate to a module, then be sure to update the module's spec in `x/moduleName/docs/spec/`. + +When writing documentation, follow the [Documentation Writing Guidelines](./docs/DOC_WRITING_GUIDELINES.md). + +## Dependencies + +We use [Go Modules](https://github.com/golang/go/wiki/Modules) to manage dependency versions. + +The master branch of every modules' repository should just build with `go get`, which means they should be kept +up-to-date with their dependencies, so we can get away with telling people they can just `go get` our software. + +Since some dependencies are not under our control, a third party may break our build, in which case we can fall back +on `go mod tidy -v`. + +## Protobuf + +We use [Protocol Buffers](https://developers.google.com/protocol-buffers) along +with [gogoproto](https://github.com/gogo/protobuf) to generate code for use in AssetMantle modules. + +For deterministic behavior around Protobuf tooling, everything is containerized using Docker. Make sure to have Docker +installed on your machine, or head to [Docker's website](https://docs.docker.com/get-docker/) to install it. + +For formatting code in `.proto` files, you can run `make proto-format` command. + +For linting and checking breaking changes, we use [buf](https://buf.build/). You can use the commands `make proto-lint` +and `make proto-check-breaking` to respectively lint your proto files and check for breaking changes. + +To generate the protobuf stubs, you can run `make proto-gen`. + +We also added the `make proto-all` command to run all the above commands sequentially. + +In order for imports to properly compile in your IDE, you may need to manually set your protobuf path in your IDE's +workspace settings/config. + +For example, in vscode your `.vscode/settings.json` should look like: + +``` +{ + "protoc": { + "options": [ + "--proto_path=${workspaceRoot}/proto", + "--proto_path=${workspaceRoot}/third_party/proto" + ] + } +} +``` + +## Branching Model and Release + +User-facing repos should adhere to the trunk based development branching model: https://trunkbaseddevelopment.com/. User +branches should start with a username, example: `{moniker}/{issue#}-branch-name`. + +The AssetMantle modules repository is +a [multi Go module](https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository) +repository. It means that we have more than one Go module in a single repository. + +The AssetMantle modules utilizes [semantic versioning](https://semver.org/). + +### PR Targeting + +Ensure that you base and target your PR on the `master` branch. + +All feature additions and all bug fixes must be targeted against `master`. Exception is for bug fixes which are only +related to a released version. In that case, the related bug fix PRs must target against the release branch. + +If needed, we backport a commit from `master` to a release branch (excluding consensus breaking feature, API breaking +and similar). + +## Code Owner Membership + +In the ethos of open source projects, and out of necessity to keep the code alive, the core contributor team will strive +to permit special repo privileges to developers who show an aptitude towards developing with this code base. + +Several kinds of privileges may be granted however most common privileges to be granted are merging rights to either +part of, or the entirety of the code base (through the GitHub `CODEOWNERS` file). The on-boarding process for new code +owners is as follows: On a bi-monthly basis (or more frequently if agreeable) all the existing code owners will +privately convene to discuss potential new candidates as well as the potential for existing code-owners to exit or "pass +on the torch". This private meeting is to be a held as a phone/video meeting. + +Subsequently, after the meeting, and pending final approval from the ICF, one of the existing code owners should open a +PR modifying the `CODEOWNERS` file. The other code owners should then all approve this PR to publicly display their +support. + +Only if unanimous consensus is reached among all the existing code-owners will an invitation be extended to a new +potential-member. Likewise, when an existing member is suggested to be removed/or have their privileges reduced, the +member in question must agree on the decision for their removal or else no action should be taken. If however, a +code-owner is demonstrably shown to intentionally have had acted maliciously or grossly negligent, code-owner privileges +may be stripped with no prior warning or consent from the member in question. + +Other potential removal criteria: + +* Missing 3 scheduled meetings results in ICF evaluating whether the member should be removed / replaced +* Violation of Code of Conduct + +Earning this privilege should be considered to be no small feat and is by no means guaranteed by any quantifiable +metric. Serving as a code owner is a symbol of great trust from the community of this project. + +## Concept & Feature Approval Process + +The process for how AssetMantle modules maintainers take features and ADRs from concept to release is broken up into +three distinct stages: **Strategy Discovery**, **Concept Approval**, and +**Implementation & Release Approval** + +### Strategy Discovery + +* Develop long term priorities, strategy and roadmap for the AssetMantle modules +* Release committee not yet defined as there is already a roadmap that can be used for the time being + +### Concept Approval + +* Architecture Decision Records (ADRs) may be proposed by any contributors or maintainers of the AssetMantle modules, + and should follow the guidelines outlined in the + [ADR Creation Process](https://github.com/AssetMantle/modules/blob/master/docs/architecture/PROCESS.md) +* After proposal, a time bound period for Request for Comment (RFC) on ADRs commences +* ADRs are intended to be iterative, and may be merged into `master` while still in a `Proposed` status + +**Time Bound Period** + +* Once a PR for an ADR is opened, reviewers are expected to perform a first review within 1 week of pull request being + open +* Time bound period for individual ADR Pull Requests to be merged should not exceed 2 weeks +* Total time bound period for an ADR to reach a decision (`ABANDONED | ACCEPTED | REJECTED`) should not exceed 4 weeks + +If an individual Pull Request for an ADR needs more time than 2 weeks to reach resolution, it should be merged in +current state (`Draft` or `Proposed`), with its contents updated to summarize the current state of its discussion. + +If an ADR is taking longer than 4 weeks to reach a final conclusion, the **Concept Approval Committee** +should convene to rectify the situation by either: + +- unanimously setting a new time bound period for this ADR +- making changes to the Concept Approval Process (as outlined here) +- making changes to the members of the Concept Approval Committee + +**Approval Committee & Decision-Making** + +In absence of general consensus, decision-making requires 1/2 vote from the two members of the **Concept Approval +Committee**. + +### Implementation & Release Approval + +The following process should be adhered to both for implementation PRs corresponding to ADRs, and for PRs made as part +of a release process: + +* Code reviewers should ensure the PR does exactly what the ADR said it should +* Code reviewers should have more senior engineering capability +* 1/2 approval is required from the **primary repo maintainers** in `CODEOWNERS` + +**Note**: For any major release series denoted as a "Stable Release" (e.g. v0.42 "Stargate"), a separate release +committee is often established. Stable Releases, and their corresponding release committees are documented separately +in [Stable Release Policy](./RELEASE_PROCESS.md#stable-release-policy)* \ No newline at end of file diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index f5e6f162c..000000000 --- a/Dockerfile +++ /dev/null @@ -1,39 +0,0 @@ -# This Dockerfile is used for proto generation -# To build, run `make proto-image-build` - -FROM bufbuild/buf:1.7.0 as BUILDER - -FROM golang:1.19-alpine - - -RUN apk add --no-cache \ - nodejs \ - npm \ - git \ - make - -ENV GOLANG_PROTOBUF_VERSION=1.28.0 \ - GOGO_PROTOBUF_VERSION=1.3.2 \ - GRPC_GATEWAY_VERSION=1.16.0 - - -RUN go install github.com/cosmos/cosmos-proto/cmd/protoc-gen-go-pulsar@latest -RUN go install google.golang.org/protobuf/cmd/protoc-gen-go@v${GOLANG_PROTOBUF_VERSION} -RUN go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway@v${GRPC_GATEWAY_VERSION} \ - github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger@v${GRPC_GATEWAY_VERSION} - -# install all gogo protobuf binaries -RUN git clone https://github.com/regen-network/protobuf.git; \ - cd protobuf; \ - go mod download; \ - make install - -# we need to use git clone because we use 'replace' directive in go.mod -# protoc-gen-gocosmos was moved to to in cosmos/gogoproto but pending a migration there. -RUN git clone https://github.com/regen-network/cosmos-proto.git; \ - cd cosmos-proto/protoc-gen-gocosmos; \ - go install . - -RUN npm install -g swagger-combine - -COPY --from=BUILDER /usr/local/bin /usr/local/bin diff --git a/Makefile b/Makefile index c4099d5e3..9c43cf603 100644 --- a/Makefile +++ b/Makefile @@ -8,33 +8,12 @@ LEDGER_ENABLED ?= true BINDIR ?= $(HOME)/go/bin SIMAPP = ./simulation/make -GOLANG_PROTOBUF_VERSION=1.28.0 -GOGO_PROTOBUF_VERSION=1.3.2 -GRPC_GATEWAY_VERSION=1.16.0 - -#install all dependencies for buf -install-buf-dependencies: - @go install github.com/cosmos/cosmos-proto/cmd/protoc-gen-go-pulsar@latest - @go install google.golang.org/protobuf/cmd/protoc-gen-go@v${GOLANG_PROTOBUF_VERSION} - @go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway@v${GRPC_GATEWAY_VERSION} - @go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger@v${GRPC_GATEWAY_VERSION} - git clone https://github.com/regen-network/protobuf.git; \ - cd protobuf; \ - go mod download; \ - make install - git clone https://github.com/regen-network/cosmos-proto.git; \ - cd cosmos-proto/protoc-gen-gocosmos; \ - go install . - go install github.com/regen-network/cosmos-proto/protoc-gen-gocosmos - go get github.com/cosmos/cosmos-sdk@v0.45.9 - rm -rf cosmos-proto protobuf - export GO111MODULE = on all: build test lintci # The below include contains the tools and runsim targets. -#include simulation/make/Makefile +include simulation/make/Makefile ######################################## ### Build diff --git a/README.md b/README.md new file mode 100644 index 000000000..00c657ab5 --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +
+

Modules

+ +![GitHub Workflow Status](https://github.com/assetmantle/modules/actions/workflows/test.yml/badge.svg) +[![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=AssetMantle_modules&metric=reliability_rating)](https://sonarcloud.io/summary/new_code?id=AssetMantle_modules) +[![Go Report Card](https://goreportcard.com/badge/github.com/assetmantle/modules)](https://goreportcard.com/report/github.com/assetmantle/modules) +[![License: Apache-2.0](https://img.shields.io/github/license/assetmantle/modules.svg)](https://github.com/assetmantle/modules/blob/main/LICENSE) +[![Lines Of Code](https://img.shields.io/tokei/lines/github/assetmantle/modules)](https://github.com/assetmantle/modules) +[![Version](https://img.shields.io/github/tag/assetmantle/modules.svg?cacheSeconds=3600)](https://github.com/assetmantle/modules/latest) + +
+ +Node modules and client utilities to build AssetMantle platform node applications. + +## Contributing + +If you want to contribute to AssetMantle Modules, please read the instructions +in [CODING_GUIDELINES.md](CODING_GUIDELINES.md). + +
+ +[![Discord](https://dcbadge.vercel.app/api/server/8tSZ2NPSnS)](https://discord.gg/8tSZ2NPSnS) +[![Twitter](https://img.shields.io/twitter/follow/AssetMantle?color=blue&label=Twitter&style=for-the-badge&cacheSeconds=3600&logo=twitter)](https://twitter.com/AssetMantle) +[![Reddit](https://img.shields.io/reddit/subreddit-subscribers/AssetMantle?style=for-the-badge&cacheSeconds=3600&logo=reddit&label=Reddit%20r/assetmantle&logoColor=white)](https://www.reddit.com/r/AssetMantle/) +[![YouTube](https://img.shields.io/youtube/channel/subscribers/UCQkov-0kol99KGMxyXc-a6Q?label=YouTube&cacheSeconds=3600&logoColor=red&style=for-the-badge&logo=YouTube)](https://www.youtube.com/channel/UCQkov-0kol99KGMxyXc-a6Q/videos) +[![Telegram](https://img.shields.io/badge/Telegram-chat-4995be?style=for-the-badge&cacheSeconds=3600)](https://t.me/assetmantlechat) +[![Instagram](https://img.shields.io/badge/Instagram-follow-dd2a7b?style=for-the-badge&cacheSeconds=3600)](https://www.instagram.com/assetmantle/) + +
+ +
+
+

Contributors

+
+
+ contributors +
diff --git a/RELEASE_PROCESS.md b/RELEASE_PROCESS.md new file mode 100644 index 000000000..ad6cc7c86 --- /dev/null +++ b/RELEASE_PROCESS.md @@ -0,0 +1,211 @@ +# Release Process + +This document outlines the process for releasing a new version of Cosmos SDK, which involves major release and patch +releases as well as maintenance for the major release. + +## Major Release Procedure + +A _major release_ is an increment of the first number (eg: `v1.2` β†’ `v2.0.0`) or the _point number_ (eg: `v1.1 β†’ v1.2.0` +, also called _point release_). Each major release opens a _stable release series_ and receives updates outlined in +the [Major Release Maintenance](#major-release-maintenance)_section. + +Before making a new _major_ release we do beta and release candidate releases. For example, for release 1.0.0: + +``` +v1.0.0-beta1 β†’ v1.0.0-beta2 β†’ ... β†’ v1.0.0-rc1 β†’ v1.0.0-rc2 β†’ ... β†’ v1.0.0 +``` + +- Release a first beta version on the `master` branch and freeze `master` from receiving any new features. After beta is + released, we focus on releasing the release candidate: + - finish audits and reviews + - kick off a large round of simulation testing (e.g. 400 seeds for 2k blocks) + - perform functional tests + - add more tests + - release new beta version as the bugs are discovered and fixed. +- After the team feels that the `master` works fine we create a `release/vY` branch (going forward known a release + branch), where `Y` is the version number, with the patch part substituted to `x` (eg: 0.42.x, 1.0.x). Ensure the + release branch is protected so that pushes against the release branch are permitted only by the release manager or + release coordinator. + - **PRs targeting this branch can be merged _only_ when exceptional circumstances arise** + - update the GitHub mergify integration by adding instructions for automatically backporting commits from `master` + to the `release/vY` using the `backport/Y` label. +- In the release branch, prepare a new version section in the `CHANGELOG.md` + - All links must be link-ified: `$ python ./scripts/linkify_changelog.py CHANGELOG.md` + - Copy the entries into a `RELEASE_CHANGELOG.md`, this is needed so the bot knows which entries to add to the + release page on GitHub. +- Create a new annotated git tag for a release candidate (eg: `git tag -a v1.1.0-rc1`) in the release branch. + - from this point we unfreeze master. + - the SDK teams collaborate and do their best to run testnets in order to validate the release. + - when bugs are found, create a PR for `master`, and backport fixes to the release branch. + - create new release candidate tags after bugs are fixed. +- After the team feels the release branch is stable and everything works, create a full release: + - update `CHANGELOG.md`. + - create a new annotated git tag (eg `git -a v1.1.0`) in the release branch. + - Create a GitHub release. + +Following _semver_ philosophy, point releases after `v1.0`: + +- must not break API +- can break consensus + +Before `v1.0`, point release can break both point API and consensus. + +## Patch Release Procedure + +A _patch release_ is an increment of the patch number (eg: `v1.2.0` β†’ `v1.2.1`). + +**Patch release must not break API nor consensus.** + +Updates to the release branch should come from `master` by backporting PRs (usually done by automatic cherry-pick +followed by a PRs to the release branch). The backports must be marked using `backport/Y` label in PR for master. It is +the PR author's responsibility to fix merge conflicts, update changelog entries, and ensure CI passes. If a PR +originates from an external contributor, a core team member assumes responsibility to perform this process instead of +the original author. Lastly, it is core team's responsibility to ensure that the PR meets all the SRU criteria. + +Point Release must follow the [Stable Release Policy](#stable-release-policy). + +After the release branch has all commits required for the next patch release: + +- update `CHANGELOG.md`. +- create a new annotated git tag (eg `git -a v1.1.0`) in the release branch. +- Create a GitHub release. + +## Major Release Maintenance + +Major Release series continue to receive bug fixes (released as a Patch Release) until they reach **End Of Life**. Major +Release series is maintained in compliance with the **Stable Release Policy** as described in this document. Note: not +every Major Release is denoted as stable releases. + +## Stable Release Policy + +### Patch Releases + +// TODO Correct Once a Persistence-SDK release has been completed and published, updates for it are released under +certain circumstances. + +### Rationale + +Unlike in-development `master` branch snapshots,// TODO correct **Persistence-SDK** releases are subject to much wider +adoption, and by a significantly different demographic of users. During development, changes in the `master` branch +affect SDK users, application developers, early adopters, and other advanced users that elect to use unstable +experimental software at their own risk. + +Conversely, users of a stable release expect a high degree of stability. They build their applications on it, and the +problems they experience with it could be potentially highly disruptive to their projects. + +Stable release updates are recommended to the vast majority of developers, and so it is crucial to treat them with great +caution. Hence, when updates are proposed, they must be accompanied by a strong rationale and present a low risk of +regressions, i.e. even one-line changes could cause unexpected regressions due to side effects or poorly tested code. We +never assume that any change, no matter how little or non-intrusive, is completely exempt of regression risks. + +Therefore, the requirements for stable changes are different from those that are candidates to be merged in the `master` +branch. When preparing future major releases, our aim is to design the most elegant, user-friendly and maintainable SDK +possible which often entails fundamental changes to the SDK's architecture design, rearranging and/or renaming packages +as well as reducing code duplication so that we maintain common functions and data structures in one place rather than +leaving them scattered all over the code base. However, once a release is published, the priority is to minimise the +risk caused by changes that are not strictly required to fix qualifying bugs; this tends to be correlated with +minimising the size of such changes. As such, the same bug may need to be fixed in different ways in stable releases +and `master` branch. + +### Migrations + +To smoothen the update to the latest stable release, the SDK includes a set of CLI commands for managing migrations +between SDK versions, under the `migrate` subcommand. Only migration scripts between stable releases are included. For +the current major release, and later, migrations are supported. + +### What qualifies as a Stable Release Update (SRU)? + +* **High-impact bugs** + * Bugs that may directly cause a security vulnerability. + * *Severe regressions* from a //TODO Correct Persistence-SDK's previous release. This includes all sort of issues + that may cause the core packages or the `x/` modules unusable. + * Bugs that may cause **loss of user's data**. +* Other safe cases: + * Bugs which don't fit in the aforementioned categories for which an obvious safe patch is known. + * Relatively small yet strictly non-breaking features with strong support from the community. + * Relatively small yet strictly non-breaking changes that introduce forward-compatible client features to smoothen + the migration to successive releases. + * Relatively small yet strictly non-breaking CLI improvements. + +### What does not qualify as SRU? + +* State machine changes. +* Changes that introduces API breakages (e.g. public functions and interfaces removal/renaming). +* Client-breaking changes in gRPC and HTTP request and response types. +* CLI-breaking changes. +* Cosmetic fixes, such as formatting or linter warning fixes. + +### What pull requests will be included in stable point-releases? + +Pull requests that fix bugs and add features that fall in the following categories do not require a **Stable Release +Exception** to be granted to be included in a stable point-release: + +* **Severe regressions**. +* Bugs that may cause **client applications** to be **largely unusable**. +* Bugs that may cause **state corruption or data loss**. +* Bugs that may directly or indirectly cause a **security vulnerability**. +* Non-breaking features that are strongly requested by the community. +* Non-breaking CLI improvements that are strongly requested by the community. + +### What pull requests will NOT be automatically included in stable point-releases? + +As rule of thumb, the following changes will **NOT** be automatically accepted into stable point-releases: + +* **State machine changes**. +* **Protobug-breaking changes**, as specified in [ADR-044](./docs/architecture/adr-044-protobuf-updates- guidelines.md). +* **Client-breaking changes**, i.e. changes that prevent gRPC, HTTP and RPC clients to continue interacting with the + node without any change. +* **API-breaking changes**, i.e. changes that prevent client applications to *build without modifications* to the client + application's source code. +* **CLI-breaking changes**, i.e. changes that require usage changes for CLI users. + +In some circumstances, PRs that don't meet the aforementioned criteria might be raised and asked to be granted a *Stable +Release Exception*. + +### Stable Release Exception - Procedure + +1. Check that the bug is either fixed or not reproducible in `master`. It is, in general, not appropriate to release bug + fixes for stable releases without first testing them in `master`. Please apply the label //TODO + Correct [v0.43](https://github.com/persistenceone/persistence-sdk/milestone/26) to the issue. +2. Add a comment to the issue and ensure it contains the following information (see the bug template below): + + * **[Impact]** An explanation of the bug on users and justification for backporting the fix to the stable release. + * A **[Test Case]** section containing detailed instructions on how to reproduce the bug. + * A **[Regression Potential]** section with a clear assessment on how regressions are most likely to manifest as a + result of the pull request that aims to fix the bug in the target stable release. + +3. **Stable Release Managers** will review and discuss the PR. Once *consensus* surrounding the rationale has been + reached and the technical review has successfully concluded, the pull request will be merged in the respective + point-release target branch (e.g. `release/v0.43.x`) and the PR included in the point-release's respective + milestone (e.g. `v0.43.5`). + +#### Stable Release Exception - Bug template + +``` +#### Impact + +Brief xplanation of the effects of the bug on users and a justification for backporting the fix to the stable release. + +#### Test Case + +Detailed instructions on how to reproduce the bug on Stargate's most recently published point-release. + +#### Regression Potential + +Explanation on how regressions might manifest - even if it's unlikely. +It is assumed that stable release fixes are well-tested and they come with a low risk of regressions. +It's crucial to make the effort of thinking about what could happen in case a regression emerges. +``` + +### Stable Release Managers + +The **Stable Release Managers** evaluate and approve or reject updates and backports to // TODO Correct Persistence-SDK +Stable Release series, according to the [stable release policy](#stable-release-policy). Decisions are made by +consensus. + +Their responsibilities include: + +* Driving the Stable Release Exception process. +* Approving/rejecting proposed changes to a stable release series. +* Executing the release process of stable point-releases in compliance with + the [Point Release Procedure](CONTRIBUTING.md). diff --git a/bin/golangci-lint b/bin/golangci-lint deleted file mode 100755 index a4e43f699..000000000 Binary files a/bin/golangci-lint and /dev/null differ diff --git a/buf.gen.gogo.yaml b/buf.gen.gogo.yaml deleted file mode 100644 index 4e8fb72d6..000000000 --- a/buf.gen.gogo.yaml +++ /dev/null @@ -1,8 +0,0 @@ -version: v1 -plugins: - - name: gocosmos - out: .. - opt: plugins=grpc,Mgoogle/protobuf/duration.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/struct.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/wrappers.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types,Mcosmos/orm/v1alpha1/orm.proto=github.com/cosmos/cosmos-sdk/api/cosmos/orm/v1alpha1 - - name: grpc-gateway - out: .. - opt: logtostderr=true,allow_colon_final_segments=true diff --git a/buf.gen.yaml b/buf.gen.yaml deleted file mode 100644 index 82a432d19..000000000 --- a/buf.gen.yaml +++ /dev/null @@ -1,15 +0,0 @@ -version: v1 -managed: - enabled: true - go_package_prefix: - default: github.com/AssetMantle/modules - except: - - buf.build/googleapis/googleapis - - buf.build/cosmos/gogo-proto -plugins: - - name: gocosmos - out: . - opt: plugins=grpc,Mgoogle/protobuf/duration.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/struct.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/wrappers.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types,Mcosmos/orm/v1alpha1/orm.proto=github.com/cosmos/cosmos-sdk/api/cosmos/orm/v1alpha1,paths=source_relative - - name: grpc-gateway - out: . - opt: logtostderr=true,allow_colon_final_segments=true,paths=source_relative diff --git a/buf.lock b/buf.lock deleted file mode 100644 index 2f66f81c4..000000000 --- a/buf.lock +++ /dev/null @@ -1,19 +0,0 @@ -# Generated by buf. DO NOT EDIT. -version: v1 -deps: - - remote: buf.build - owner: cosmos - repository: cosmos-proto - commit: 1935555c206d4afb9e94615dfd0fad31 - - remote: buf.build - owner: cosmos - repository: cosmos-sdk - commit: 05be31b399c8473aab4c9884a407ebaa - - remote: buf.build - owner: cosmos - repository: gogo-proto - commit: 34d970b699f84aa382f3c29773a60836 - - remote: buf.build - owner: googleapis - repository: googleapis - commit: faacf837d7304c58b7c9020c7807fa6e diff --git a/buf.md b/buf.md deleted file mode 100644 index 563731248..000000000 --- a/buf.md +++ /dev/null @@ -1,2 +0,0 @@ -# AssetMantle Schema -This module contains the schema for the AssetMantle blockchain application and it's services. \ No newline at end of file diff --git a/buf.yaml b/buf.yaml deleted file mode 100644 index 6e2ab1e3f..000000000 --- a/buf.yaml +++ /dev/null @@ -1,14 +0,0 @@ -version: v1 -name: buf.build/assetmantle/schema -deps: - - buf.build/cosmos/cosmos-sdk - - buf.build/cosmos/cosmos-proto - - buf.build/cosmos/gogo-proto - - buf.build/googleapis/googleapis -breaking: - use: - - FILE -lint: - use: - - DEFAULT - diff --git a/go.mod b/go.mod index 95533cc17..102d5cd2a 100644 --- a/go.mod +++ b/go.mod @@ -1,159 +1,109 @@ module github.com/AssetMantle/modules -go 1.18 +go 1.17 require ( - github.com/CosmWasm/wasmd v0.29.1 - github.com/Shopify/sarama v1.37.2 + github.com/CosmWasm/wasmd v0.10.0 + github.com/Shopify/sarama v1.19.0 github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d - github.com/cosmos/cosmos-sdk v0.45.9 - github.com/cosmos/go-bip39 v1.0.0 - github.com/gorilla/mux v1.8.0 + github.com/bartekn/go-bip39 v0.0.0-20171116152956-a05967ea095d + github.com/cosmos/cosmos-sdk v0.39.3 + github.com/gorilla/mux v1.7.4 github.com/pkg/errors v0.9.1 - github.com/spf13/cobra v1.5.0 - github.com/spf13/viper v1.13.0 - github.com/stretchr/testify v1.8.0 + github.com/spf13/cobra v1.1.1 + github.com/spf13/viper v1.7.1 + github.com/stretchr/testify v1.7.0 github.com/swaggo/http-swagger v1.3.3 github.com/swaggo/swag v1.8.1 - github.com/tendermint/tendermint v0.34.21 - github.com/tendermint/tm-db v0.6.7 + github.com/tendermint/tendermint v0.33.9 + github.com/tendermint/tm-db v0.5.2 + honnef.co/go/tools v0.0.1-2020.1.6 ) require ( - filippo.io/edwards25519 v1.0.0-beta.2 // indirect - github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect - github.com/99designs/keyring v1.2.1 // indirect + github.com/99designs/keyring v1.1.6 // indirect github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d // indirect - github.com/CosmWasm/wasmvm v1.1.1 // indirect + github.com/CosmWasm/go-cosmwasm v0.10.0 // indirect github.com/KyleBanks/depth v1.2.1 // indirect - github.com/Workiva/go-datastructures v1.0.53 // indirect - github.com/armon/go-metrics v0.4.0 // indirect + github.com/PuerkitoBio/purell v1.1.1 // indirect + github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bgentry/speakeasy v0.1.0 // indirect - github.com/btcsuite/btcd v0.22.1 // indirect - github.com/cespare/xxhash v1.1.0 // indirect - github.com/cespare/xxhash/v2 v2.1.2 // indirect - github.com/coinbase/rosetta-sdk-go v0.7.0 // indirect - github.com/confio/ics23/go v0.7.0 // indirect - github.com/cosmos/btcutil v1.0.4 // indirect - github.com/cosmos/cosmos-proto v1.0.0-alpha7 // indirect - github.com/cosmos/gogoproto v1.4.2 // indirect - github.com/cosmos/gorocksdb v1.2.0 // indirect - github.com/cosmos/iavl v0.19.3 // indirect - github.com/cosmos/ibc-go/v3 v3.3.0 // indirect + github.com/btcsuite/btcd v0.20.1-beta // indirect + github.com/btcsuite/btcutil v1.0.2 // indirect + github.com/cespare/xxhash/v2 v2.1.1 // indirect + github.com/cosmos/go-bip39 v1.0.0 // indirect github.com/cosmos/ledger-cosmos-go v0.11.1 // indirect github.com/cosmos/ledger-go v0.9.2 // indirect - github.com/creachadair/taskgroup v0.3.2 // indirect - github.com/danieljoos/wincred v1.1.2 // indirect + github.com/danieljoos/wincred v1.0.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect - github.com/dgraph-io/badger/v2 v2.2007.4 // indirect - github.com/dgraph-io/ristretto v0.1.0 // indirect - github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect - github.com/dustin/go-humanize v1.0.0 // indirect - github.com/dvsekhvalnov/jose2go v1.5.0 // indirect - github.com/eapache/go-resiliency v1.3.0 // indirect + github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b // indirect + github.com/eapache/go-resiliency v1.1.0 // indirect github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 // indirect github.com/eapache/queue v1.1.0 // indirect - github.com/felixge/httpsnoop v1.0.1 // indirect - github.com/fsnotify/fsnotify v1.5.4 // indirect - github.com/go-kit/kit v0.12.0 // indirect - github.com/go-kit/log v0.2.1 // indirect - github.com/go-logfmt/logfmt v0.5.1 // indirect + github.com/fsnotify/fsnotify v1.4.7 // indirect + github.com/go-kit/kit v0.10.0 // indirect + github.com/go-logfmt/logfmt v0.5.0 // indirect github.com/go-openapi/jsonpointer v0.19.5 // indirect github.com/go-openapi/jsonreference v0.20.0 // indirect github.com/go-openapi/spec v0.20.6 // indirect github.com/go-openapi/swag v0.19.15 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect - github.com/gogo/gateway v1.1.0 // indirect - github.com/gogo/protobuf v1.3.3 // indirect - github.com/golang/glog v1.0.0 // indirect - github.com/golang/protobuf v1.5.2 // indirect - github.com/golang/snappy v0.0.4 // indirect - github.com/google/btree v1.1.2 // indirect - github.com/google/gofuzz v1.2.0 // indirect - github.com/google/orderedcode v0.0.1 // indirect - github.com/gorilla/handlers v1.5.1 // indirect - github.com/gorilla/websocket v1.5.0 // indirect - github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect - github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect + github.com/gogo/protobuf v1.3.1 // indirect + github.com/golang/protobuf v1.4.1 // indirect + github.com/golang/snappy v0.0.2 // indirect + github.com/google/btree v1.0.0 // indirect + github.com/google/gofuzz v1.0.0 // indirect + github.com/gorilla/websocket v1.4.2 // indirect github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect github.com/gtank/merlin v0.1.1 // indirect github.com/gtank/ristretto255 v0.1.2 // indirect - github.com/hashicorp/errwrap v1.1.0 // indirect - github.com/hashicorp/go-immutable-radix v1.3.1 // indirect - github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/hashicorp/go-uuid v1.0.3 // indirect github.com/hashicorp/golang-lru v0.5.4 // indirect github.com/hashicorp/hcl v1.0.0 // indirect - github.com/hdevalence/ed25519consensus v0.0.0-20210204194344-59a8610d2b87 // indirect - github.com/improbable-eng/grpc-web v0.14.1 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect - github.com/jcmturner/aescts/v2 v2.0.0 // indirect - github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect - github.com/jcmturner/gofork v1.7.6 // indirect - github.com/jcmturner/gokrb5/v8 v8.4.3 // indirect - github.com/jcmturner/rpc/v2 v2.0.3 // indirect github.com/jmhodges/levigo v1.0.0 // indirect github.com/josharian/intern v1.0.0 // indirect - github.com/klauspost/compress v1.15.11 // indirect - github.com/lib/pq v1.10.6 // indirect - github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/magiconair/properties v1.8.6 // indirect + github.com/keybase/go-keychain v0.0.0-20190712205309-48d3d31d256d // indirect + github.com/libp2p/go-buffer-pool v0.0.2 // indirect + github.com/magiconair/properties v1.8.1 // indirect github.com/mailru/easyjson v0.7.6 // indirect - github.com/mattn/go-colorable v0.1.12 // indirect - github.com/mattn/go-isatty v0.0.14 // indirect - github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect + github.com/mattn/go-isatty v0.0.12 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 // indirect - github.com/minio/highwayhash v1.0.2 // indirect - github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/mitchellh/go-homedir v1.1.0 // indirect + github.com/mitchellh/mapstructure v1.1.2 // indirect github.com/mtibben/percent v0.2.1 // indirect - github.com/pelletier/go-toml v1.9.5 // indirect - github.com/pelletier/go-toml/v2 v2.0.5 // indirect - github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect - github.com/pierrec/lz4/v4 v4.1.17 // indirect + github.com/pelletier/go-toml v1.6.0 // indirect + github.com/pierrec/lz4 v2.0.5+incompatible // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.13.0 // indirect + github.com/prometheus/client_golang v1.5.1 // indirect github.com/prometheus/client_model v0.2.0 // indirect - github.com/prometheus/common v0.37.0 // indirect - github.com/prometheus/procfs v0.8.0 // indirect - github.com/rakyll/statik v0.1.7 // indirect - github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/regen-network/cosmos-proto v0.3.1 // indirect - github.com/rs/cors v1.8.2 // indirect - github.com/rs/zerolog v1.27.0 // indirect - github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa // indirect - github.com/spf13/afero v1.8.2 // indirect - github.com/spf13/cast v1.5.0 // indirect + github.com/prometheus/common v0.9.1 // indirect + github.com/prometheus/procfs v0.0.8 // indirect + github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 // indirect + github.com/spf13/afero v1.2.2 // indirect + github.com/spf13/cast v1.3.0 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect - github.com/subosito/gotenv v1.4.1 // indirect + github.com/subosito/gotenv v1.2.0 // indirect github.com/swaggo/files v0.0.0-20220610200504-28940afbdbfe // indirect - github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca // indirect + github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d // indirect + github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c // indirect github.com/tendermint/btcd v0.1.1 // indirect github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 // indirect - github.com/tendermint/go-amino v0.16.0 // indirect + github.com/tendermint/go-amino v0.15.1 // indirect + github.com/tendermint/iavl v0.14.3 // indirect github.com/zondax/hid v0.9.0 // indirect - go.etcd.io/bbolt v1.3.6 // indirect - golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90 // indirect - golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect - golang.org/x/net v0.0.0-20220927171203-f486391704dc // indirect - golang.org/x/sys v0.0.0-20220907062415-87db552b00fd // indirect - golang.org/x/term v0.0.0-20220722155259-a9ba230a4035 // indirect + go.etcd.io/bbolt v1.3.4 // indirect + golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de // indirect + golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 // indirect + golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e // indirect golang.org/x/text v0.3.7 // indirect - golang.org/x/tools v0.1.12 // indirect - google.golang.org/genproto v0.0.0-20220725144611-272f38e5d71b // indirect - google.golang.org/grpc v1.49.0 // indirect - google.golang.org/protobuf v1.28.1 // indirect - gopkg.in/ini.v1 v1.67.0 // indirect + golang.org/x/tools v0.1.10 // indirect + google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 // indirect + google.golang.org/grpc v1.30.0 // indirect + google.golang.org/protobuf v1.25.0 // indirect + gopkg.in/ini.v1 v1.51.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect - nhooyr.io/websocket v1.8.6 // indirect -) - -replace ( - github.com/confio/ics23/go => github.com/cosmos/cosmos-sdk/ics23/go v0.8.0 - github.com/gin-gonic/gin => github.com/gin-gonic/gin v1.7.7 - github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1 - google.golang.org/grpc => google.golang.org/grpc v1.33.2 + gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 // indirect ) diff --git a/go.sum b/go.sum index 4bec3f925..e00e41875 100644 --- a/go.sum +++ b/go.sum @@ -1,428 +1,261 @@ +bou.ke/monkey v1.0.1/go.mod h1:FgHuK96Rv2Nlf+0u1OOVDpCMdsWyOFmeeketDHE7LIg= +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.44.3/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= -cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= -cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= -cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= -cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= -cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= -cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= -cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= -cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= -cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= -cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= -cloud.google.com/go v0.75.0/go.mod h1:VGuuCn7PG0dwsd5XPVm2Mm3wlh3EL55/79EKB6hlPTY= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= -cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= -cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= -cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= -cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= -cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= -cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= -cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= -cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= -cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= -cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= -cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= -cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= -cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= -cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -filippo.io/edwards25519 v1.0.0-beta.2 h1:/BZRNzm8N4K4eWfK28dL4yescorxtO7YG1yun8fy+pI= -filippo.io/edwards25519 v1.0.0-beta.2/go.mod h1:X+pm78QAUPtFLi1z9PYIlS/bdDnvbCOGKtZ+ACWEf7o= -github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs= -github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4= -github.com/99designs/keyring v1.2.1 h1:tYLp1ULvO7i3fI5vE21ReQuj99QFSs7lGm0xWyJo87o= -github.com/99designs/keyring v1.2.1/go.mod h1:fc+wB5KTk9wQ9sDx0kFXB3A0MaeGHM9AwRStKOQ5vOA= -github.com/Azure/azure-pipeline-go v0.2.1/go.mod h1:UGSo8XybXnIGZ3epmeBw7Jdz+HiUVpqIlpz/HKHylF4= -github.com/Azure/azure-pipeline-go v0.2.2/go.mod h1:4rQ/NZncSvGqNkkOsNpOU1tgoNuIlp9AfUH5G1tvCHc= -github.com/Azure/azure-storage-blob-go v0.7.0/go.mod h1:f9YQKtsG1nMisotuTPpO0tjNuEjKRYAcJU8/ydDI++4= -github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= -github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= -github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= -github.com/Azure/go-autorest/autorest/adal v0.8.0/go.mod h1:Z6vX6WXXuyieHAXwMj0S6HY6e6wcHn37qQMBQlvY3lc= -github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= -github.com/Azure/go-autorest/autorest/date v0.2.0/go.mod h1:vcORJHLJEh643/Ioh9+vPmf1Ij9AEBM5FuBIXLmIy0g= -github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= -github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= -github.com/Azure/go-autorest/autorest/mocks v0.3.0/go.mod h1:a8FDP3DYzQ4RYfVAxAN3SVSiiO77gL2j2ronKKP0syM= -github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= -github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= +github.com/99designs/keyring v1.1.3/go.mod h1:657DQuMrBZRtuL/voxVyiyb6zpMehlm5vLB9Qwrv904= +github.com/99designs/keyring v1.1.6 h1:kVDC2uCgVwecxCk+9zoCt2uEL6dt+dfVzMvGgnVcIuM= +github.com/99designs/keyring v1.1.6/go.mod h1:16e0ds7LGQQcT59QqkTg72Hh5ShM51Byv5PEmW6uoRU= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d h1:nalkkPQcITbvhmL4+C4cKA87NW0tfm3Kl9VXRoPywFg= github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d/go.mod h1:URdX5+vg25ts3aCh8H5IFZybJYKWhJHYMTnf+ULtoC4= -github.com/CosmWasm/wasmd v0.29.1 h1:uagvdFfNYzkxUurKmVooHqkPqWo0dF+KvAzgUt4aOn0= -github.com/CosmWasm/wasmd v0.29.1/go.mod h1:agYHzj3R0O+UExLHlXLuEfLqhIrCC+pF5ouAmbe9/68= -github.com/CosmWasm/wasmvm v1.1.1 h1:0xtdrmmsP9fibe+x42WcMkp5aQ738BICgcH3FNVLzm4= -github.com/CosmWasm/wasmvm v1.1.1/go.mod h1:ei0xpvomwSdONsxDuONzV7bL1jSET1M8brEx0FCXc+A= -github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= -github.com/DataDog/zstd v1.4.1/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= -github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= +github.com/CosmWasm/go-cosmwasm v0.10.0 h1:3DBOiGtLllevLgf8PQO5+hRCKKqYEQJIw6cgaZzr1Ag= +github.com/CosmWasm/go-cosmwasm v0.10.0/go.mod h1:gAFCwllx97ejI+m9SqJQrmd2SBW7HA0fOjvWWJjM2uc= +github.com/CosmWasm/wasmd v0.10.0 h1:P37B8YUX3n7AxYEbTD71YcVjCRmu5LpXK5m7vpS6N+4= +github.com/CosmWasm/wasmd v0.10.0/go.mod h1:dq8Tc10ykvPSfCcv4bLVrjGiXm3ol5WDY255UrL8lHI= github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= -github.com/Microsoft/go-winio v0.5.2 h1:a9IhgEQBCUEk6QCdml9CiJGhAws+YwffDHEMp1VMrpA= -github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEVMRuU21PR1EtLVZJmdB18Gu3Rw= -github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= +github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= +github.com/Shopify/sarama v1.19.0 h1:9oksLxC6uxVPHPVYUmq6xhr1BOF/hHobWH2UzO67z1s= github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= -github.com/Shopify/sarama v1.37.2 h1:LoBbU0yJPte0cE5TZCGdlzZRmMgMtZU/XgnUKZg9Cv4= -github.com/Shopify/sarama v1.37.2/go.mod h1:Nxye/E+YPru//Bpaorfhc3JsSGYwCaDDj+R4bK52U5o= github.com/Shopify/toxiproxy v2.1.4+incompatible h1:TKdv8HiTLgE5wdJuEML90aBgNWsokNbMijUGhmcoBJc= github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= -github.com/Shopify/toxiproxy/v2 v2.5.0 h1:i4LPT+qrSlKNtQf5QliVjdP08GyAH8+BUIc9gT0eahc= -github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= -github.com/VictoriaMetrics/fastcache v1.5.7/go.mod h1:ptDBkNMQI4RtmVo8VS/XwRY6RoTu1dAWCbrk+6WsEM8= github.com/VividCortex/gohistogram v1.0.0 h1:6+hBz+qvs0JOrrNhhmR7lFxo5sINxBCGXrdtl/UvroE= github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= -github.com/Workiva/go-datastructures v1.0.53 h1:J6Y/52yX10Xc5JjXmGtWoSSxs3mZnGSaq37xZZh7Yig= -github.com/Workiva/go-datastructures v1.0.53/go.mod h1:1yZL+zfsztete+ePzZz/Zb1/t5BnDuE2Ya2MMGhzP6A= -github.com/Zilliqa/gozilliqa-sdk v1.2.1-0.20201201074141-dd0ecada1be6/go.mod h1:eSYp2T6f0apnuW8TzhV3f6Aff2SE8Dwio++U4ha4yEM= -github.com/adlio/schema v1.3.3 h1:oBJn8I02PyTB466pZO1UZEn1TV5XLlifBSyMrmHl/1I= +github.com/Workiva/go-datastructures v1.0.52 h1:PLSK6pwn8mYdaoaCZEMsXBpBotr4HHn9abU0yMQt0NI= +github.com/Workiva/go-datastructures v1.0.52/go.mod h1:Z+F2Rca0qCsVYDS8z7bAGm8f3UkzuWYS/oBZz5a7VVA= github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c= -github.com/agiledragon/gomonkey/v2 v2.3.1 h1:k+UnUY0EMNYUFUAQVETGY9uUTxjMdnUkP0ARyJS1zzs= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= -github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= -github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= -github.com/aristanetworks/goarista v0.0.0-20170210015632-ea17b1a17847/go.mod h1:D/tb0zPVXnP7fmsLZjtdUhSsumbK/ij54UXjjVgMGxQ= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= -github.com/armon/go-metrics v0.4.0 h1:yCQqn7dwca4ITXb+CbubHmedzaQYHhNhrEXLYUeEe8Q= -github.com/armon/go-metrics v0.4.0/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A= github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d h1:Byv0BzEl3/e6D5CLfI0j/7hiIEtvGVFPCZ7Ei2oq8iQ= github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU= -github.com/aws/aws-sdk-go v1.25.48/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= +github.com/bartekn/go-bip39 v0.0.0-20171116152956-a05967ea095d h1:1aAija9gr0Hyv4KfQcRcwlmFIrhkDmIj2dz5bkg/s/8= +github.com/bartekn/go-bip39 v0.0.0-20171116152956-a05967ea095d/go.mod h1:icNx/6QdFblhsEjZehARqbNumymUT/ydwlLojFdv7Sk= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= -github.com/btcsuite/btcd v0.0.0-20171128150713-2e60448ffcc6/go.mod h1:Dmm/EzmjnCiweXmzRIAiUWCInVmPgjkzgv5k4tVyXiQ= +github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= github.com/btcsuite/btcd v0.0.0-20190115013929-ed77733ec07d/go.mod h1:d3C0AkH6BRcvO8T0UEPu53cnw4IbV63x1bEjildYhO0= -github.com/btcsuite/btcd v0.0.0-20190315201642-aa6e0f35703c/go.mod h1:DrZx5ec/dmnfpw9KyYoQyYo7d0KEvTkk/5M/vbZjAr8= +github.com/btcsuite/btcd v0.20.1-beta h1:Ik4hyJqN8Jfyv3S4AGBOmyouMsYE3EdYODkMbQjwPGw= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= -github.com/btcsuite/btcd v0.21.0-beta/go.mod h1:ZSWyehm27aAuS9bvkATT+Xte3hjHZ+MRgMY/8NJ7K94= -github.com/btcsuite/btcd v0.22.1 h1:CnwP9LM/M9xuRrGSCGeMVs9iv09uMqwsVX7EeIpgV2c= -github.com/btcsuite/btcd v0.22.1/go.mod h1:wqgTSL29+50LRkmOVknEdmt8ZojIzhuWvgu/iptuN7Y= -github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 h1:q0rUy8C/TYNBQS1+CGKw68tLOFYSNEs0TFnxxnS9+4U= github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= github.com/btcsuite/btcutil v0.0.0-20180706230648-ab6388e0c60a/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= -github.com/btcsuite/btcutil v0.0.0-20190207003914-4c204d697803/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= +github.com/btcsuite/btcutil v1.0.2 h1:9iZ1Terx9fMIOtq1VrwdqfsATL9MC2l8ZrUY6YZ2uts= github.com/btcsuite/btcutil v1.0.2/go.mod h1:j9HUFwoQRsZL3V4n+qG+CUnEGHOarIxfC3Le2Yhbcts= -github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce h1:YtWJF7RHm2pYCvA5t0RPmAaLUhREsKuKd+SLhxFbFeQ= github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY= -github.com/btcsuite/goleveldb v1.0.0/go.mod h1:QiK9vBlgftBg6rWQIj6wFzbPfRjiykIEhBH4obrXJ/I= github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= -github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= -github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4= github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/cespare/cp v0.1.0/go.mod h1:SOGHArjBr4JWaSDEVpWpo/hNg6RoKrls6Oh40hiwW+s= github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= -github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag= -github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I= github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4dUb/I5gc9Hdhagfvm9+RyrPryS/auMzxE= -github.com/cloudflare/cloudflare-go v0.10.2-0.20190916151808-a80f83b9add9/go.mod h1:1MxXX1Ux4x6mqPmjkUgTP1CdXIBXKX7T+Jk9Gxrmx+U= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= -github.com/coinbase/rosetta-sdk-go v0.7.0 h1:lmTO/JEpCvZgpbkOITL95rA80CPKb5CtMzLaqF2mCNg= -github.com/coinbase/rosetta-sdk-go v0.7.0/go.mod h1:7nD3oBPIiHqhRprqvMgPoGxe/nyq3yftRmpsy29coWE= -github.com/containerd/continuity v0.3.0 h1:nisirsYROK15TAMVukJOUyGJjz4BNQJBVsNvAXZJ/eg= +github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= -github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= +github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= -github.com/cosmos/btcutil v1.0.4 h1:n7C2ngKXo7UC9gNyMNLbzqz7Asuf+7Qv4gnX/rOdQ44= -github.com/cosmos/btcutil v1.0.4/go.mod h1:Ffqc8Hn6TJUdDgHBwIZLtrLQC1KdJ9jGJl/TvgUaxbU= -github.com/cosmos/cosmos-proto v1.0.0-alpha7 h1:yqYUOHF2jopwZh4dVQp3xgqwftE5/2hkrwIV6vkUbO0= -github.com/cosmos/cosmos-proto v1.0.0-alpha7/go.mod h1:dosO4pSAbJF8zWCzCoTWP7nNsjcvSUBQmniFxDg5daw= -github.com/cosmos/cosmos-sdk v0.45.9 h1:Z4s1EZL/mfM8uSSZr8WmyEbWp4hqbWVI5sAIFR432KY= -github.com/cosmos/cosmos-sdk v0.45.9/go.mod h1:Z5M4TX7PsHNHlF/1XanI2DIpORQ+Q/st7oaeufEjnvU= -github.com/cosmos/cosmos-sdk/ics23/go v0.8.0 h1:iKclrn3YEOwk4jQHT2ulgzuXyxmzmPczUalMwW4XH9k= -github.com/cosmos/cosmos-sdk/ics23/go v0.8.0/go.mod h1:2a4dBq88TUoqoWAU5eu0lGvpFP3wWDPgdHPargtyw30= +github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/cosmos/cosmos-sdk v0.39.1-0.20200727135228-9d00f712e334/go.mod h1:soj4C8lIjJLeUQPBqrM+krbXdnF4cDKaaDgg1JIJYRU= +github.com/cosmos/cosmos-sdk v0.39.3 h1:zqd8gmjbwIrvdjY9JL49qH9we+MxLtQHjiEbhYu4xM8= +github.com/cosmos/cosmos-sdk v0.39.3/go.mod h1:PbSREFoyGIOW2OD6muga691A1WiBMcEqLhMy7m+hUJs= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= -github.com/cosmos/gogoproto v1.4.2 h1:UeGRcmFW41l0G0MiefWhkPEVEwvu78SZsHBvI78dAYw= -github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= -github.com/cosmos/gorocksdb v1.2.0 h1:d0l3jJG8M4hBouIZq0mDUHZ+zjOx044J3nGRskwTb4Y= -github.com/cosmos/gorocksdb v1.2.0/go.mod h1:aaKvKItm514hKfNJpUJXnnOWeBnk2GL4+Qw9NHizILw= -github.com/cosmos/iavl v0.19.3 h1:cESO0OwTTxQm5rmyESKW+zESheDUYI7CcZDWWDwnuxg= -github.com/cosmos/iavl v0.19.3/go.mod h1:X9PKD3J0iFxdmgNLa7b2LYWdsGd90ToV5cAONApkEPw= -github.com/cosmos/ibc-go/v3 v3.3.0 h1:r8gYUvQreMQrf4R5RgedK9gcbjLk4uE2q6fuZGjf4n0= -github.com/cosmos/ibc-go/v3 v3.3.0/go.mod h1:VUWLHw0C3USmTQZnTdkuXXdUdLbW8zsK3lV1Ieposog= -github.com/cosmos/interchain-accounts v0.1.0 h1:QmuwNsf1Hxl3P5GSGt7Z+JeuHPiZw4Z34R/038P5T6s= github.com/cosmos/ledger-cosmos-go v0.11.1 h1:9JIYsGnXP613pb2vPjFeMMjBI5lEDsEaF6oYorTy6J4= github.com/cosmos/ledger-cosmos-go v0.11.1/go.mod h1:J8//BsAGTo3OC/vDLjMRFLW6q0WAaXvHnVc7ZmE8iUY= github.com/cosmos/ledger-go v0.9.2 h1:Nnao/dLwaVTk1Q5U9THldpUMMXU94BOTWPddSmVB6pI= github.com/cosmos/ledger-go v0.9.2/go.mod h1:oZJ2hHAZROdlHiwTg4t7kP+GKIIkBT+o6c9QWFanOyI= -github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/creachadair/taskgroup v0.3.2 h1:zlfutDS+5XG40AOxcHDSThxKzns8Tnr9jnr6VqkYlkM= -github.com/creachadair/taskgroup v0.3.2/go.mod h1:wieWwecHVzsidg2CsUnFinW1faVN4+kq+TDlRJQ0Wbk= +github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0= -github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnGqR5Vl2tAx0= +github.com/danieljoos/wincred v1.0.2 h1:zf4bhty2iLuwgjgpraD2E9UbvO+fe54XXGJbOwe23fU= +github.com/danieljoos/wincred v1.0.2/go.mod h1:SnuYRW9lp1oJrZX/dXJqr0cPK5gYXqx3EJbmjhLdK9U= github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/deckarep/golang-set v0.0.0-20180603214616-504e848d77ea/go.mod h1:93vsz/8Wt4joVM7c2AVqh+YRMiUSc14yDtF28KmMOgQ= -github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218= -github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= -github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= -github.com/dgraph-io/badger/v2 v2.2007.2/go.mod h1:26P/7fbL4kUZVEVKLAKXkBXKOydDmM2p1e+NhhnBCAE= -github.com/dgraph-io/badger/v2 v2.2007.4 h1:TRWBQg8UrlUhaFdco01nO2uXwzKS7zd+HVdwV/GHc4o= -github.com/dgraph-io/badger/v2 v2.2007.4/go.mod h1:vSw/ax2qojzbN6eXHIx6KPKtCSHJN/Uz0X0VPruTIhk= -github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E= -github.com/dgraph-io/ristretto v0.0.3/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E= -github.com/dgraph-io/ristretto v0.1.0 h1:Jv3CGQHp9OjuMBSne1485aDpUkTKEcUqF+jm/LuerPI= -github.com/dgraph-io/ristretto v0.1.0/go.mod h1:fux0lOrBhrVCJd3lcTHsIJhq1T2rokOu6v9Vcb3Q9ug= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= -github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= -github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WAFKLNi6ZS0675eEUC9y3AlwSbQu1Y= -github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= -github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= -github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= -github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= -github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw= -github.com/dop251/goja v0.0.0-20200721192441-a695b0cdd498/go.mod h1:Mw6PkjjMXWbTj+nnj4s3QPXq1jaT0s5pC0iFD4+BOAA= github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= -github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= -github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= -github.com/dvsekhvalnov/jose2go v1.5.0 h1:3j8ya4Z4kMCwT5nXIKFSV84YS+HdqSSO0VsTQxaLAeM= -github.com/dvsekhvalnov/jose2go v1.5.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU= -github.com/dvyukov/go-fuzz v0.0.0-20200318091601-be3528f3a813/go.mod h1:11Gm+ccJnvAhCNLlf5+cS9KjtbaD5I5zaZpFMsTHWTw= +github.com/dvsekhvalnov/jose2go v0.0.0-20180829124132-7f401d37b68a/go.mod h1:7BvyPhdbLxMXIYTFPLsyJRFMsKmOZnQmzh6Gb+uquuM= +github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b h1:HBah4D48ypg3J7Np4N+HY/ZR76fx3HEUGxDU6Uk39oQ= +github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b/go.mod h1:7BvyPhdbLxMXIYTFPLsyJRFMsKmOZnQmzh6Gb+uquuM= +github.com/eapache/go-resiliency v1.1.0 h1:1NtRmCAqadE2FN4ZcN6g90TP3uk8cg9rn9eNK2197aU= github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= -github.com/eapache/go-resiliency v1.3.0 h1:RRL0nge+cWGlxXbUzJ7yMcq6w2XBEr19dCN6HECGaT0= -github.com/eapache/go-resiliency v1.3.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho= github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 h1:YEetp8/yCZMuEPMUDHG0CW/brkkEp8mzqk2+ODEitlw= github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc= github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= -github.com/edsrzf/mmap-go v0.0.0-20160512033002-935e0e8a636c/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/ethereum/go-ethereum v1.9.25/go.mod h1:vMkFiYLHI4tgPw4k2j4MHKoovchFE8plZ0M9VMk4/oM= -github.com/facebookgo/ensure v0.0.0-20200202191622-63f1cf65ac4c h1:8ISkoahWXwZR41ois5lSJBSVw4D0OV19Ht/JSTzvSv0= +github.com/facebookgo/ensure v0.0.0-20160127193407-b4ab57deab51 h1:0JZ+dUmQeA8IIVUMzysrX4/AKuQwWhV2dYQuPZdvdSQ= +github.com/facebookgo/ensure v0.0.0-20160127193407-b4ab57deab51/go.mod h1:Yg+htXGokKKdzcwhuNDwVvN+uBxDGXJ7G/VN1d8fa64= github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 h1:JWuenKqqX8nojtoVVWjGfOF9635RETekkoH6Cc9SX0A= -github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4 h1:7HZCaLC5+BZpmbhCOZJ293Lz68O7PYrF2EzeiFMwCLk= -github.com/fatih/color v1.3.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/facebookgo/stack v0.0.0-20160209184415-751773369052/go.mod h1:UbMTZqLaRiH3MsBH8va0n7s1pQYcu3uTb8G4tygF4Zg= +github.com/facebookgo/subset v0.0.0-20150612182917-8dac2c3c4870 h1:E2s37DuLxFhQDg5gKsWoLBOB0n+ZW8s599zru8FJ2/Y= +github.com/facebookgo/subset v0.0.0-20150612182917-8dac2c3c4870/go.mod h1:5tD+neXqOorC30/tWg0LCSkrqj/AR6gu8yY8/fpw1q0= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= -github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8SPQ= -github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/fjl/memsize v0.0.0-20180418122429-ca190fb6ffbc/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= +github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4= github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20= -github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI= -github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= -github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= -github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= -github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs= -github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U= +github.com/go-chi/chi v4.0.2+incompatible h1:maB6vn6FqCxrpz4FqWdh4+lwpyZIQS7YEAUcHlgXVRs= +github.com/go-chi/chi v4.0.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.10.0 h1:dXFJfIHVvUcpSgDOV+Ne6t7jXri8Tfv2uOLHUZ2XNuo= github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o= -github.com/go-kit/kit v0.12.0 h1:e4o3o3IsBfAKQh5Qbbiqyfu97Ku7jrO/JbohvztANh4= -github.com/go-kit/kit v0.12.0/go.mod h1:lHd+EkCZPIwYItmGDDRdhinkzX2A1sj+M9biaEaizzs= -github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= -github.com/go-kit/log v0.2.0/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= -github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU= -github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-logfmt/logfmt v0.5.0 h1:TrB8swr/68K7m9CcGut2g3UOihhbcbiMAYiuTXdEih4= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= -github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA= -github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= -github.com/go-ole/go-ole v1.2.1/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonreference v0.19.4/go.mod h1:RdybgQwPxbL4UEjuAruzK1x3nE69AqPYEJeo/TWfEeg= +github.com/go-openapi/jsonreference v0.19.5 h1:1WJP/wi4OjB4iV8KVbH73rQaoialJrqv8gitZLxGLtM= +github.com/go-openapi/jsonreference v0.19.5/go.mod h1:RdybgQwPxbL4UEjuAruzK1x3nE69AqPYEJeo/TWfEeg= github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA= github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo= +github.com/go-openapi/spec v0.19.14/go.mod h1:gwrgJS15eCUgjLpMjBJmbZezCsw88LmgeEip0M63doA= +github.com/go-openapi/spec v0.20.0 h1:HGLc8AJ7ynOxwv0Lq4TsnwLsWMawHAYiJIFzbcML86I= +github.com/go-openapi/spec v0.20.0/go.mod h1:+81FIL1JwC5P3/Iuuozq3pPE9dXdIEGxFutcFKaVbmU= github.com/go-openapi/spec v0.20.6 h1:ich1RQ3WDbfoeTqTAb+5EIxNmpKVJZWBNah9RAT0jIQ= github.com/go-openapi/spec v0.20.6/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/swag v0.19.11/go.mod h1:Uc0gKkdR+ojzsEpjh39QChyu92vPgIr72POcgHMAgSY= +github.com/go-openapi/swag v0.19.12 h1:Bc0bnY2c3AoF7Gc+IMIAQQsD8fLHjHpc19wXvYuayQI= +github.com/go-openapi/swag v0.19.12/go.mod h1:eFdyEBkTdoAf/9RXBvj4cr1nH7GD8Kzo5HTt47gr72M= github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= -github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= -github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= -github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= -github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= -github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= -github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= -github.com/go-sourcemap/sourcemap v2.1.2+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0= -github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= -github.com/gobwas/pool v0.2.0 h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8= -github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= -github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo= -github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+Hoeu/iUR3ruzNvZ+yQfO03a0= github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= -github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= -github.com/gogo/gateway v1.1.0 h1:u0SuhL9+Il+UbjM9VIE3ntfRujKbvVpFvNB4HbjeVQ0= -github.com/gogo/gateway v1.1.0/go.mod h1:S7rR8FRQyG3QFESeSv4l2WnsyzlCLG0CzBbUUo/mbic= +github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= +github.com/gogo/protobuf v1.3.1 h1:DqDEcV5aeaTmdFBePNpYsp3FlcVH/2ISVVM9Qf8PSls= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= -github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1-0.20190508161146-9fa652df1129/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= -github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3 h1:GV+pQPG/EUUbkh47niozDcADz6go/dUwhVzdUQHIVRw= github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1 h1:ZFgWrT+bLgsYPirOnRfKLYJLvssAegOj/hgyMFdJZe0= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.3-0.20201103224600-674baa8c7fc3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= -github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.2 h1:aeE13tS0IiQgFjYdoL8qN3K1N2bXXtI6Vi51/y7BpMw= +github.com/golang/snappy v0.0.2/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= -github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= +github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/gofuzz v1.1.1-0.20200604201612-c04b05f3adfa/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= -github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= -github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/orderedcode v0.0.1 h1:UzfcAexk9Vhv8+9pNOgRu41f16lHq725vPwnSeiG/Us= -github.com/google/orderedcode v0.0.1/go.mod h1:iVyU4/qPKHY5h/wSd6rZZCDcLJNxiWO6dvsYES2Sb20= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= -github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= -github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= +github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ= github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= -github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= -github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= -github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= +github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc= +github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/gorilla/websocket v1.4.1-0.20190629185528-ae1634f6a989/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= -github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/graph-gophers/graphql-go v0.0.0-20191115155744-f33e81362277/go.mod h1:9CQHMSxwO4MprSdzoIEobiHpoLtHm77vfxsvsIN5Vuc= +github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= -github.com/grpc-ecosystem/go-grpc-middleware v1.2.2/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= -github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 h1:+9834+KizmvFV7pXQGSXQTsaWhq2GjuNUt0aUU0YBYw= -github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway v1.8.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= -github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= -github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= github.com/gtank/merlin v0.1.1-0.20191105220539-8318aed1a79f/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= @@ -430,29 +263,20 @@ github.com/gtank/merlin v0.1.1 h1:eQ90iG7K9pOhtereWsmyRJ6RAwcP4tHTDBHXNg+u5is= github.com/gtank/merlin v0.1.1/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= github.com/gtank/ristretto255 v0.1.2 h1:JEqUCPA1NvLq5DwYtuzigd7ss8fwbYay9fi4/5uMzcc= github.com/gtank/ristretto255 v0.1.2/go.mod h1:Ph5OpO6c7xKUGROZfWVLiJf9icMDwUeIvY4OmlYW69o= +github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= +github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= -github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= -github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc= -github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= -github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= -github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= -github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= @@ -465,147 +289,83 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= -github.com/hdevalence/ed25519consensus v0.0.0-20210204194344-59a8610d2b87 h1:uUjLpLt6bVvZ72SQc/B4dXcPBw4Vgd7soowdRl52qEM= -github.com/hdevalence/ed25519consensus v0.0.0-20210204194344-59a8610d2b87/go.mod h1:XGsKKeXxeRr95aEOgipvluMPlgjr7dGlk9ZTWOjcUcg= -github.com/holiman/uint256 v1.1.1/go.mod h1:y4ga/t+u+Xwd7CpDgZESaRcWy0I7XMlTMA25ApIH5Jw= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= -github.com/huin/goupnp v1.0.0/go.mod h1:n9v9KO1tAxYH82qOn+UTIFQDmx5n1Zxd/ClZDMX7Bnc= -github.com/huin/goutil v0.0.0-20170803182201-1ca381bf3150/go.mod h1:PpLOETDnJ0o3iZrZfqZzyLl6l7F3c6L1oWn7OICBi6o= -github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/improbable-eng/grpc-web v0.14.1 h1:NrN4PY71A6tAz2sKDvC5JCauENWp0ykG8Oq1H3cpFvw= -github.com/improbable-eng/grpc-web v0.14.1/go.mod h1:zEjGHa8DAlkoOXmswrNvhUGEYQA9UI7DhrGeHR1DMGU= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/influxdata/influxdb v1.2.3-0.20180221223340-01288bdb0883/go.mod h1:qZna6X/4elxqT3yI9iZYdZrWWdeFOOprn86kgg4+IzY= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= -github.com/jackpal/go-nat-pmp v1.0.2-0.20160603034137-1fa385a6f458/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc= -github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8= -github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs= -github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo= -github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM= -github.com/jcmturner/gofork v1.7.6 h1:QH0l3hzAU1tfT3rZCnW5zXl+orbkNMMRGJfdJjHVETg= -github.com/jcmturner/gofork v1.7.6/go.mod h1:1622LH6i/EZqLloHfE7IeZ0uEJwMSUyQ/nDd82IeqRo= -github.com/jcmturner/goidentity/v6 v6.0.1 h1:VKnZd2oEIMorCTsFBnJWbExfNN7yZr3EhJAxwOkZg6o= -github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg= -github.com/jcmturner/gokrb5/v8 v8.4.3 h1:iTonLeSJOn7MVUtyMT+arAn5AKAPrkilzhGw8wE/Tq8= -github.com/jcmturner/gokrb5/v8 v8.4.3/go.mod h1:dqRwJGXznQrzw6cWmyo6kH+E7jksEQG/CyVWsJEsJO0= -github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY= -github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= -github.com/jedisct1/go-minisign v0.0.0-20190909160543-45766022959e/go.mod h1:G1CVv03EnqU1wYL2dFwXxW2An0az9JTl/ZsqXQeBlkU= github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= -github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= -github.com/jhump/protoreflect v1.12.1-0.20220721211354-060cc04fc18b h1:izTof8BKh/nE1wrKOrloNA5q4odOarjf+Xpe+4qow98= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmhodges/levigo v1.0.0 h1:q5EC36kV79HWeTBWsod3mG11EgStG3qArTKcvlksN1U= github.com/jmhodges/levigo v1.0.0/go.mod h1:Q6Qx+uH3RAqyK4rFQroq9RL7mdkABMcfhEI+nNuzMJQ= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= -github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= -github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/julienschmidt/httprouter v1.1.1-0.20170430222011-975b5c4c7c21/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= -github.com/karalabe/usb v0.0.0-20190919080040-51dc0efba356/go.mod h1:Od972xHfMJowv7NGVDiWVxk2zxnWgjLlJzE+F4F7AGU= -github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/keybase/go-keychain v0.0.0-20190712205309-48d3d31d256d h1:Z+RDyXzjKE0i2sTjZ/b1uxiGtPhFy34Ou/Tk0qwN0kM= +github.com/keybase/go-keychain v0.0.0-20190712205309-48d3d31d256d/go.mod h1:JJNrCn9otv/2QP4D7SMJBgaleKpOf66PnW6F5WGNRIc= +github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= -github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= -github.com/klauspost/compress v1.11.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= -github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= -github.com/klauspost/compress v1.15.11 h1:Lcadnb3RKGin4FYM/orgq0qde+nc15E5Cbqg4B9Sx9c= -github.com/klauspost/compress v1.15.11/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= -github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= -github.com/lib/pq v1.10.6 h1:jbk+ZieJ0D7EVGJYpL9QTz7/YW6UHbmdnZWYyK5cdBs= -github.com/lib/pq v1.10.6/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= -github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6cdF0Y8= -github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= +github.com/libp2p/go-buffer-pool v0.0.2 h1:QNK2iAFa8gjAe1SPz6mHSMuCcjs+X1wlHzeOSqcmlfs= +github.com/libp2p/go-buffer-pool v0.0.2/go.mod h1:MvaB6xw5vOrDl8rYZGLFdKAuk/hRoRZd1Vi32+RXyFM= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/lucasjones/reggen v0.0.0-20180717132126-cdb49ff09d77/go.mod h1:5ELEyG+X8f+meRWHuqUOewBOhvHkl7M76pdGEansxW4= +github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= -github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= -github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= +github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4= +github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-colorable v0.1.0/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= -github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= -github.com/mattn/go-ieproxy v0.0.0-20190610004146-91bb50d98149/go.mod h1:31jz6HNzdxOmlERGGEc4v/dMssOfmp2p5bT/okiKFFc= -github.com/mattn/go-ieproxy v0.0.0-20190702010315-6dee0af9227d/go.mod h1:31jz6HNzdxOmlERGGEc4v/dMssOfmp2p5bT/okiKFFc= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.5-0.20180830101745-3fb116b82035/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= -github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 h1:I0XW9+e1XWDxdcEniV4rQAIOPUGDq67JSCiRCgGCZLI= -github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 h1:hLDRPB66XQT/8+wG9WsDpiCvZf1yKO7sz7scAjSlBa0= github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643/go.mod h1:43+3pMjjKimDBf5Kr4ZFNGbLql1zKkbImw+fZbw3geM= -github.com/minio/highwayhash v1.0.2 h1:Aak5U0nElisjDCfPSG79Tgzkn2gl66NxOMspRrKnA/g= -github.com/minio/highwayhash v1.0.2/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY= +github.com/minio/highwayhash v1.0.0 h1:iMSDhgUILCr0TNm8LWlSjF8N0ZIj2qbO8WHp6Q/J2BA= +github.com/minio/highwayhash v1.0.0/go.mod h1:xQboMTeM9nY9v/LlAOxFctujiv5+Aq2hR5dxBpaMbdc= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= -github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs= github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f h1:KUppIJq7/+SVif2QVs3tOP0zanoHgBEVAwHxUSIzRqU= -github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/mwitkow/grpc-proxy v0.0.0-20181017164139-0f1106ef9c76/go.mod h1:x5OoJHDHqxHS801UIuhqGl6QdSAEJvtausosHSdazIo= -github.com/naoina/go-stringutil v0.1.0/go.mod h1:XJ2SJL9jCtBh+P9q5btrd/Ylo8XwT/h1USek5+NqSA0= -github.com/naoina/toml v0.1.2-0.20170918210437-9fafd6967416/go.mod h1:NBIhNtsFMo3G2szEBne+bO4gS192HuIYRqfvOWb4i1E= github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= github.com/nats-io/jwt v0.3.2/go.mod h1:/euKqTS1ZD+zzjYrY7pseZrTtWQSjujC7xjPc8wL6eU= github.com/nats-io/nats-server/v2 v2.1.2/go.mod h1:Afk+wRZqkMQs/p45uXdrVLuab3gwv3Z8C4HTBu8GD/k= @@ -613,30 +373,20 @@ github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzE github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= -github.com/neilotoole/errgroup v0.1.5/go.mod h1:Q2nLGf+594h0CLBs/Mbg6qOr7GtqDK7C2S41udRnToE= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= -github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtbWGs= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= -github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= -github.com/olekukonko/tablewriter v0.0.2-0.20190409134802-7e037d187b0c/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA= -github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= -github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= +github.com/onsi/ginkgo v1.8.0 h1:VkHVNpR4iVnU8XQR6DBm8BqYjN7CRzw+xKUbVVbbW9w= +github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= -github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo= +github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= -github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= -github.com/opencontainers/image-spec v1.0.3-0.20211202183452-c5a74bcca799 h1:rc3tiVYb5z54aKaDfakKn0dDjIyPpTtszkjuMzyt7ec= -github.com/opencontainers/runc v1.1.3 h1:vIXrkId+0/J2Ymu2m7VjGvbSlAId9XNRPhn2p4b+d8w= github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go.mod h1:Ngi6UdF0k5OKD5t5wlmGhe/EDKPoUM3BXZSSfIuJbis= github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74= github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= @@ -645,47 +395,36 @@ github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxS github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= -github.com/ory/dockertest v3.3.5+incompatible h1:iLLK6SQwIhcbrG783Dghaaa3WPzGc+4Emza6EbVUUGA= -github.com/otiai10/copy v1.7.0 h1:hVoPiN+t+7d2nzzwMiDHPSOogsWAStewq3TwU05+clE= +github.com/otiai10/copy v1.0.2/go.mod h1:c7RpqBkwMom4bYTSkLSym4VSJz/XtncWRAj/J4PEIMY= +github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= +github.com/otiai10/curr v0.0.0-20190513014714-f5a3d24e5776/go.mod h1:3HNVkVOU7vZeFXocWuvtcS0XSFLcf2XUSDHkq9t1jU4= +github.com/otiai10/mint v1.2.4/go.mod h1:d+b7n/0R3tdyUYYylALXpWQ/kTN+QobSq/4SRGBkR3M= +github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= -github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pborman/uuid v0.0.0-20170112150404-1b00554d8222/go.mod h1:VyrYX9gd7irzKovcSS6BIIEwPRkP2Wm2m9ufcdFSJ34= github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= -github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= -github.com/pelletier/go-toml/v2 v2.0.5 h1:ipoSadvV8oGUjnUbMub59IDPPwfxF694nG/jwbMiyQg= -github.com/pelletier/go-toml/v2 v2.0.5/go.mod h1:OMHamSCAODeSsVrwwvcJOaoN0LIUIaFVNZzmWyNfXas= +github.com/pelletier/go-toml v1.6.0 h1:aetoXYr0Tv7xRU/V4B4IZJ2QcbtMUFoNb3ORp7TzIK4= +github.com/pelletier/go-toml v1.6.0/go.mod h1:5N711Q9dKgbdkxHL+MEfF31hpT7l0S0s/t2kKREewys= github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= -github.com/peterh/liner v1.1.1-0.20190123174540-a2c9a5303de7/go.mod h1:CRroGNssyjTd/qIG2FyxByd2S8JEAZXBl4qUrZf8GS0= -github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 h1:q2e307iGHPdTGp0hoxKjt1H5pDo6utceo3dQVK3I5XQ= -github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o= -github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= +github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= -github.com/pierrec/lz4/v4 v4.1.17 h1:kV4Ip+/hUBC+8T6+2EgburRtkE9ef4nbY3f4dFhGjMc= -github.com/pierrec/lz4/v4 v4.1.17/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= -github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= +github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= -github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= -github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= -github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY= -github.com/prometheus/client_golang v1.13.0 h1:b71QUfeo5M8gq2+evJdTPfZhYMAU0uKPkyPJ7TPsloU= -github.com/prometheus/client_golang v1.13.0/go.mod h1:vTeo+zgvILHsnnj/39Ou/1fPN5nJFOEMgftOUOmlvYQ= +github.com/prometheus/client_golang v1.5.1 h1:bdHYieyGlH+6OLEk2YQha8THib30KP0/yD0YH9m6xcA= +github.com/prometheus/client_golang v1.5.1/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -695,81 +434,51 @@ github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2 github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= +github.com/prometheus/common v0.9.1 h1:KOMtN28tlbam3/7ZKEYKHhKoJZYYj3gMH4uc62x7X7U= github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= -github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= -github.com/prometheus/common v0.15.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s= -github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= -github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= -github.com/prometheus/common v0.37.0 h1:ccBbHCgIiT9uSoFY0vX8H3zsNR5eLt17/RQLUvn8pXE= -github.com/prometheus/common v0.37.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.8 h1:+fpWZdT24pJBiqJdAwYBjPSk+5YmQzYNPYzQsdzLkt8= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= -github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/prometheus/procfs v0.3.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= -github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= -github.com/prometheus/procfs v0.8.0 h1:ODq8ZFEaYeCaZOJlZZdJA2AbQR98dSHSM1KW/You5mo= -github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0uaxHdg830/4= -github.com/prometheus/tsdb v0.6.2-0.20190402121629-4f204dcbc150/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= -github.com/rakyll/statik v0.1.7 h1:OF3QCZUuyPxuGEP7B4ypUa7sB/iHtqOTDYZXGM8KOdQ= -github.com/rakyll/statik v0.1.7/go.mod h1:AlZONWzMtEnMs7W4e/1LURLiI49pIMmp6V9Unghqrcc= +github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= +github.com/rakyll/statik v0.1.6/go.mod h1:OEi9wJV/fMUAGx1eNjq75DKDsJVuEv1U0oYdX6GX8Zs= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= -github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= -github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= -github.com/regen-network/cosmos-proto v0.3.1 h1:rV7iM4SSFAagvy8RiyhiACbWEGotmqzywPxOvwMdxcg= -github.com/regen-network/cosmos-proto v0.3.1/go.mod h1:jO0sVX6a1B36nmE8C9xBFXpNwWejXC7QqCOnH3O0+YM= -github.com/regen-network/protobuf v1.3.3-alpha.regen.1 h1:OHEc+q5iIAXpqiqFKeLpu5NwTIkVXUs48vFMwzqpqY4= -github.com/regen-network/protobuf v1.3.3-alpha.regen.1/go.mod h1:2DjTFR1HhMQhiWC5sZ4OhQ3+NtdbZ6oBDKQwq5Ou+FI= -github.com/rjeczalik/notify v0.9.1/go.mod h1:rKwnCoCGeuQnwBtTSPL9Dad03Vh2n40ePRrjvIXnJho= +github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 h1:MkV+77GLUNo5oJ0jf870itWm3D0Sjh7+Za9gazKc5LQ= +github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= -github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k= -github.com/rs/cors v0.0.0-20160617231935-a62a804a8a00/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= +github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= -github.com/rs/cors v1.8.2 h1:KCooALfAYGs415Cwu5ABvv9n9509fSiG5SQJn/AQo4U= -github.com/rs/cors v1.8.2/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= -github.com/rs/xhandler v0.0.0-20160618193221-ed27b6fd6521/go.mod h1:RvLn4FgxWubrpZHtQLnOf6EwhN2hEMusxZOhcW9H3UQ= -github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.27.0 h1:1T7qCieN22GVc8S4Q2yuexzBb1EqjbgjSH9RohbMjKs= -github.com/rs/zerolog v1.27.0/go.mod h1:7frBqO0oezxmnO7GF86FY++uy8I0Tk/If5ni1G9Qc0U= -github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= -github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa h1:0U2s5loxrTy6/VgfVoLuVLFJcURKLH49ie0zSch7gh4= -github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa/go.mod h1:F73l+cr82YSh10GxyRI6qZiCgK64VaZjwesgfQ1/iLM= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/segmentio/fasthash v1.0.3/go.mod h1:waKX8l2N8yckOgmSsXJi7x1ZfdKZ4x7KRMzBtS3oedY= -github.com/shirou/gopsutil v2.20.5+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= -github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa/go.mod h1:oJyF+mSPHbB5mVY2iO9KV3pTt/QbIkGaO8gQ2WrDbP4= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= -github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= -github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= -github.com/spf13/afero v1.8.2 h1:xehSyVa0YnHWsJ49JFljMpg1HX19V6NDZ1fkm1Xznbo= -github.com/spf13/afero v1.8.2/go.mod h1:CtAatgMJh6bJEIs48Ay/FOnkljP3WeGUG0MC1RfAqwo= +github.com/spf13/afero v1.2.1/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= +github.com/spf13/afero v1.2.2 h1:5jhuqJyZCZf2JRofRvN/nIFgIWNzPa3/Vz8mYylgbWc= +github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= +github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= -github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU= -github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM= +github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= +github.com/spf13/cobra v1.1.1 h1:KfztREH0tPxJJ+geloSLaAkaPkr4ki2Er5quFV1TDo4= +github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -777,89 +486,82 @@ github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIn github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= -github.com/spf13/viper v1.13.0 h1:BWSJ/M+f+3nmdz9bxB+bWX28kkALN2ok11D0rSo8EJU= -github.com/spf13/viper v1.13.0/go.mod h1:Icm2xNL3/8uyh/wFuB1jI7TiTNKp8632Nwegu+zgdYw= -github.com/status-im/keycard-go v0.0.0-20190316090335-8537d3370df4/go.mod h1:RZLeN1LMWmRsyYjvAu+I6Dm9QmlDaIIt+Y+4Kd7Tp+Q= -github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570/go.mod h1:8OR4w3TdeIHIh1g6EMY5p0gVNOovcWC+1vpc7naMuAw= -github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3/go.mod h1:hpGUWaI9xL8pRQCTXQgocU38Qw1g0Us7n5PxxTwTCYU= +github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= +github.com/spf13/viper v1.6.3/go.mod h1:jUMtyi0/lB5yZH/FjyGAoH7IMNrIhlBf6pXZmbMDvzw= +github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= +github.com/spf13/viper v1.7.1 h1:pM5oEahlgWv/WnHXpgbKz7iLIxRf65tye2Ci+XFK5sk= +github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0 h1:M2gUjqZET1qApGOWNSnZ49BAIMX4F/1plDv3+l31EJ4= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48= +github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/subosito/gotenv v1.4.1 h1:jyEFiXpy21Wm81FBN71l9VoMMV8H8jG+qIK3GCpY6Qs= -github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= +github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= +github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= +github.com/swaggo/files v0.0.0-20190704085106-630677cd5c14 h1:PyYN9JH5jY9j6av01SpfRMb+1DWg/i3MbGOKPxJ2wjM= +github.com/swaggo/files v0.0.0-20190704085106-630677cd5c14/go.mod h1:gxQT6pBGRuIGunNf/+tSOB5OHvguWi8Tbt82WOkf35E= github.com/swaggo/files v0.0.0-20220610200504-28940afbdbfe h1:K8pHPVoTgxFJt1lXuIzzOX7zZhZFldJQK/CgKx9BFIc= github.com/swaggo/files v0.0.0-20220610200504-28940afbdbfe/go.mod h1:lKJPbtWzJ9JhsTN1k1gZgleJWY/cqq0psdoMmaThG3w= +github.com/swaggo/http-swagger v1.0.0 h1:ksYgVBCYmAaxFsGVGojlPROgYfiQQSllETTWMtHJHTo= +github.com/swaggo/http-swagger v1.0.0/go.mod h1:cKIcshBU9yEAnfWv6ZzVKSsEf8h5ozxB8/zHQWyOQ/8= github.com/swaggo/http-swagger v1.3.3 h1:Hu5Z0L9ssyBLofaama21iYaF2VbWyA8jdohaaCGpHsc= github.com/swaggo/http-swagger v1.3.3/go.mod h1:sE+4PjD89IxMPm77FnkDz0sdO+p5lbXzrVWT6OTVVGo= +github.com/swaggo/swag v1.7.0 h1:5bCA/MTLQoIqDXXyHfOpMeDvL9j68OY/udlK4pQoo4E= +github.com/swaggo/swag v1.7.0/go.mod h1:BdPIL73gvS9NBsdi7M1JOxLvlbfvNRaBP8m6WT6Aajo= github.com/swaggo/swag v1.8.1 h1:JuARzFX1Z1njbCGz+ZytBR15TFJwF2Q7fu8puJHhQYI= github.com/swaggo/swag v1.8.1/go.mod h1:ugemnJsPZm/kRwFUnzBlbHRd0JY9zE1M4F+uy2pAaPQ= -github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca h1:Ld/zXl5t4+D69SiV4JoN7kkfvJdOWlPpfxrzxpLMoUk= -github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca/go.mod h1:u2MKkTVTVJWe5D1rCvame8WqhBd88EuIwODJZ1VHCPM= +github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d h1:gZZadD8H+fF+n9CmNhYL1Y0dJB+kLOmKd7FbPJLeGHs= +github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d/go.mod h1:9OrXJhf154huy1nPWmuSrkgjPUtUNhA+Zmy+6AESzuA= +github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c h1:g+WoO5jjkqGAzHWCjJB1zZfXPIAaDpzXIEJ0eS6B5Ok= +github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c/go.mod h1:ahpPrc7HpcfEWDQRZEmnXMzHY03mLDYMCxeDzy46i+8= github.com/tendermint/btcd v0.1.1 h1:0VcxPfflS2zZ3RiOAHkBiFUcPvbtRj5O7zHmcJWHV7s= github.com/tendermint/btcd v0.1.1/go.mod h1:DC6/m53jtQzr/NFmMNEu0rxf18/ktVoVtMrnDD5pN+U= github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 h1:hqAk8riJvK4RMWx1aInLzndwxKalgi5rTqgfXxOxbEI= github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15/go.mod h1:z4YtwM70uOnk8h0pjJYlj3zdYwi9l03By6iAIF5j/Pk= -github.com/tendermint/go-amino v0.16.0 h1:GyhmgQKvqF82e2oZeuMSp9JTN0N09emoSZlb2lyGa2E= -github.com/tendermint/go-amino v0.16.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= -github.com/tendermint/tendermint v0.34.21 h1:UiGGnBFHVrZhoQVQ7EfwSOLuCtarqCSsRf8VrklqB7s= -github.com/tendermint/tendermint v0.34.21/go.mod h1:XDvfg6U7grcFTDx7VkzxnhazQ/bspGJAn4DZ6DcLLjQ= -github.com/tendermint/tm-db v0.6.7 h1:fE00Cbl0jayAoqlExN6oyQJ7fR/ZtoVOmvPJ//+shu8= -github.com/tendermint/tm-db v0.6.7/go.mod h1:byQDzFkZV1syXr/ReXS808NxA2xvyuuVgXOJ/088L6I= -github.com/tidwall/gjson v1.6.7/go.mod h1:zeFuBCIqD4sN/gmqBzZ4j7Jd6UcA2Fc56x7QFsv+8fI= -github.com/tidwall/match v1.0.3/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= -github.com/tidwall/pretty v1.0.2/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= -github.com/tidwall/sjson v1.1.4/go.mod h1:wXpKXu8CtDjKAZ+3DrKY5ROCorDFahq8l0tey/Lx1fg= -github.com/tinylib/msgp v1.1.5/go.mod h1:eQsjooMTnV42mHu917E26IogZ2930nFyBQdofk10Udg= +github.com/tendermint/go-amino v0.14.1/go.mod h1:i/UKE5Uocn+argJJBb12qTZsCDBcAYMbR92AaJVmKso= +github.com/tendermint/go-amino v0.15.1 h1:D2uk35eT4iTsvJd9jWIetzthE5C0/k2QmMFkCN+4JgQ= +github.com/tendermint/go-amino v0.15.1/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= +github.com/tendermint/iavl v0.14.0/go.mod h1:QmfViflFiXzxKLQE4tAUuWQHq+RSuQFxablW5oJZ6sE= +github.com/tendermint/iavl v0.14.3 h1:tuiUAqJdA3OOyPU/9P3pMYnAcd+OL7BUdzNiE3ytUwQ= +github.com/tendermint/iavl v0.14.3/go.mod h1:vHLYxU/zuxBmxxr1v+5Vnd/JzcIsyK17n9P9RDubPVU= +github.com/tendermint/tendermint v0.33.5/go.mod h1:0yUs9eIuuDq07nQql9BmI30FtYGcEC60Tu5JzB5IezM= +github.com/tendermint/tendermint v0.33.6/go.mod h1:0yUs9eIuuDq07nQql9BmI30FtYGcEC60Tu5JzB5IezM= +github.com/tendermint/tendermint v0.33.9 h1:rRKIfu5qAXX5f9bwX1oUXSZz/ALFJjDuivhkbGUQxiU= +github.com/tendermint/tendermint v0.33.9/go.mod h1:0yUs9eIuuDq07nQql9BmI30FtYGcEC60Tu5JzB5IezM= +github.com/tendermint/tm-db v0.5.1/go.mod h1:g92zWjHpCYlEvQXvy9M168Su8V1IBEeawpXVVBaK4f4= +github.com/tendermint/tm-db v0.5.2 h1:QG3IxQZBubWlr7kGQcYIavyTNmZRO+r//nENxoq0g34= +github.com/tendermint/tm-db v0.5.2/go.mod h1:VrPTx04QJhQ9d8TFUTc2GpPBvBf/U9vIdBIzkjBk7Lk= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/ttacon/chalk v0.0.0-20160626202418-22c06c80ed31/go.mod h1:onvgF043R+lC5RZ8IT9rBXDaEDnpnw/Cl+HFiw+v/7Q= -github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= -github.com/tyler-smith/go-bip39 v1.0.1-0.20181017060643-dbb3b84ba2ef/go.mod h1:sJ5fKU0s6JVwZjjcUEX2zFOnvq0ASQ2K9Zr6cf67kNs= -github.com/tyler-smith/go-bip39 v1.0.2/go.mod h1:sJ5fKU0s6JVwZjjcUEX2zFOnvq0ASQ2K9Zr6cf67kNs= -github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= -github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= -github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= -github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= -github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= +github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= -github.com/vmihailenco/msgpack/v5 v5.1.4/go.mod h1:C5gboKD0TJPqWDTVTtrQNfRbiBwHZGo8UTqP/9/XvLI= -github.com/vmihailenco/tagparser v0.1.2/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= -github.com/wsddn/go-ecdh v0.0.0-20161211032359-48726bab9208/go.mod h1:IotVbo4F+mw0EzQ08zFqg7pK3FebNXpaMsRy2RT+Ees= +github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= -github.com/ybbus/jsonrpc v2.1.2+incompatible/go.mod h1:XJrh1eMSzdIYFbM08flv0wp5G35eRniyeGut1z+LSiE= -github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/zondax/hid v0.9.0 h1:eiT3P6vNxAEVxXMw66eZUAAnU2zD33JBkfG/EnfAKl8= github.com/zondax/hid v0.9.0/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM= +go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= -go.etcd.io/bbolt v1.3.6 h1:/ecaJf0sk1l4l6V4awd65v2C3ILy7MSj+s/x1ADCIMU= -go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4= +go.etcd.io/bbolt v1.3.4 h1:hi1bXHMVrlQh6WwxAy+qZCV/SYIlqo+Ushwdpa4tAKg= +go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= @@ -871,68 +573,43 @@ go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190909091759-094676da4a83/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200406173513-056763e48d71/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de h1:ikNHVSjEfnvz6sxdSPCaPt572qowuyMDMJLLm3Db3ig= golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= -golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90 h1:Y/gsMcFOcR+6S6f3YeMKl5g+dZMEWqcz5Czj/GWYbkM= -golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= -golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56/go.mod h1:JhuoJpWY28nO4Vef9tZUw9qufEGTyX1+7lmHxV5q5G4= golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= -golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= -golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA= -golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= -golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= -golang.org/x/mobile v0.0.0-20200801112145-973feb4309de/go.mod h1:skQtrUTUwhdJvXM/2KKJzY8pDgNr9I/FOMqDVRPBUS4= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.1.1-0.20191209134235-331c550502dd/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= -golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181011144130-49bb7cea24b1/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -944,74 +621,41 @@ golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200421231249-e086a090c8fd/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200904194848-62affa334b73/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= -golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201207224615-747e23833adb h1:xj2oMIbduz83x7tzglytWT7spn6rP+9hvKjTpro6/pM= +golang.org/x/net v0.0.0-20201207224615-747e23833adb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/net v0.0.0-20220725212005-46097bf591d3/go.mod h1:AaygXjzTFtRAg2ttMY5RMuhpJ3cNnI0XpyFJD1iQRSM= -golang.org/x/net v0.0.0-20220927171203-f486391704dc h1:FxpXZdoBqT8RjqTy6i1E8nXHhW21wK7ptQ/EPIGxzPQ= -golang.org/x/net v0.0.0-20220927171203-f486391704dc/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= +golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 h1:HVyaeDAYux4pnY+D/SiwmLOR36ewZ4iGQIIrtnuCjFA= +golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220923202941-7f9b1623fab7 h1:ZrnxWX62AgTKOSagEqxvb3ffipvEDX2pl7E1TdqLqIc= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190130150945-aca44879d564/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1021,74 +665,30 @@ golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200420163511-1957bb5e6d1f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200824131525-c12d262b63d8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200923182605-d9f96fdee20d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201013132646-2da7054afaeb h1:HS9IzC4UFbpMBLQUDSQcU+ViVT1vdFCQVjdPVpTlZrs= +golang.org/x/sys v0.0.0-20201013132646-2da7054afaeb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210819135213-f52c844e1c1c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220907062415-87db552b00fd h1:AZeIEzg+8RCELJYq8w+ODLVxFgLMMigSwO/ffKPEd9U= -golang.org/x/sys v0.0.0-20220907062415-87db552b00fd/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.0.0-20220722155259-a9ba230a4035 h1:Q5284mrmYTpACcm+eAKjKJH48BBwSyfJqmmGDTtT8Vc= -golang.org/x/term v0.0.0-20220722155259-a9ba230a4035/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.4 h1:0YWbFKbhXG/wIiuHDSKpS0Iy7FSA+u45VtBMfQcFTTc= golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= @@ -1096,7 +696,11 @@ golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxb golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= @@ -1113,77 +717,31 @@ golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200117012304-6edc0a871e69/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= -golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= -golang.org/x/tools v0.0.0-20201022035929-9cf592e881e9/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= -golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.0.0-20200410194907-79a7a3126eef/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20201120155355-20be4ac4bd6e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201208062317-e652b2f42cc7 h1:2OSu5vYyX4LVqZAtqZXnFEcN26SDKIJYlEVIRl1tj8U= +golang.org/x/tools v0.0.0-20201208062317-e652b2f42cc7/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.10 h1:QjFRCZxdOhBJ/UNgnBZLbNV13DlbnK0quyivTnXJM20= +golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df h1:5Pf6pFKu98ODmgnpvkJ3kFUOQGGLIzLIkbzUHp47618= google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= -google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= -google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= -google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= -google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= -google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= @@ -1195,75 +753,50 @@ google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98 google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= -google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200324203455-a04cca1dde73/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= -google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210126160654-44e461bb6506/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20220725144611-272f38e5d71b h1:SfSkJugek6xm7lWywqth4r2iTrYLpD8lOj1nMIIhMNM= -google.golang.org/genproto v0.0.0-20220725144611-272f38e5d71b/go.mod h1:iHe1svFLAZg9VWz891+QbRMwUv9O/1Ww+/mngYeThbc= -google.golang.org/grpc v1.33.2 h1:EQyQC3sa8M+p6Ulc8yy9SWSS2GVwyRc83gAbG8lrl4o= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.22.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.28.1/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.30.0 h1:M5a8xTlYTxwMn5ZFkwhRabsygDY5G8TYLyQDBxJNAxE= +google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= -google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= -gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= -gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= -gopkg.in/olebedev/go-duktape.v3 v3.0.0-20200619000410-60c24ae608a6/go.mod h1:uAJfkITjFhyEEuUfm7bsmCZRbW5WRq8s9EY8HZ6hCns= +gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno= +gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/urfave/cli.v1 v1.20.0/go.mod h1:vuBzUtMdQeixQj8LVd+/98pzhxNGQoyuPBlsXHOQNO0= gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -1276,21 +809,16 @@ gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 h1:tQIYjPdBoyREyB9XMu+nnTclpTYkz2zFM+lzLJFO4gQ= gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= +honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -nhooyr.io/websocket v1.8.6 h1:s+C3xAMLwGmlI31Nyn/eAehUlZPwfYZu2JXM621Q5/k= -nhooyr.io/websocket v1.8.6/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= -pgregory.net/rapid v0.4.7/go.mod h1:UYpPVyjFHzYBGHIxLFoupi8vwk6rXNzRY9OMvVxFIOU= +honnef.co/go/tools v0.0.1-2020.1.6 h1:W18jzjh8mfPez+AwGLxmOImucz/IFjpNlrKVnaj2YVc= +honnef.co/go/tools v0.0.1-2020.1.6/go.mod h1:pyyisuGw24ruLjrr1ddx39WE0y9OooInRzEYLhQB2YY= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/modules/assets/auxiliaries/prototype.go b/modules/assets/auxiliaries/prototype.go new file mode 100644 index 000000000..31a4dee9b --- /dev/null +++ b/modules/assets/auxiliaries/prototype.go @@ -0,0 +1,13 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Auxiliaries { + return baseHelpers.NewAuxiliaries() +} diff --git a/modules/assets/auxiliaries/prototype_test.go b/modules/assets/auxiliaries/prototype_test.go new file mode 100644 index 000000000..1a6a58015 --- /dev/null +++ b/modules/assets/auxiliaries/prototype_test.go @@ -0,0 +1,29 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "reflect" + "testing" + + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Auxiliaries + }{ + + {"+ve", baseHelpers.NewAuxiliaries()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/assets/doc.go b/modules/assets/doc.go new file mode 100644 index 000000000..27f6eedb0 --- /dev/null +++ b/modules/assets/doc.go @@ -0,0 +1,5 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +// Package assets defines the assets' module. +package assets diff --git a/modules/assets/internal/block/block.go b/modules/assets/internal/block/block.go new file mode 100644 index 000000000..2b406cdb0 --- /dev/null +++ b/modules/assets/internal/block/block.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package block + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + abciTypes "github.com/tendermint/tendermint/abci/types" + + "github.com/AssetMantle/modules/schema/helpers" +) + +type block struct { + mapper helpers.Mapper + parameters helpers.Parameters +} + +var _ helpers.Block = (*block)(nil) + +func (block block) Begin(_ sdkTypes.Context, _ abciTypes.RequestBeginBlock) { + +} + +func (block block) End(_ sdkTypes.Context, _ abciTypes.RequestEndBlock) { + +} + +func Prototype() helpers.Block { + return block{} +} + +func (block block) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, _ ...interface{}) helpers.Block { + block.mapper, block.parameters = mapper, parameters + return block +} diff --git a/modules/assets/internal/common/codec.go b/modules/assets/internal/common/codec.go new file mode 100644 index 000000000..e194868f0 --- /dev/null +++ b/modules/assets/internal/common/codec.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package common + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + "github.com/AssetMantle/modules/utilities/module" +) + +var Codec *codec.Codec + +func init() { + Codec = module.RegisterCodec(key.Prototype, mappable.Prototype) +} diff --git a/modules/assets/internal/genesis/genesis.go b/modules/assets/internal/genesis/genesis.go deleted file mode 100644 index ab819a808..000000000 --- a/modules/assets/internal/genesis/genesis.go +++ /dev/null @@ -1,188 +0,0 @@ -package genesis - -import ( - "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ helpers.Genesis = (*Genesis)(nil) - -func (genesis Genesis) Default() helpers.Genesis { - return genesis.Initialize(genesis.GetMappableList(), genesis.GetParameterList()) -} - -func (genesis Genesis) Validate() error { - if len(genesis.ParameterList) != len(genesis.DefaultParameterList) { - return errors.InvalidParameter - } - - for _, parameter := range genesis.ParameterList { - var isPresent bool - for _, defaultParameter := range genesis.DefaultParameterList { - isPresent = false - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - isPresent = true - break - } - } - - if !isPresent { - return errors.InvalidParameter - } - - if Error := parameter.Validate(); Error != nil { - return Error - } - } - - _, Error := govalidator.ValidateStruct(genesis) - - return Error -} - -func (genesis Genesis) Import(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) { - for _, mappableValue := range genesis.MappableList { - mapper.Create(context, &mappableValue) - } - - for _, parameter := range genesis.ParameterList { - parameters.Mutate(context, ¶meter) - } -} - -func (genesis Genesis) Export(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) helpers.Genesis { - var mappableList []helpers.Mappable - - appendMappableList := func(mappable helpers.Mappable) bool { - mappableList = append(mappableList, mappable) - return false - } - mapper.Iterate(context, key.Prototype(), appendMappableList) - - for _, defaultParameter := range genesis.DefaultParameterList { - parameters = parameters.Fetch(context, defaultParameter.GetID()) - } - - return genesis.Initialize(mappableList, parameters.GetList()) -} - -func (genesis Genesis) LegacyAminoEncode() []byte { - legacyAminoCodec := codec.NewLegacyAmino() - bytes, Error := legacyAminoCodec.MarshalJSON(genesis) - if Error != nil { - panic(Error) - } - - return bytes -} -func (genesis Genesis) LegacyAminoDecode(byte []byte) helpers.Genesis { - var newGenesis Genesis - legacyAminoCodec := codec.NewLegacyAmino() - if Error := legacyAminoCodec.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(newGenesis.DefaultMappableList, newGenesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Encode(cdc codec.JSONMarshaler) []byte { - bytes, Error := cdc.MarshalJSON(&genesis) - if Error != nil { - panic(Error) - } - - return bytes -} - -func (genesis Genesis) Decode(cdc codec.JSONMarshaler, byte []byte) helpers.Genesis { - var newGenesis Genesis - if Error := cdc.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(newGenesis.DefaultMappableList, newGenesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Initialize(mappableList []helpers.Mappable, parameterList []types.Parameter) helpers.Genesis { - newParametersList := make([]dummy.DummyParameter, len(parameterList)) - for i, _ := range parameterList { - newParametersList[i] = *dummy.NewParameter(parameterList[i].GetID(), parameterList[i].GetData()) - } - newMappableList := make([]mappable.Asset, len(mappableList)) - for i, _ := range mappableList { - newMappableList[i] = *mappableList[i].(*mappable.Asset) - } - newParameter := dummy.Parameter.Mutate(dummy.Parameter.GetData()) - genesis.DefaultParameterList = []dummy.DummyParameter{*dummy.NewParameter(newParameter.GetID(), newParameter.GetData())} - if len(newMappableList) == 0 { - genesis.MappableList = genesis.DefaultMappableList - } else { - genesis.MappableList = newMappableList - } - - if len(newParametersList) == 0 { - genesis.ParameterList = genesis.DefaultParameterList - } else { - for _, defaultParameter := range genesis.DefaultParameterList { - for i, parameter := range newParametersList { - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - newParametersList[i] = *dummy.NewParameter(defaultParameter.Mutate(parameter.GetData()).GetID(), defaultParameter.Mutate(parameter.GetData()).GetData()) - } - } - } - genesis.ParameterList = newParametersList - } - - if Error := genesis.Validate(); Error != nil { - panic(Error) - } - - return &genesis -} - -func (genesis Genesis) GetParameterList() []types.Parameter { - newParameterList := make([]types.Parameter, len(genesis.ParameterList)) - for i, _ := range genesis.ParameterList { - newParameterList[i] = &genesis.ParameterList[i] - } - return newParameterList -} -func (genesis Genesis) GetMappableList() []helpers.Mappable { - newMappableList := make([]helpers.Mappable, len(genesis.MappableList)) - for i, _ := range genesis.MappableList { - newMappableList[i] = &genesis.MappableList[i] - } - return newMappableList -} - -func (genesis Genesis) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*helpers.Key)(nil), - &key.AssetID{}, - ) - registry.RegisterImplementations((*helpers.Mappable)(nil), - &mappable.Asset{}, - ) - registry.RegisterImplementations((*types.Parameter)(nil), - &dummy.DummyParameter{}, - ) - registry.RegisterImplementations((*helpers.Genesis)(nil), - &Genesis{}, - ) -} - -func NewGenesis(defaultMappableList []mappable.Asset, defaultParameterList []dummy.DummyParameter) *Genesis { - return &Genesis{ - DefaultMappableList: defaultMappableList, - DefaultParameterList: defaultParameterList, - MappableList: []mappable.Asset{}, - ParameterList: []dummy.DummyParameter{}, - } -} diff --git a/modules/assets/internal/genesis/genesis.pb.go b/modules/assets/internal/genesis/genesis.pb.go deleted file mode 100644 index c2febdf1c..000000000 --- a/modules/assets/internal/genesis/genesis.pb.go +++ /dev/null @@ -1,499 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/assets/internal/genesis/genesis.proto - -package genesis - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - mappable "github.com/persistenceOne/persistenceSDK/modules/assets/internal/mappable" - dummy "github.com/persistenceOne/persistenceSDK/modules/assets/internal/parameters/dummy" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Genesis struct { - DefaultMappableList []mappable.Asset `protobuf:"bytes,1,rep,name=defaultMappableList,proto3" json:"defaultMappableList"` - DefaultParameterList []dummy.DummyParameter `protobuf:"bytes,2,rep,name=defaultParameterList,proto3" json:"defaultParameterList"` - MappableList []mappable.Asset `protobuf:"bytes,3,rep,name=MappableList,proto3" json:"MappableList"` - ParameterList []dummy.DummyParameter `protobuf:"bytes,4,rep,name=ParameterList,proto3" json:"ParameterList"` -} - -func (m *Genesis) Reset() { *m = Genesis{} } -func (m *Genesis) String() string { return proto.CompactTextString(m) } -func (*Genesis) ProtoMessage() {} -func (*Genesis) Descriptor() ([]byte, []int) { - return fileDescriptor_db6a2b7960c1ed2d, []int{0} -} -func (m *Genesis) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Genesis) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Genesis.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Genesis) XXX_Merge(src proto.Message) { - xxx_messageInfo_Genesis.Merge(m, src) -} -func (m *Genesis) XXX_Size() int { - return m.Size() -} -func (m *Genesis) XXX_DiscardUnknown() { - xxx_messageInfo_Genesis.DiscardUnknown(m) -} - -var xxx_messageInfo_Genesis proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Genesis)(nil), "persistence_sdk.modules.assets.internal.genesis.Genesis") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/assets/internal/genesis/genesis.proto", fileDescriptor_db6a2b7960c1ed2d) -} - -var fileDescriptor_db6a2b7960c1ed2d = []byte{ - // 327 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x2d, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0x4f, 0x2c, 0x2e, 0x4e, 0x2d, 0x29, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, - 0xca, 0x4b, 0xcc, 0xd1, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0x86, 0xd1, 0x7a, 0x05, 0x45, - 0xf9, 0x25, 0xf9, 0x42, 0xfa, 0x68, 0xda, 0xf5, 0xa0, 0xda, 0xf5, 0x20, 0xda, 0xf5, 0x60, 0xda, - 0xf5, 0xa0, 0xda, 0xa4, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x7a, 0xf5, 0x41, 0x2c, 0x88, 0x31, - 0x52, 0x36, 0xc4, 0xba, 0x22, 0x37, 0xb1, 0xa0, 0x20, 0x31, 0x29, 0x27, 0x15, 0x22, 0x01, 0xd5, - 0xed, 0x41, 0xac, 0xee, 0x82, 0xc4, 0xa2, 0xc4, 0xdc, 0xd4, 0x92, 0xd4, 0xa2, 0x62, 0xfd, 0x94, - 0xd2, 0xdc, 0xdc, 0x4a, 0x84, 0x00, 0xc4, 0x24, 0xa5, 0x7b, 0xcc, 0x5c, 0xec, 0xee, 0x10, 0x97, - 0x0a, 0xe5, 0x73, 0x09, 0xa7, 0xa4, 0xa6, 0x25, 0x96, 0xe6, 0x94, 0xf8, 0x42, 0x2d, 0xf5, 0xc9, - 0x2c, 0x2e, 0x91, 0x60, 0x54, 0x60, 0xd6, 0xe0, 0x36, 0x32, 0xd7, 0x23, 0xd6, 0xe3, 0x30, 0x17, - 0xeb, 0x39, 0x82, 0x24, 0x9c, 0x58, 0x4e, 0xdc, 0x93, 0x67, 0x08, 0xc2, 0x66, 0xb2, 0x50, 0x13, - 0x23, 0x97, 0x08, 0x54, 0x3c, 0x00, 0xe6, 0x2e, 0xb0, 0x95, 0x4c, 0x60, 0x2b, 0x3d, 0x88, 0xb6, - 0x12, 0xe1, 0x4d, 0x3d, 0xb0, 0x37, 0xf5, 0x5c, 0x40, 0x24, 0xdc, 0x4c, 0xa8, 0x1b, 0xb0, 0xda, - 0x25, 0x94, 0xc8, 0xc5, 0x83, 0xe2, 0x5d, 0x66, 0x6a, 0x78, 0x17, 0xc5, 0x48, 0xa1, 0x12, 0x2e, - 0x5e, 0x54, 0xff, 0xb1, 0xd0, 0xc4, 0x7f, 0xa8, 0x96, 0x58, 0xb1, 0x74, 0x2c, 0x90, 0x67, 0x70, - 0x4a, 0x3a, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, - 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0x8f, 0xf4, 0xcc, 0x92, - 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0xe4, 0x44, 0xed, 0x9f, 0x97, 0x8a, 0xcc, 0x0d, 0x76, - 0xf1, 0x26, 0x94, 0x43, 0x92, 0xd8, 0xc0, 0x69, 0xc9, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x34, - 0x84, 0x67, 0xe2, 0x5b, 0x03, 0x00, 0x00, -} - -func (m *Genesis) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Genesis) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Genesis) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ParameterList) > 0 { - for iNdEx := len(m.ParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.MappableList) > 0 { - for iNdEx := len(m.MappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.DefaultParameterList) > 0 { - for iNdEx := len(m.DefaultParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.DefaultMappableList) > 0 { - for iNdEx := len(m.DefaultMappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultMappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Genesis) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.DefaultMappableList) > 0 { - for _, e := range m.DefaultMappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.DefaultParameterList) > 0 { - for _, e := range m.DefaultParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.MappableList) > 0 { - for _, e := range m.MappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ParameterList) > 0 { - for _, e := range m.ParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Genesis) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Genesis: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Genesis: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultMappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultMappableList = append(m.DefaultMappableList, mappable.Asset{}) - if err := m.DefaultMappableList[len(m.DefaultMappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultParameterList = append(m.DefaultParameterList, dummy.DummyParameter{}) - if err := m.DefaultParameterList[len(m.DefaultParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MappableList = append(m.MappableList, mappable.Asset{}) - if err := m.MappableList[len(m.MappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ParameterList = append(m.ParameterList, dummy.DummyParameter{}) - if err := m.ParameterList[len(m.ParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/assets/internal/genesis/prototype.go b/modules/assets/internal/genesis/prototype.go index e1af8cad6..3b9823fe4 100644 --- a/modules/assets/internal/genesis/prototype.go +++ b/modules/assets/internal/genesis/prototype.go @@ -1,16 +1,16 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package genesis import ( - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + "github.com/AssetMantle/modules/modules/assets/internal/parameters" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" ) func Prototype() helpers.Genesis { - return NewGenesis([]mappable.Asset{}, []dummy.DummyParameter{}) + return baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{}, parameters.Prototype().GetList()) } diff --git a/modules/assets/internal/genesis/prototype_test.go b/modules/assets/internal/genesis/prototype_test.go index f8524fb9f..f6aceebb0 100644 --- a/modules/assets/internal/genesis/prototype_test.go +++ b/modules/assets/internal/genesis/prototype_test.go @@ -1,14 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + package genesis import ( - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/stretchr/testify/require" "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + "github.com/AssetMantle/modules/modules/assets/internal/parameters" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" ) func TestPrototype(t *testing.T) { - require.Panics(t, func() { - require.Equal(t, Prototype(), NewGenesis([]helpers.Mappable{}, parameters.Prototype().GetList())) - }) + tests := []struct { + name string + want helpers.Genesis + }{ + + {"+ve", baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{}, parameters.Prototype().GetList())}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Panics(t, func() { + require.Equal(t, Prototype(), tt.want) + }) + }) + } } diff --git a/modules/assets/internal/key/assetID.pb.go b/modules/assets/internal/key/assetID.pb.go deleted file mode 100644 index d3a226d54..000000000 --- a/modules/assets/internal/key/assetID.pb.go +++ /dev/null @@ -1,367 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/assets/internal/key/assetID.proto - -package key - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - github_com_persistenceOne_persistenceSDK_schema_types "github.com/persistenceOne/persistenceSDK/schema/types" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type AssetID struct { - ClassificationID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,1,opt,name=classification_i_d,json=classificationID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"classification_i_d"` - HashID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,2,opt,name=hash_i_d,json=hashID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"hash_i_d"` -} - -func (m *AssetID) Reset() { *m = AssetID{} } -func (*AssetID) ProtoMessage() {} -func (*AssetID) Descriptor() ([]byte, []int) { - return fileDescriptor_ce33edb771165453, []int{0} -} -func (m *AssetID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AssetID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AssetID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *AssetID) XXX_Merge(src proto.Message) { - xxx_messageInfo_AssetID.Merge(m, src) -} -func (m *AssetID) XXX_Size() int { - return m.Size() -} -func (m *AssetID) XXX_DiscardUnknown() { - xxx_messageInfo_AssetID.DiscardUnknown(m) -} - -var xxx_messageInfo_AssetID proto.InternalMessageInfo - -func init() { - proto.RegisterType((*AssetID)(nil), "persistence_sdk.modules.assets.internal.key.AssetID") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/assets/internal/key/assetID.proto", fileDescriptor_ce33edb771165453) -} - -var fileDescriptor_ce33edb771165453 = []byte{ - // 264 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x2c, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0x4f, 0x2c, 0x2e, 0x4e, 0x2d, 0x29, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, - 0xca, 0x4b, 0xcc, 0xd1, 0xcf, 0x4e, 0xad, 0x84, 0x88, 0x79, 0xba, 0xe8, 0x15, 0x14, 0xe5, 0x97, - 0xe4, 0x0b, 0x69, 0xa3, 0x69, 0xd5, 0x83, 0x6a, 0xd5, 0x83, 0x68, 0xd5, 0x83, 0x69, 0xd5, 0xcb, - 0x4e, 0xad, 0x94, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0xeb, 0xd3, 0x07, 0xb1, 0x20, 0x46, 0x28, - 0xdd, 0x66, 0xe4, 0x62, 0x77, 0x84, 0x18, 0x2a, 0x94, 0xc7, 0x25, 0x94, 0x9c, 0x93, 0x58, 0x5c, - 0x9c, 0x99, 0x96, 0x99, 0x9c, 0x58, 0x92, 0x99, 0x9f, 0x17, 0x9f, 0x19, 0x9f, 0x22, 0xc1, 0xa8, - 0xc0, 0xa8, 0xc1, 0xe9, 0xe4, 0x70, 0xe2, 0x9e, 0x3c, 0xc3, 0xad, 0x7b, 0xf2, 0x16, 0xe9, 0x99, - 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x48, 0xb6, 0xfb, 0xe7, 0xa5, 0x22, 0x73, - 0x83, 0x5d, 0xbc, 0xf5, 0x8b, 0x93, 0x33, 0x52, 0x73, 0x13, 0xf5, 0x4b, 0x2a, 0x0b, 0x52, 0x8b, - 0xf5, 0x3c, 0x5d, 0x82, 0x04, 0x50, 0xcd, 0xf6, 0x74, 0x11, 0x8a, 0xe2, 0xe2, 0xc8, 0x48, 0x2c, - 0xce, 0x00, 0xdb, 0xc2, 0x44, 0x25, 0x5b, 0xd8, 0x40, 0x26, 0x7a, 0xba, 0x58, 0xb1, 0xcc, 0x58, - 0x20, 0xcf, 0xe0, 0x14, 0x77, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, - 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x2e, - 0x44, 0xdb, 0x80, 0x27, 0x3a, 0x92, 0xd8, 0xc0, 0x81, 0x68, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, - 0xd7, 0x6d, 0x89, 0x7a, 0xc4, 0x01, 0x00, 0x00, -} - -func (m *AssetID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AssetID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AssetID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.HashID.Size() - i -= size - if _, err := m.HashID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintAssetID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.ClassificationID.Size() - i -= size - if _, err := m.ClassificationID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintAssetID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintAssetID(dAtA []byte, offset int, v uint64) int { - offset -= sovAssetID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *AssetID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ClassificationID.Size() - n += 1 + l + sovAssetID(uint64(l)) - l = m.HashID.Size() - n += 1 + l + sovAssetID(uint64(l)) - return n -} - -func sovAssetID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozAssetID(x uint64) (n int) { - return sovAssetID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *AssetID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAssetID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AssetID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AssetID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAssetID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAssetID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthAssetID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HashID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAssetID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthAssetID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthAssetID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HashID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAssetID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAssetID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipAssetID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAssetID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAssetID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAssetID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthAssetID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupAssetID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthAssetID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthAssetID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowAssetID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupAssetID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/assets/internal/key/key_test.go b/modules/assets/internal/key/key_test.go new file mode 100644 index 000000000..990722dd7 --- /dev/null +++ b/modules/assets/internal/key/key_test.go @@ -0,0 +1,190 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package key + +import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/assets/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +var ( + immutables = baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables = baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID = baseIDs.NewClassificationID(immutables, mutables) + testAssetID = baseIDs.NewAssetID(classificationID, immutables) +) + +func TestNewKey(t *testing.T) { + type args struct { + assetID ids.AssetID + } + tests := []struct { + name string + args args + want helpers.Key + }{ + {"+ve", args{testAssetID}, key{testAssetID}}, + {"+ve with nil", args{}, key{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewKey(tt.args.assetID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewKey() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Key + }{ + {"+ve", key{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_keyFromInterface(t *testing.T) { + type args struct { + i interface{} + } + tests := []struct { + name string + args args + want key + wantErr bool + }{ + {"+ve", args{key{testAssetID}}, key{testAssetID}, false}, + {"+ve with nil", args{key{}}, key{}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := keyFromInterface(tt.args.i) + if (err != nil) != tt.wantErr { + t.Errorf("keyFromInterface() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("keyFromInterface() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_Equals(t *testing.T) { + type fields struct { + AssetID ids.AssetID + } + type args struct { + compareKey helpers.Key + } + tests := []struct { + name string + fields fields + args args + want bool + }{ + {"+ve", fields{testAssetID}, args{key{testAssetID}}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key := key{ + AssetID: tt.fields.AssetID, + } + if got := key.Equals(tt.args.compareKey); got != tt.want { + t.Errorf("Equals() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_GenerateStoreKeyBytes(t *testing.T) { + type fields struct { + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{testAssetID}, module.StoreKeyPrefix.GenerateStoreKey(key{testAssetID}.Bytes())}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key := key{ + AssetID: tt.fields.AssetID, + } + if got := key.GenerateStoreKeyBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GenerateStoreKeyBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_IsPartial(t *testing.T) { + type fields struct { + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + want bool + }{ + {"+ve", fields{key{testAssetID}}, false}, + {"+ve", fields{key{baseIDs.PrototypeAssetID()}}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key := key{ + AssetID: tt.fields.AssetID, + } + if got := key.IsPartial(); got != tt.want { + t.Errorf("IsPartial() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_RegisterCodec(t *testing.T) { + type fields struct { + AssetID ids.AssetID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testAssetID}, args{codec.New()}}, + {"+ve", fields{baseIDs.PrototypeAssetID()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ke := key{ + AssetID: tt.fields.AssetID, + } + ke.RegisterCodec(tt.args.codec) + }) + } +} diff --git a/modules/assets/internal/key/utilities.go b/modules/assets/internal/key/utilities.go deleted file mode 100644 index 3c9e03528..000000000 --- a/modules/assets/internal/key/utilities.go +++ /dev/null @@ -1,46 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - "strings" - - "github.com/persistenceOne/persistenceSDK/schema/helpers" - - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -func readAssetID(assetIDString string) AssetID { - idList := strings.Split(assetIDString, constants.FirstOrderCompositeIDSeparator) - if len(idList) == 2 { - return AssetID{ - ClassificationID: base.NewID(idList[0]), - HashID: base.NewID(idList[1]), - } - } - - return AssetID{ClassificationID: base.NewID(""), HashID: base.NewID("")} -} -func assetIDFromInterface(i interface{}) AssetID { - switch value := i.(type) { - case AssetID: - return value - case types.ID: - return assetIDFromInterface(readAssetID(value.String())) - default: - panic(i) - } -} - -func ReadClassificationID(assetID types.ID) types.ID { - return assetIDFromInterface(assetID).ClassificationID -} - -func FromID(id types.ID) helpers.Key { - return assetIDFromInterface(id) -} diff --git a/modules/assets/internal/mappable/asset.pb.go b/modules/assets/internal/mappable/asset.pb.go deleted file mode 100644 index a8750f483..000000000 --- a/modules/assets/internal/mappable/asset.pb.go +++ /dev/null @@ -1,417 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/assets/internal/mappable/asset.proto - -package mappable - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base1 "github.com/persistenceOne/persistenceSDK/schema/traits/base" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Asset struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - HasImmutables base1.HasImmutables `protobuf:"bytes,2,opt,name=has_immutables,json=hasImmutables,proto3" json:"has_immutables"` - HasMutables base1.HasMutables `protobuf:"bytes,3,opt,name=has_mutables,json=hasMutables,proto3" json:"has_mutables"` -} - -func (m *Asset) Reset() { *m = Asset{} } -func (m *Asset) String() string { return proto.CompactTextString(m) } -func (*Asset) ProtoMessage() {} -func (*Asset) Descriptor() ([]byte, []int) { - return fileDescriptor_70d520ea1f8f3c5c, []int{0} -} -func (m *Asset) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Asset) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Asset.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Asset) XXX_Merge(src proto.Message) { - xxx_messageInfo_Asset.Merge(m, src) -} -func (m *Asset) XXX_Size() int { - return m.Size() -} -func (m *Asset) XXX_DiscardUnknown() { - xxx_messageInfo_Asset.DiscardUnknown(m) -} - -var xxx_messageInfo_Asset proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Asset)(nil), "persistence_sdk.modules.assets.internal.mappable.Asset") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/assets/internal/mappable/asset.proto", fileDescriptor_70d520ea1f8f3c5c) -} - -var fileDescriptor_70d520ea1f8f3c5c = []byte{ - // 333 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x29, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0x4f, 0x2c, 0x2e, 0x4e, 0x2d, 0x29, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, - 0xca, 0x4b, 0xcc, 0xd1, 0xcf, 0x4d, 0x2c, 0x28, 0x48, 0x4c, 0xca, 0x49, 0x85, 0x48, 0xe8, 0x15, - 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0x19, 0xa0, 0xe9, 0xd6, 0x83, 0xea, 0xd6, 0x83, 0xe8, 0xd6, 0x83, - 0xe9, 0xd6, 0x83, 0xe9, 0x96, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x6b, 0xd6, 0x07, 0xb1, 0x20, - 0xe6, 0x48, 0x99, 0xa1, 0xbb, 0xa2, 0x38, 0x39, 0x23, 0x35, 0x37, 0x51, 0xbf, 0xa4, 0x28, 0x31, - 0xb3, 0xa4, 0x58, 0x3f, 0x29, 0xb1, 0x38, 0x55, 0x3f, 0x23, 0xb1, 0xd8, 0x33, 0x37, 0xb7, 0xb4, - 0x04, 0x64, 0x4c, 0x31, 0x54, 0x9f, 0x09, 0x71, 0xfa, 0x7c, 0x51, 0x75, 0x69, 0xe1, 0xd2, 0x55, - 0x59, 0x90, 0x0a, 0xd5, 0x94, 0x99, 0x02, 0x51, 0xab, 0xd4, 0xca, 0xc4, 0xc5, 0xea, 0x08, 0xf2, - 0x8c, 0x90, 0x0d, 0x17, 0x73, 0x66, 0x7c, 0x8a, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0xaa, - 0x1e, 0xba, 0xcf, 0x21, 0x66, 0xe8, 0x81, 0xcd, 0xd0, 0x03, 0x99, 0xa1, 0xe7, 0xe9, 0xe2, 0xc4, - 0x72, 0xe2, 0x9e, 0x3c, 0x43, 0x10, 0x53, 0xa6, 0x8b, 0x50, 0x1c, 0x17, 0x5f, 0x46, 0x62, 0x71, - 0x7c, 0x26, 0xdc, 0x07, 0x12, 0x4c, 0x60, 0x83, 0x0c, 0x71, 0x1a, 0x04, 0xf6, 0x02, 0xc4, 0x24, - 0x0f, 0x64, 0xaf, 0x43, 0x0d, 0xe5, 0x45, 0x09, 0x0f, 0xa1, 0x08, 0x2e, 0x1e, 0x90, 0xf9, 0x70, - 0xd3, 0x99, 0xc1, 0xa6, 0xeb, 0x13, 0x69, 0xba, 0x2f, 0xaa, 0xd9, 0xdc, 0x48, 0x61, 0x66, 0xc5, - 0xd2, 0xb1, 0x40, 0x9e, 0xc1, 0x29, 0xf9, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, - 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, - 0xa2, 0x3c, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x91, 0x6c, 0xf3, - 0xcf, 0x4b, 0x45, 0xe6, 0x06, 0xbb, 0x78, 0x13, 0x4c, 0x5a, 0x49, 0x6c, 0xe0, 0x30, 0x37, 0x06, - 0x04, 0x00, 0x00, 0xff, 0xff, 0x82, 0x45, 0xf6, 0x56, 0x95, 0x02, 0x00, 0x00, -} - -func (m *Asset) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Asset) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Asset) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.HasMutables.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAsset(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.HasImmutables.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAsset(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAsset(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintAsset(dAtA []byte, offset int, v uint64) int { - offset -= sovAsset(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Asset) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovAsset(uint64(l)) - l = m.HasImmutables.Size() - n += 1 + l + sovAsset(uint64(l)) - l = m.HasMutables.Size() - n += 1 + l + sovAsset(uint64(l)) - return n -} - -func sovAsset(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozAsset(x uint64) (n int) { - return sovAsset(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Asset) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAsset - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Asset: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Asset: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAsset - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAsset - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAsset - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HasImmutables", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAsset - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAsset - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAsset - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HasImmutables.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HasMutables", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAsset - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAsset - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAsset - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HasMutables.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAsset(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAsset - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipAsset(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAsset - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAsset - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAsset - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthAsset - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupAsset - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthAsset - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthAsset = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowAsset = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupAsset = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/assets/internal/mappable/mappable.go b/modules/assets/internal/mappable/mappable.go new file mode 100644 index 000000000..8f040bcf8 --- /dev/null +++ b/modules/assets/internal/mappable/mappable.go @@ -0,0 +1,37 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mappable + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +type mappable struct { + documents.Asset +} + +var _ helpers.Mappable = (*mappable)(nil) + +func (asset mappable) GetKey() helpers.Key { + return key.NewKey(baseIDs.NewAssetID(asset.GetClassificationID(), asset.GetImmutables())) +} +func (mappable) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, mappable{}) +} + +func Prototype() helpers.Mappable { + return mappable{} +} + +func NewMappable(asset documents.Asset) helpers.Mappable { + return mappable{ + Asset: asset, + } +} diff --git a/modules/assets/internal/mappable/mappable_test.go b/modules/assets/internal/mappable/mappable_test.go new file mode 100644 index 000000000..6856a6a3f --- /dev/null +++ b/modules/assets/internal/mappable/mappable_test.go @@ -0,0 +1,125 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mappable + +import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + baseData "github.com/AssetMantle/modules/schema/data/base" + documentsSchema "github.com/AssetMantle/modules/schema/documents" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/qualified" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +func createTestInput() (ids.ClassificationID, qualified.Immutables, qualified.Mutables, mappable) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + testMappable := mappable{Asset: baseDocuments.NewAsset(classificationID, immutables, mutables)} + return classificationID, immutables, mutables, testMappable +} + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Mappable + }{ + {"+ve", mappable{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestNewMappable(t *testing.T) { + classificationID, immutables, mutables, testMappable := createTestInput() + type args struct { + Asset documentsSchema.Asset + } + tests := []struct { + name string + args args + want documentsSchema.Asset + }{ + {"+ve", args{baseDocuments.NewAsset(classificationID, immutables, mutables)}, testMappable}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewMappable(tt.args.Asset); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewAsset() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_mappable_GetKey(t *testing.T) { + _, _, _, testMappable := createTestInput() + type fields struct { + Document mappable + } + tests := []struct { + name string + fields fields + want helpers.Key + wantPanic bool + }{ + {"+ve", fields{testMappable}, key.NewKey(baseIDs.NewAssetID(mappable{testMappable}.GetClassificationID(), mappable{testMappable}.GetImmutables())), false}, + {"panic case nil", fields{mappable{nil}}, nil, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + asset := mappable{ + Asset: tt.fields.Document, + } + if tt.wantPanic { + require.Panics(t, func() { + asset.GetKey() + }) + } else if got := asset.GetKey(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetKey() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_mappable_RegisterCodec(t *testing.T) { + _, _, _, testMappable := createTestInput() + type fields struct { + Document mappable + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testMappable}, args{codec: codec.New()}}, + {"+ve nil", fields{mappable{nil}}, args{codec: codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + as := mappable{ + Asset: tt.fields.Document, + } + as.RegisterCodec(tt.args.codec) + }) + } +} diff --git a/modules/assets/internal/mappable/prototype.go b/modules/assets/internal/mappable/prototype.go deleted file mode 100644 index 2e0f791df..000000000 --- a/modules/assets/internal/mappable/prototype.go +++ /dev/null @@ -1,14 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import ( - "github.com/persistenceOne/persistenceSDK/schema/helpers" -) - -func Prototype() helpers.Mappable { - return &Asset{} -} diff --git a/modules/assets/internal/mapper/prototype.go b/modules/assets/internal/mapper/prototype.go new file mode 100644 index 000000000..a1c726907 --- /dev/null +++ b/modules/assets/internal/mapper/prototype.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mapper + +import ( + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Mapper { + return baseHelpers.NewMapper(key.Prototype, mappable.Prototype) +} diff --git a/modules/assets/internal/mapper/prototype_test.go b/modules/assets/internal/mapper/prototype_test.go index d8710fd69..899235e97 100644 --- a/modules/assets/internal/mapper/prototype_test.go +++ b/modules/assets/internal/mapper/prototype_test.go @@ -4,10 +4,11 @@ package mapper import ( - "github.com/AssetMantle/modules/schema/helpers" "reflect" "testing" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/modules/assets/internal/key" "github.com/AssetMantle/modules/modules/assets/internal/mappable" baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" diff --git a/modules/assets/internal/module/constants.go b/modules/assets/internal/module/constants.go new file mode 100644 index 000000000..58dcc8c8d --- /dev/null +++ b/modules/assets/internal/module/constants.go @@ -0,0 +1,12 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package module + +import ( + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +const Name = "assets" + +var StoreKeyPrefix = constants.AssetsStoreKeyPrefix diff --git a/modules/assets/internal/parameters/dummy/constants.go b/modules/assets/internal/parameters/dummy/constants.go new file mode 100644 index 000000000..c60667817 --- /dev/null +++ b/modules/assets/internal/parameters/dummy/constants.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package dummy + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +var ID = baseIDs.NewStringID("dummy") +var DefaultData = baseData.NewDecData(sdkTypes.SmallestDec()) diff --git a/modules/assets/internal/parameters/dummy/parameter.go b/modules/assets/internal/parameters/dummy/parameter.go index fde478cc8..5ffc0eaf5 100644 --- a/modules/assets/internal/parameters/dummy/parameter.go +++ b/modules/assets/internal/parameters/dummy/parameter.go @@ -1,64 +1,10 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "encoding/json" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" ) -var _ types.Parameter = (*DummyParameter)(nil) - -func (dummyParameter DummyParameter) String() string { - bytes, Error := json.Marshal(dummyParameter) - if Error != nil { - return Error.Error() - } - return string(bytes) -} - -func (dummyParameter DummyParameter) Equal(compareParameter types.Parameter) bool { - if compareParameter == nil { - return false - } - return dummyParameter.Data.Compare(compareParameter.GetData()) == 0 -} - -func (dummyParameter DummyParameter) Validate() error { - return validator(dummyParameter) -} - -func (dummyParameter DummyParameter) GetID() types.ID { - return &dummyParameter.ID -} - -func (dummyParameter DummyParameter) GetData() types.Data { - return &dummyParameter.Data -} - -func (dummyParameter DummyParameter) GetValidator() func(interface{}) error { - return validator -} - -func (dummyParameter DummyParameter) Mutate(data types.Data) types.Parameter { - decData, _ := data.AsDec() - dummyParameter.Data = *base.NewDummyDecData(decData) - return &dummyParameter -} - -func (DummyParameter) RegisterImplementation(interfaceRegistry codecTypes.InterfaceRegistry) { - interfaceRegistry.RegisterImplementations((*types.Parameter)(nil), &DummyParameter{}) -} - -func NewParameter(id types.ID, data types.Data) *DummyParameter { - decData, _ := data.AsDec() - return &DummyParameter{ - ID: *base.NewID(id.String()), - Data: *base.NewDummyDecData(decData), - } -} +var Parameter = baseTypes.NewParameter(ID, DefaultData, validator) diff --git a/modules/assets/internal/parameters/dummy/parameter.pb.go b/modules/assets/internal/parameters/dummy/parameter.pb.go deleted file mode 100644 index 27197b596..000000000 --- a/modules/assets/internal/parameters/dummy/parameter.pb.go +++ /dev/null @@ -1,367 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/assets/internal/parameters/dummy/parameter.proto - -package dummy - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type DummyParameter struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - Data base.DecData `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` -} - -func (m *DummyParameter) Reset() { *m = DummyParameter{} } -func (*DummyParameter) ProtoMessage() {} -func (*DummyParameter) Descriptor() ([]byte, []int) { - return fileDescriptor_778508db2e6703a7, []int{0} -} -func (m *DummyParameter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DummyParameter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DummyParameter.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DummyParameter) XXX_Merge(src proto.Message) { - xxx_messageInfo_DummyParameter.Merge(m, src) -} -func (m *DummyParameter) XXX_Size() int { - return m.Size() -} -func (m *DummyParameter) XXX_DiscardUnknown() { - xxx_messageInfo_DummyParameter.DiscardUnknown(m) -} - -var xxx_messageInfo_DummyParameter proto.InternalMessageInfo - -func init() { - proto.RegisterType((*DummyParameter)(nil), "persistence_sdk.modules.assets.internal.parameters.dummy.DummyParameter") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/assets/internal/parameters/dummy/parameter.proto", fileDescriptor_778508db2e6703a7) -} - -var fileDescriptor_778508db2e6703a7 = []byte{ - // 304 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xf2, 0x28, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0x4f, 0x2c, 0x2e, 0x4e, 0x2d, 0x29, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, - 0xca, 0x4b, 0xcc, 0xd1, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x4d, 0x2d, 0x49, 0x2d, 0x2a, 0xd6, 0x4f, - 0x29, 0xcd, 0xcd, 0xad, 0x44, 0x08, 0xe8, 0x15, 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0x59, 0xa0, 0x99, - 0xa4, 0x07, 0x35, 0x49, 0x0f, 0x62, 0x92, 0x1e, 0xcc, 0x24, 0x3d, 0x84, 0x49, 0x7a, 0x60, 0x93, - 0xa4, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x86, 0xe8, 0x83, 0x58, 0x10, 0xf3, 0xa4, 0xf4, 0xd1, - 0x5d, 0x56, 0x9c, 0x9c, 0x91, 0x9a, 0x9b, 0xa8, 0x5f, 0x52, 0x59, 0x90, 0x5a, 0xac, 0x9f, 0x94, - 0x58, 0x9c, 0xaa, 0x9f, 0x92, 0x9a, 0xec, 0x92, 0x58, 0x92, 0x08, 0xd5, 0xa0, 0x45, 0x58, 0x43, - 0x66, 0x0a, 0x44, 0xad, 0xd2, 0x3c, 0x46, 0x2e, 0x3e, 0x17, 0x90, 0xe5, 0x01, 0x30, 0xc7, 0x08, - 0xd9, 0x70, 0x31, 0x67, 0xc6, 0xa7, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x1b, 0xa9, 0xea, 0xa1, - 0xfb, 0x06, 0x62, 0x98, 0x1e, 0xd8, 0x30, 0x3d, 0x90, 0x61, 0x7a, 0x9e, 0x2e, 0x4e, 0x2c, 0x27, - 0xee, 0xc9, 0x33, 0x04, 0x31, 0x65, 0xba, 0x08, 0xb9, 0x70, 0xb1, 0xa4, 0x24, 0x96, 0x24, 0x4a, - 0x30, 0x81, 0xb5, 0x6b, 0x11, 0xa1, 0xdd, 0x05, 0xe2, 0x78, 0xa8, 0x19, 0x60, 0xdd, 0x56, 0x1c, - 0x1d, 0x0b, 0xe4, 0x19, 0x66, 0x2c, 0x90, 0x67, 0x70, 0xca, 0x3e, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, - 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, - 0xc6, 0x63, 0x39, 0x86, 0xa8, 0xc0, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, - 0xe4, 0x20, 0xf2, 0xcf, 0x4b, 0x45, 0xe6, 0x06, 0xbb, 0x78, 0x13, 0x1d, 0x95, 0x49, 0x6c, 0xe0, - 0x40, 0x31, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x92, 0xb1, 0xd5, 0x6a, 0x0d, 0x02, 0x00, 0x00, -} - -func (m *DummyParameter) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DummyParameter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DummyParameter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Data.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintParameter(dAtA []byte, offset int, v uint64) int { - offset -= sovParameter(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *DummyParameter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovParameter(uint64(l)) - l = m.Data.Size() - n += 1 + l + sovParameter(uint64(l)) - return n -} - -func sovParameter(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParameter(x uint64) (n int) { - return sovParameter(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *DummyParameter) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DummyParameter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DummyParameter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParameter(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParameter - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParameter(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParameter - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParameter - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParameter - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParameter = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParameter = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParameter = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/assets/internal/parameters/dummy/prototype.go b/modules/assets/internal/parameters/dummy/prototype.go deleted file mode 100644 index b390a673e..000000000 --- a/modules/assets/internal/parameters/dummy/prototype.go +++ /dev/null @@ -1,3 +0,0 @@ -package dummy - -var Parameter = NewParameter(ID, DefaultData) diff --git a/modules/assets/internal/parameters/dummy/validator.go b/modules/assets/internal/parameters/dummy/validator.go index cc0d80a52..2bb100018 100644 --- a/modules/assets/internal/parameters/dummy/validator.go +++ b/modules/assets/internal/parameters/dummy/validator.go @@ -1,32 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/parameters" ) func validator(i interface{}) error { switch value := i.(type) { - case DummyParameter: - data, Error := value.GetData().AsDec() - if Error != nil || value.GetID().Compare(ID) != 0 || data.IsNegative() { - return errors.InvalidParameter + case parameters.Parameter: + if value.GetID().Compare(ID) != 0 || value.GetData().(data.DecData).Get().IsNegative() { + return constants.InvalidParameter } return nil - case types.Data: - data, Error := value.AsDec() - if Error != nil || data.IsNegative() { - return errors.InvalidParameter + case data.DecData: + if value.Get().IsNegative() { + return constants.InvalidParameter } return nil default: - return errors.IncorrectFormat + return constants.IncorrectFormat } } diff --git a/modules/assets/internal/parameters/prototype.go b/modules/assets/internal/parameters/prototype.go new file mode 100644 index 000000000..b876742af --- /dev/null +++ b/modules/assets/internal/parameters/prototype.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package parameters + +import ( + "github.com/AssetMantle/modules/modules/assets/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Parameters { + return baseHelpers.NewParameters(dummy.Parameter) +} diff --git a/modules/assets/internal/parameters/prototype_test.go b/modules/assets/internal/parameters/prototype_test.go index 3d6d2afcc..84a9beffe 100644 --- a/modules/assets/internal/parameters/prototype_test.go +++ b/modules/assets/internal/parameters/prototype_test.go @@ -4,10 +4,11 @@ package parameters import ( - "github.com/AssetMantle/modules/schema/helpers" "reflect" "testing" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/modules/assets/internal/parameters/dummy" baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" ) diff --git a/modules/assets/internal/queries/asset/grpc_query.go b/modules/assets/internal/queries/asset/grpc_query.go deleted file mode 100644 index 2bb76d4b3..000000000 --- a/modules/assets/internal/queries/asset/grpc_query.go +++ /dev/null @@ -1,29 +0,0 @@ -package asset - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/key" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type queryServer struct { - queryKeeper -} - -var _ QueryServer = queryServer{} - -func (queryServer queryServer) Enquire(ctx context.Context, queryRequest *QueryRequest) (*QueryResponse, error) { - cntx := sdkTypes.UnwrapSDKContext(ctx) - - keyr := key.FromID(base.NewID(queryRequest.AssetID.String())) - - collection := queryServer.queryKeeper.mapper.NewCollection(cntx) - response := newQueryResponse(collection.Fetch(keyr), nil) - return &response, response.GetError() - -} - -func NewQueryServerImpl(keeper queryKeeper) QueryServer { - return &queryServer{keeper} -} diff --git a/modules/assets/internal/queries/asset/keeper.go b/modules/assets/internal/queries/asset/keeper.go new file mode 100644 index 000000000..074496134 --- /dev/null +++ b/modules/assets/internal/queries/asset/keeper.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package asset + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/schema/helpers" +) + +type queryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.QueryKeeper = (*queryKeeper)(nil) + +func (queryKeeper queryKeeper) Enquire(context sdkTypes.Context, queryRequest helpers.QueryRequest) helpers.QueryResponse { + return newQueryResponse(queryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(queryRequestFromInterface(queryRequest).AssetID)), nil) +} + +func (queryKeeper queryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + queryKeeper.mapper = mapper + return queryKeeper +} + +func keeperPrototype() helpers.QueryKeeper { + return queryKeeper{} +} diff --git a/modules/assets/internal/queries/asset/keeper_test.go b/modules/assets/internal/queries/asset/keeper_test.go new file mode 100644 index 000000000..b21495c4c --- /dev/null +++ b/modules/assets/internal/queries/asset/keeper_test.go @@ -0,0 +1,161 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package asset + +import ( + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + "github.com/AssetMantle/modules/modules/assets/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + + "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/helpers" +) + +type TestKeepers struct { + AssetKeeper helpers.QueryKeeper +} + +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + keepers := TestKeepers{ + AssetKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.QueryKeeper), + } + + return context, keepers, Mapper, Parameters +} + +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryKeeper + }{ + {"+ve", queryKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryKeeper_Enquire(t *testing.T) { + context, keepers, Mapper, _ := createTestInput(t) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + testAssetID := baseIDs.NewAssetID(classificationID, immutables) + keepers.AssetKeeper.(queryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(base.NewAsset(classificationID, immutables, mutables))) + type fields struct { + mapper helpers.Mapper + } + type args struct { + context types.Context + queryRequest helpers.QueryRequest + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryResponse + }{ + {"+ve", fields{Mapper}, args{context, newQueryRequest(testAssetID)}, newQueryResponse(keepers.AssetKeeper.(queryKeeper).mapper.NewCollection(context).Fetch(key.NewKey(testAssetID)), nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryKeeper := queryKeeper{ + mapper: tt.fields.mapper, + } + if got := queryKeeper.Enquire(tt.args.context, tt.args.queryRequest); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Enquire() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + in2 []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + + {"+ve with nil", fields{}, args{}, queryKeeper{}}, + {"+ve", fields{Mapper}, args{Mapper, Parameters, []interface{}{}}, queryKeeper{Mapper}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryKeeper := queryKeeper{ + mapper: tt.fields.mapper, + } + if got := queryKeeper.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/assets/internal/queries/asset/query.go b/modules/assets/internal/queries/asset/query.go index 6120f8ca6..e0e38e507 100644 --- a/modules/assets/internal/queries/asset/query.go +++ b/modules/assets/internal/queries/asset/query.go @@ -1,23 +1,24 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package asset import ( - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers/base" + "github.com/AssetMantle/modules/modules/assets/internal/module" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" ) -var Query = base.NewQuery( +var Query = baseHelpers.NewQuery( "assets", "", "", + module.Name, + requestPrototype, responsePrototype, keeperPrototype, - flags.AssetID, + + constants.AssetID, ) diff --git a/modules/assets/internal/queries/asset/query.pb.go b/modules/assets/internal/queries/asset/query.pb.go deleted file mode 100644 index c675d845a..000000000 --- a/modules/assets/internal/queries/asset/query.pb.go +++ /dev/null @@ -1,673 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/assets/internal/queries/asset/query.proto - -package asset - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - github_com_persistenceOne_persistenceSDK_schema_helpers "github.com/persistenceOne/persistenceSDK/schema/helpers" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type QueryRequest struct { - AssetID base.ID `protobuf:"bytes,1,opt,name=asset_i_d,json=assetID,proto3" json:"asset_i_d" valid:"required~required AssetID missing"` -} - -func (m *QueryRequest) Reset() { *m = QueryRequest{} } -func (m *QueryRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRequest) ProtoMessage() {} -func (*QueryRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_a52141441ac620ee, []int{0} -} -func (m *QueryRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRequest.Merge(m, src) -} -func (m *QueryRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRequest proto.InternalMessageInfo - -type QueryResponse struct { - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` - List []github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable `protobuf:"bytes,3,rep,name=list,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable" json:"list"` -} - -func (m *QueryResponse) Reset() { *m = QueryResponse{} } -func (m *QueryResponse) String() string { return proto.CompactTextString(m) } -func (*QueryResponse) ProtoMessage() {} -func (*QueryResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a52141441ac620ee, []int{1} -} -func (m *QueryResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryResponse.Merge(m, src) -} -func (m *QueryResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryRequest)(nil), "persistence_sdk.modules.assets.internal.queries.asset.QueryRequest") - proto.RegisterType((*QueryResponse)(nil), "persistence_sdk.modules.assets.internal.queries.asset.QueryResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/assets/internal/queries/asset/query.proto", fileDescriptor_a52141441ac620ee) -} - -var fileDescriptor_a52141441ac620ee = []byte{ - // 463 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0x31, 0x8b, 0xd4, 0x40, - 0x14, 0xc7, 0x33, 0x77, 0x9e, 0x7b, 0x1b, 0xb5, 0x09, 0x57, 0xac, 0xab, 0x24, 0x31, 0x20, 0xac, - 0x16, 0x33, 0x78, 0x62, 0x73, 0x95, 0xb7, 0xae, 0xe0, 0x21, 0x2a, 0xc6, 0x4e, 0x84, 0x65, 0x36, - 0x79, 0x64, 0x07, 0xb3, 0x33, 0xd9, 0x79, 0x13, 0xe1, 0x1a, 0x0b, 0x2b, 0x2b, 0x11, 0xfc, 0x02, - 0xd7, 0xf9, 0x11, 0xac, 0xed, 0xae, 0x3c, 0xb0, 0x11, 0x8b, 0x45, 0x76, 0x2d, 0xac, 0xfd, 0x04, - 0x92, 0xc9, 0x06, 0x97, 0xad, 0x16, 0xaf, 0xca, 0xfc, 0xdf, 0x84, 0x5f, 0x7e, 0xef, 0xcd, 0xc4, - 0x3d, 0x2c, 0x40, 0xa3, 0x40, 0x03, 0x32, 0x81, 0x21, 0xa6, 0xaf, 0xd9, 0x44, 0xa5, 0x65, 0x0e, - 0xc8, 0x38, 0x22, 0x18, 0x64, 0x42, 0x1a, 0xd0, 0x92, 0xe7, 0x6c, 0x5a, 0x82, 0x16, 0x4d, 0xdd, - 0xa6, 0x63, 0x5a, 0x68, 0x65, 0x94, 0x77, 0x6f, 0x0d, 0x41, 0x97, 0x08, 0x5a, 0x23, 0x68, 0x83, - 0xa0, 0x4b, 0x44, 0x5d, 0xef, 0xee, 0x65, 0x2a, 0x53, 0x96, 0xc0, 0xaa, 0x55, 0x0d, 0xeb, 0x5e, - 0xcf, 0x94, 0xca, 0x72, 0x60, 0xbc, 0x10, 0x8c, 0x4b, 0xa9, 0x0c, 0x37, 0x42, 0x49, 0x5c, 0xee, - 0xde, 0x5e, 0xb7, 0xc5, 0x64, 0x0c, 0x13, 0xce, 0xcc, 0x71, 0x01, 0xc8, 0x46, 0x1c, 0x81, 0x89, - 0xb4, 0x7e, 0x37, 0xfa, 0x40, 0xdc, 0xcb, 0xcf, 0x2b, 0xcd, 0x18, 0xa6, 0x25, 0xa0, 0xf1, 0x8c, - 0xdb, 0xb6, 0x5f, 0x1e, 0x8a, 0x61, 0xda, 0x21, 0x21, 0xe9, 0x5d, 0xda, 0xbf, 0x49, 0xd7, 0xdd, - 0x6b, 0x20, 0xb5, 0x40, 0x5a, 0x01, 0xe9, 0xd1, 0xa0, 0x7f, 0xe7, 0x74, 0x16, 0x38, 0x7f, 0x66, - 0xc1, 0xad, 0x37, 0x3c, 0x17, 0xe9, 0x41, 0xa4, 0x61, 0x5a, 0x0a, 0x0d, 0xe9, 0xdb, 0x66, 0x11, - 0x1e, 0x56, 0xe0, 0xa3, 0x41, 0x38, 0x11, 0x88, 0x42, 0x66, 0x51, 0xdc, 0xe2, 0x75, 0xe5, 0x60, - 0xf7, 0xfd, 0x49, 0xe0, 0xfc, 0x3e, 0x09, 0x9c, 0xe8, 0x33, 0x71, 0xaf, 0x2c, 0x85, 0xb0, 0x50, - 0x12, 0xc1, 0xeb, 0xb8, 0x2d, 0x2c, 0x93, 0x04, 0x10, 0xad, 0xcf, 0x6e, 0xdc, 0x44, 0x6f, 0xcf, - 0xdd, 0x01, 0xad, 0x95, 0xee, 0x6c, 0x85, 0xa4, 0xd7, 0x8e, 0xeb, 0xe0, 0xbd, 0x72, 0x2f, 0xe4, - 0x02, 0x4d, 0x67, 0x3b, 0xdc, 0xee, 0xb5, 0xfb, 0x8f, 0x2a, 0xab, 0x1f, 0xb3, 0xe0, 0x7e, 0x26, - 0xcc, 0xb8, 0x1c, 0xd1, 0x44, 0x4d, 0xd8, 0x4a, 0x3b, 0xcf, 0x24, 0xac, 0xc6, 0x17, 0x83, 0xc7, - 0xcd, 0xb4, 0xc6, 0x90, 0x57, 0x1b, 0xf4, 0x09, 0x2f, 0x0a, 0x3e, 0xca, 0x21, 0xb6, 0xd4, 0x7f, - 0xa6, 0xfb, 0x5f, 0x89, 0xbb, 0x63, 0x4d, 0xbd, 0x2f, 0xc4, 0x6d, 0x3d, 0x94, 0xb6, 0x49, 0xef, - 0x01, 0xfd, 0xaf, 0x83, 0xa6, 0xab, 0x87, 0xd0, 0x1d, 0x9c, 0x0f, 0x52, 0x0f, 0x2e, 0xba, 0xf1, - 0xee, 0xdb, 0xaf, 0x4f, 0x5b, 0xd7, 0xbc, 0xab, 0xab, 0x1d, 0x36, 0x57, 0xd6, 0x3e, 0xfa, 0xe3, - 0xd3, 0xb9, 0x4f, 0xce, 0xe6, 0x3e, 0xf9, 0x39, 0xf7, 0xc9, 0xc7, 0x85, 0xef, 0x9c, 0x2d, 0x7c, - 0xe7, 0xfb, 0xc2, 0x77, 0x5e, 0x3e, 0xdd, 0x78, 0x5e, 0x1b, 0xfd, 0x0b, 0xa3, 0x8b, 0xf6, 0xbe, - 0xdd, 0xfd, 0x1b, 0x00, 0x00, 0xff, 0xff, 0xb7, 0x7a, 0x5f, 0x4e, 0x4b, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) { - out := new(QueryResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.assets.internal.queries.asset.Query/Enquire", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - Enquire(context.Context, *QueryRequest) (*QueryResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Enquire(ctx context.Context, req *QueryRequest) (*QueryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Enquire not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Enquire_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Enquire(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.assets.internal.queries.asset.Query/Enquire", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Enquire(ctx, req.(*QueryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.assets.internal.queries.asset.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Enquire", - Handler: _Query_Enquire_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/assets/internal/queries/asset/query.proto", -} - -func (m *QueryRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.AssetID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.List) > 0 { - for iNdEx := len(m.List) - 1; iNdEx >= 0; iNdEx-- { - { - size := m.List[iNdEx].Size() - i -= size - if _, err := m.List[iNdEx].MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Error) > 0 { - i -= len(m.Error) - copy(dAtA[i:], m.Error) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Error))) - i-- - dAtA[i] = 0x12 - } - if m.Success { - i-- - if m.Success { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.AssetID.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Success { - n += 2 - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.List) > 0 { - for _, e := range m.List { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AssetID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.AssetID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Success = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field List", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var v github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable - m.List = append(m.List, v) - if err := m.List[len(m.List)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/assets/internal/queries/asset/query.pb.gw.go b/modules/assets/internal/queries/asset/query.pb.gw.go deleted file mode 100644 index 9237b2bed..000000000 --- a/modules/assets/internal/queries/asset/query.pb.gw.go +++ /dev/null @@ -1,166 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: persistence_sdk/modules/assets/internal/queries/asset/query.proto - -/* -Package asset is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package asset - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage - -var ( - filter_Query_Enquire_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Enquire(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Enquire(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features (such as grpc.SendHeader, etc) to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Enquire_0(rctx, inboundMarshaler, server, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Enquire_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Enquire_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"persistence", "assets", "asset"}, "", runtime.AssumeColonVerbOpt(true))) -) - -var ( - forward_Query_Enquire_0 = runtime.ForwardResponseMessage -) diff --git a/modules/assets/internal/queries/asset/request.go b/modules/assets/internal/queries/asset/request.go index 74e187e83..9f3f36052 100644 --- a/modules/assets/internal/queries/asset/request.go +++ b/modules/assets/internal/queries/asset/request.go @@ -1,76 +1,75 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package asset import ( "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/cosmos/cosmos-sdk/client/context" + + "github.com/AssetMantle/modules/modules/assets/internal/common" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" ) -var _ helpers.QueryRequest = (*QueryRequest)(nil) +type queryRequest struct { + ids.AssetID `json:"assetID" valid:"required~required field assetID missing"` +} + +var _ helpers.QueryRequest = (*queryRequest)(nil) -// QueryRequest godoc -// @Summary Query asset using asset id -// @Descrption Able to query the asset +// Validate godoc +// @Summary Search for an asset by Asset ID +// @Description Unique identifier of an asset. // @Accept text/plain // @Produce json // @Tags Assets // @Param assetID path string true "Asset ID" -// @Success 200 {object} queryResponse "A succesful query response" -// @Failure default {object} queryResponse "An unexpected error response." +// @Success 200 {object} queryResponse "Message for a successful search." +// @Failure default {object} queryResponse "Message for an unexpected error." // @Router /assets/assets/{assetID} [get] -func (queryRequest QueryRequest) Validate() error { - _, Error := govalidator.ValidateStruct(queryRequest) - return Error -} -func (queryRequest QueryRequest) FromCLI(cliCommand helpers.CLICommand, _ client.Context) helpers.QueryRequest { - return newQueryRequest(base.NewID(cliCommand.ReadString(flags.AssetID))) -} -func (queryRequest QueryRequest) FromMap(vars map[string]string) helpers.QueryRequest { - return newQueryRequest(base.NewID(vars[Query.GetName()])) +func (queryRequest queryRequest) Validate() error { + _, err := govalidator.ValidateStruct(queryRequest) + return err } -func (queryRequest QueryRequest) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryRequest) +func (queryRequest) FromCLI(cliCommand helpers.CLICommand, _ context.CLIContext) (helpers.QueryRequest, error) { + if assetID, err := baseIDs.ReadAssetID(cliCommand.ReadString(constants.AssetID)); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(assetID), nil + } } - -func (queryRequest QueryRequest) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryRequest, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest) FromMap(vars map[string]string) (helpers.QueryRequest, error) { + if assetID, err := baseIDs.ReadAssetID(vars[Query.GetName()]); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(assetID), nil } - - return queryRequest, nil } -func (queryRequest QueryRequest) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryRequest) +func (queryRequest queryRequest) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryRequest) } -func (queryRequest QueryRequest) LegacyAminoDecode(bytes []byte) (helpers.QueryRequest, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest queryRequest) Decode(bytes []byte) (helpers.QueryRequest, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryRequest); err != nil { + return nil, err } return queryRequest, nil } func requestPrototype() helpers.QueryRequest { - return QueryRequest{} + return queryRequest{} } -func queryRequestFromInterface(request helpers.QueryRequest) QueryRequest { +func queryRequestFromInterface(request helpers.QueryRequest) queryRequest { switch value := request.(type) { - case QueryRequest: + case queryRequest: return value default: - return QueryRequest{} + return queryRequest{} } } -func newQueryRequest(assetID types.ID) helpers.QueryRequest { - return QueryRequest{AssetID: *base.NewID(assetID.String())} +func newQueryRequest(assetID ids.AssetID) helpers.QueryRequest { + return queryRequest{AssetID: assetID} } diff --git a/modules/assets/internal/queries/asset/request_test.go b/modules/assets/internal/queries/asset/request_test.go index 073215c8b..4362b1425 100644 --- a/modules/assets/internal/queries/asset/request_test.go +++ b/modules/assets/internal/queries/asset/request_test.go @@ -1,63 +1,254 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package asset import ( + "reflect" "testing" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/key" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/spf13/viper" "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/assets/internal/common" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" ) -func Test_Asset_Request(t *testing.T) { +var ( + immutables = baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables = baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID = baseIDs.NewClassificationID(immutables, mutables) + testAssetID = baseIDs.NewAssetID(classificationID, immutables) +) - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - classificationID := base.NewID("classificationID") - immutableProperties := base.NewProperties(base.NewProperty(base.NewID("ID1"), base.NewFact(base.NewStringData("ImmutableData")))) +func Test_newQueryRequest(t *testing.T) { + type args struct { + assetID ids.AssetID + } + tests := []struct { + name string + args args + want helpers.QueryRequest + }{ + {"+ve", args{testAssetID}, newQueryRequest(testAssetID)}, + {"+ve", args{baseIDs.PrototypeAssetID()}, newQueryRequest(baseIDs.PrototypeAssetID())}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newQueryRequest(tt.args.assetID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newQueryRequest() = %v, want %v", got, tt.want) + } + }) + } +} - testAssetID := key.NewAssetID(classificationID, immutableProperties) - testQueryRequest := newQueryRequest(testAssetID) - require.Equal(t, nil, testQueryRequest.Validate()) - require.Equal(t, QueryRequest{}, requestPrototype()) +func Test_queryRequestFromInterface(t *testing.T) { + type args struct { + request helpers.QueryRequest + } + tests := []struct { + name string + args args + want queryRequest + }{ + {"+ve", args{newQueryRequest(testAssetID)}, newQueryRequest(testAssetID).(queryRequest)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := queryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("queryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.AssetID}) - cliContext := context.NewCLIContext().WithCodec(Codec) - require.Equal(t, newQueryRequest(base.NewID("")), QueryRequest{}.FromCLI(cliCommand, cliContext)) +func Test_queryRequest_Decode(t *testing.T) { + encodedQuery, err := common.Codec.MarshalJSON(newQueryRequest(testAssetID)) + require.NoError(t, err) + encodedQuery1, err := common.Codec.MarshalJSON(newQueryRequest(baseIDs.PrototypeAssetID())) + require.NoError(t, err) + type fields struct { + AssetID ids.AssetID + } + type args struct { + bytes []byte + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testAssetID}, args{encodedQuery}, newQueryRequest(testAssetID), false}, + {"+ve", fields{baseIDs.PrototypeAssetID()}, args{encodedQuery1}, newQueryRequest(baseIDs.PrototypeAssetID()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + AssetID: tt.fields.AssetID, + } + got, err := queryRequest.Decode(tt.args.bytes) + if (err != nil) != tt.wantErr { + t.Errorf("Decode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Decode() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequest_Encode(t *testing.T) { + encodedQuery, err := common.Codec.MarshalJSON(newQueryRequest(testAssetID)) + require.NoError(t, err) + encodedQuery1, err := common.Codec.MarshalJSON(newQueryRequest(baseIDs.PrototypeAssetID())) + require.NoError(t, err) + type fields struct { + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + want []byte + wantErr bool + }{ + {"+ve", fields{testAssetID}, encodedQuery, false}, + {"+ve with nil", fields{baseIDs.PrototypeAssetID()}, encodedQuery1, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + AssetID: tt.fields.AssetID, + } + got, err := queryRequest.Encode() + if (err != nil) != tt.wantErr { + t.Errorf("Encode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Encode() got = %v, want %v", got, tt.want) + } + }) + } +} +func Test_queryRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.AssetID}) + viper.Set(constants.AssetID.GetName(), testAssetID.String()) + type fields struct { + AssetID ids.AssetID + } + type args struct { + cliCommand helpers.CLICommand + in1 context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testAssetID}, args{cliCommand, context.NewCLIContext()}, newQueryRequest(testAssetID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + AssetID: tt.fields.AssetID, + } + got, err := qu.FromCLI(tt.args.cliCommand, tt.args.in1) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequest_FromMap(t *testing.T) { vars := make(map[string]string) - vars["assets"] = "randomString" - require.Equal(t, newQueryRequest(base.NewID("randomString")), QueryRequest{}.FromMap(vars)) - - encodedRequest, Error := testQueryRequest.LegacyAminoEncode() - encodedResult, _ := common.LegacyAminoCodec.MarshalJSON(testQueryRequest) - require.Equal(t, encodedResult, encodedRequest) - require.Nil(t, Error) - - decodedRequest, Error := QueryRequest{}.LegacyAminoDecode(encodedRequest) - require.Equal(t, testQueryRequest, decodedRequest) - require.Equal(t, nil, Error) - - randomDecode, _ := QueryRequest{}.LegacyAminoDecode(base.NewID("").Bytes()) - require.Equal(t, nil, randomDecode) - require.Equal(t, testQueryRequest, queryRequestFromInterface(testQueryRequest)) - require.Equal(t, QueryRequest{}, queryRequestFromInterface(nil)) + vars[Query.GetName()] = testAssetID.String() + type fields struct { + AssetID ids.AssetID + } + type args struct { + vars map[string]string + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testAssetID}, args{vars}, newQueryRequest(testAssetID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + AssetID: tt.fields.AssetID, + } + got, err := qu.FromMap(tt.args.vars) + if (err != nil) != tt.wantErr { + t.Errorf("FromMap() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromMap() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequest_Validate(t *testing.T) { + type fields struct { + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testAssetID}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + AssetID: tt.fields.AssetID, + } + if err := queryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryRequest + }{ + {"+ve", queryRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/assets/internal/queries/asset/response.go b/modules/assets/internal/queries/asset/response.go index 3ec79347d..7a386a07d 100644 --- a/modules/assets/internal/queries/asset/response.go +++ b/modules/assets/internal/queries/asset/response.go @@ -1,64 +1,49 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package asset import ( - "errors" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/assets/internal/common" + "github.com/AssetMantle/modules/schema/helpers" ) -var _ helpers.QueryResponse = (*QueryResponse)(nil) +type queryResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` + List []helpers.Mappable `json:"list"` +} + +var _ helpers.QueryResponse = (*queryResponse)(nil) -func (queryResponse QueryResponse) IsSuccessful() bool { +func (queryResponse queryResponse) IsSuccessful() bool { return queryResponse.Success } -func (queryResponse QueryResponse) GetError() error { - return errors.New(queryResponse.Error) +func (queryResponse queryResponse) GetError() error { + return queryResponse.Error } -func (queryResponse QueryResponse) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryResponse) +func (queryResponse queryResponse) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryResponse) } -func (queryResponse QueryResponse) LegacyAminoDecode(bytes []byte) (helpers.QueryResponse, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error +func (queryResponse queryResponse) Decode(bytes []byte) (helpers.QueryResponse, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryResponse); err != nil { + return nil, err } - return &queryResponse, nil -} -func (queryResponse QueryResponse) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryResponse) -} - -func (queryResponse QueryResponse) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryResponse, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error - } - return &queryResponse, nil + return queryResponse, nil } - func responsePrototype() helpers.QueryResponse { - return &QueryResponse{} + return queryResponse{} } - -func newQueryResponse(collection helpers.Collection, error error) QueryResponse { +func newQueryResponse(collection helpers.Collection, error error) helpers.QueryResponse { success := true if error != nil { success = false - return QueryResponse{ - Success: success, - Error: "yes", - List: collection.GetList(), - } } - return QueryResponse{ + + return queryResponse{ Success: success, - Error: "no", + Error: error, List: collection.GetList(), } - } diff --git a/modules/assets/internal/queries/asset/response_test.go b/modules/assets/internal/queries/asset/response_test.go index d8e27a6cf..375a73de2 100644 --- a/modules/assets/internal/queries/asset/response_test.go +++ b/modules/assets/internal/queries/asset/response_test.go @@ -1,32 +1,34 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package asset import ( + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/mapper" - "github.com/persistenceOne/persistenceSDK/schema" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "testing" + + "github.com/AssetMantle/modules/modules/assets/internal/common" + "github.com/AssetMantle/modules/modules/assets/internal/mapper" + "github.com/AssetMantle/modules/schema/errors/constants" + + "github.com/AssetMantle/modules/schema" ) func CreateTestInput(t *testing.T) sdkTypes.Context { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + var Codec = codec.New() + + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() @@ -40,8 +42,9 @@ func CreateTestInput(t *testing.T) sdkTypes.Context { commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", @@ -55,22 +58,22 @@ func Test_Asset_Response(t *testing.T) { collection := mapper.Prototype().NewCollection(context) testQueryResponse := newQueryResponse(collection, nil) - testQueryResponseWithError := newQueryResponse(collection, errors.IncorrectFormat) + testQueryResponseWithError := newQueryResponse(collection, constants.IncorrectFormat) require.Equal(t, true, testQueryResponse.IsSuccessful()) require.Equal(t, false, testQueryResponseWithError.IsSuccessful()) require.Equal(t, nil, testQueryResponse.GetError()) - require.Equal(t, errors.IncorrectFormat, testQueryResponseWithError.GetError()) + require.Equal(t, constants.IncorrectFormat, testQueryResponseWithError.GetError()) - encodedResponse, _ := testQueryResponse.LegacyAminoEncode() - bytes, _ := common.LegacyAminoCodec.MarshalJSON(testQueryResponse) + encodedResponse, _ := testQueryResponse.Encode() + bytes, _ := common.Codec.MarshalJSON(testQueryResponse) require.Equal(t, bytes, encodedResponse) - decodedResponse, _ := QueryResponse{}.LegacyAminoDecode(bytes) + decodedResponse, _ := queryResponse{}.Decode(bytes) require.Equal(t, testQueryResponse, decodedResponse) - decodedResponse2, _ := QueryResponse{}.LegacyAminoDecode([]byte{}) + decodedResponse2, _ := queryResponse{}.Decode([]byte{}) require.Equal(t, nil, decodedResponse2) - require.Equal(t, QueryResponse{}, responsePrototype()) + require.Equal(t, queryResponse{}, responsePrototype()) } diff --git a/modules/assets/internal/queries/prototype.go b/modules/assets/internal/queries/prototype.go new file mode 100644 index 000000000..31d28260a --- /dev/null +++ b/modules/assets/internal/queries/prototype.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queries + +import ( + "github.com/AssetMantle/modules/modules/assets/internal/queries/asset" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Queries { + return baseHelpers.NewQueries( + asset.Query, + ) +} diff --git a/modules/assets/internal/queries/prototype_test.go b/modules/assets/internal/queries/prototype_test.go new file mode 100644 index 000000000..f13aabd13 --- /dev/null +++ b/modules/assets/internal/queries/prototype_test.go @@ -0,0 +1,29 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queries + +import ( + "reflect" + "testing" + + "github.com/AssetMantle/modules/modules/assets/internal/queries/asset" +) + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want string + getString string + }{ + + {"+ve", asset.Query.GetName(), "assets"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype(); !reflect.DeepEqual(got.Get(tt.getString).GetName(), tt.want) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/assets/internal/simulator/constants.go b/modules/assets/internal/simulator/constants.go new file mode 100644 index 000000000..0e23f0a61 --- /dev/null +++ b/modules/assets/internal/simulator/constants.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +const OpWeightSubmitTextProposal = "op_weight_submit_text_proposal" +const DefaultWeightTextProposal = 1 + +const OpWeightMsg = "OpWeightMsg" +const DefaultWeightMsg = 1 diff --git a/modules/assets/internal/simulator/genesis.go b/modules/assets/internal/simulator/genesis.go new file mode 100644 index 000000000..a223bfa53 --- /dev/null +++ b/modules/assets/internal/simulator/genesis.go @@ -0,0 +1,51 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "math/rand" + + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + + "github.com/AssetMantle/modules/modules/assets/internal/common" + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + assetsModule "github.com/AssetMantle/modules/modules/assets/internal/module" + "github.com/AssetMantle/modules/modules/assets/internal/parameters" + "github.com/AssetMantle/modules/modules/assets/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/data" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + parameters2 "github.com/AssetMantle/modules/schema/parameters" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseSimulation "github.com/AssetMantle/modules/simulation/schema/types/base" +) + +func (simulator) RandomizedGenesisState(simulationState *module.SimulationState) { + var Data data.Data + + simulationState.AppParams.GetOrGenerate( + simulationState.Cdc, + dummy.ID.String(), + &Data, + simulationState.Rand, + func(rand *rand.Rand) { Data = baseData.NewDecData(sdkTypes.NewDecWithPrec(int64(rand.Intn(99)), 2)) }, + ) + + mappableList := make([]helpers.Mappable, simulationState.Rand.Intn(99)) + + for i := range mappableList { + immutables := baseQualified.NewImmutables(baseSimulation.GenerateRandomPropertyList(simulationState.Rand)) + mutables := baseQualified.NewMutables(baseSimulation.GenerateRandomPropertyList(simulationState.Rand)) + mappableList[i] = mappable.NewMappable(base.NewAsset(baseIDs.NewClassificationID(immutables, mutables), immutables, mutables)) + } + + genesisState := baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, nil, parameters.Prototype().GetList()).Initialize(mappableList, []parameters2.Parameter{dummy.Parameter.Mutate(Data)}) + + simulationState.GenState[assetsModule.Name] = common.Codec.MustMarshalJSON(genesisState) +} diff --git a/modules/assets/internal/simulator/operations.go b/modules/assets/internal/simulator/operations.go index d5dfcf59e..3c3884187 100644 --- a/modules/assets/internal/simulator/operations.go +++ b/modules/assets/internal/simulator/operations.go @@ -1,21 +1,18 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( - sdkModuleSimulation "github.com/cosmos/cosmos-sdk/x/simulation" "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" ) -func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec.JSONMarshaler) simulation.WeightedOperation { +func (simulator) WeightedOperations(appParams simulation.AppParams, codec *codec.Codec) simulation.WeightedOperations { var weightMsg int appParams.GetOrGenerate(codec, OpWeightMsg, &weightMsg, nil, @@ -24,10 +21,12 @@ func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec. }, ) - return sdkModuleSimulation.NewWeightedOperation( - weightMsg, - simulateMsg(), - ) + return simulation.WeightedOperations{ + simulation.NewWeightedOperation( + weightMsg, + simulateMsg(), + ), + } } func simulateMsg() simulation.Operation { diff --git a/modules/assets/internal/simulator/params.go b/modules/assets/internal/simulator/params.go index 03cb84e34..5824ba7f6 100644 --- a/modules/assets/internal/simulator/params.go +++ b/modules/assets/internal/simulator/params.go @@ -1,31 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( "math/rand" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + sdk "github.com/cosmos/cosmos-sdk/types" - simTypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" + + "github.com/AssetMantle/modules/modules/assets/internal/common" + "github.com/AssetMantle/modules/modules/assets/internal/module" + "github.com/AssetMantle/modules/modules/assets/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/data/base" ) -func (simulator) ParamChangeList(_ *rand.Rand) []simTypes.ParamChange { - return []simTypes.ParamChange{ +func (simulator) ParamChangeList(_ *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange(module.Name, dummy.ID.String(), func(r *rand.Rand) string { - bytes, Error := common.LegacyAminoCodec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdkTypes.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) - if Error != nil { - panic(Error) + bytes, err := common.Codec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdk.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) + if err != nil { + panic(err) } return string(bytes) }), diff --git a/modules/assets/internal/simulator/proposals.go b/modules/assets/internal/simulator/proposals.go index c85fdfbd1..ce4efd54f 100644 --- a/modules/assets/internal/simulator/proposals.go +++ b/modules/assets/internal/simulator/proposals.go @@ -1,34 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( - simulation2 "github.com/cosmos/cosmos-sdk/x/simulation" "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/simulation" ) func (simulator) WeightedProposalContentList() []simulation.WeightedProposalContent { return []simulation.WeightedProposalContent{ - simulation2.NewWeightedProposalContent( - OpWeightSubmitTextProposal, - DefaultWeightTextProposal, - contentSimulatorFunc(), - ), + { + AppParamsKey: OpWeightSubmitTextProposal, + DefaultWeight: DefaultWeightTextProposal, + ContentSimulatorFn: simulateTextProposalContent, + }, } } -func contentSimulatorFunc() simulation.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) simulation.Content { - return types.NewTextProposal( - simulation.RandStringOfLength(r, 140), - simulation.RandStringOfLength(r, 5000), - ) - } +func simulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Account) types.Content { + return types.NewTextProposal( + simulation.RandStringOfLength(r, 140), + simulation.RandStringOfLength(r, 5000), + ) } diff --git a/modules/assets/internal/simulator/prototype.go b/modules/assets/internal/simulator/prototype.go new file mode 100644 index 000000000..3da39d69f --- /dev/null +++ b/modules/assets/internal/simulator/prototype.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +func Prototype() helpers.Simulator { + return newSimulator() +} diff --git a/modules/assets/internal/simulator/prototype_test.go b/modules/assets/internal/simulator/prototype_test.go new file mode 100644 index 000000000..594e47582 --- /dev/null +++ b/modules/assets/internal/simulator/prototype_test.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func Test_Prototype(t *testing.T) { + require.Equal(t, newSimulator(), Prototype()) +} diff --git a/modules/assets/internal/simulator/simulator.go b/modules/assets/internal/simulator/simulator.go new file mode 100644 index 000000000..7c21354cd --- /dev/null +++ b/modules/assets/internal/simulator/simulator.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +type simulator struct { +} + +var _ helpers.Simulator = (*simulator)(nil) + +func newSimulator() helpers.Simulator { + return simulator{} +} diff --git a/modules/assets/internal/simulator/simulator_test.go b/modules/assets/internal/simulator/simulator_test.go new file mode 100644 index 000000000..1a738209a --- /dev/null +++ b/modules/assets/internal/simulator/simulator_test.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func Test_newSimulator(t *testing.T) { + require.Equal(t, newSimulator(), simulator{}) +} diff --git a/modules/assets/internal/transactions/burn/keeper.go b/modules/assets/internal/transactions/burn/keeper.go new file mode 100644 index 000000000..85b31ad7e --- /dev/null +++ b/modules/assets/internal/transactions/burn/keeper.go @@ -0,0 +1,95 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package burn + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/maintain" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/renumerate" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/documents" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/properties" + "github.com/AssetMantle/modules/schema/properties/constants" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + renumerateAuxiliary helpers.Auxiliary + maintainAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + assets := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.AssetID)) + + Mappable := assets.Get(key.NewKey(message.AssetID)) + if Mappable == nil { + return newTransactionResponse(errorConstants.EntityNotFound) + } + asset := Mappable.(documents.Asset) + + metaProperties, err := supplement.GetMetaPropertiesFromResponse(transactionKeeper.supplementAuxiliary.GetKeeper().Help(context, supplement.NewAuxiliaryRequest(asset.GetBurn()))) + if err != nil { + return newTransactionResponse(err) + } + + if burnHeightMetaProperty := metaProperties.GetProperty(constants.BurnHeightProperty.GetID()); burnHeightMetaProperty != nil { + burnHeight := burnHeightMetaProperty.(properties.MetaProperty).GetData().(data.HeightData).Get() + if burnHeight.Compare(baseTypes.NewHeight(context.BlockHeight())) > 0 { + return newTransactionResponse(errorConstants.NotAuthorized) + } + } + + if auxiliaryResponse := transactionKeeper.renumerateAuxiliary.GetKeeper().Help(context, renumerate.NewAuxiliaryRequest(message.FromID, message.AssetID, sdkTypes.ZeroDec())); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + assets.Remove(mappable.NewMappable(asset)) + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper = mapper + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case renumerate.Auxiliary.GetName(): + transactionKeeper.renumerateAuxiliary = value + case maintain.Auxiliary.GetName(): + transactionKeeper.maintainAuxiliary = value + case supplement.Auxiliary.GetName(): + transactionKeeper.supplementAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} + +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/assets/internal/transactions/burn/keeper_test.go b/modules/assets/internal/transactions/burn/keeper_test.go index 275ea5671..d1da0a0a9 100644 --- a/modules/assets/internal/transactions/burn/keeper_test.go +++ b/modules/assets/internal/transactions/burn/keeper_test.go @@ -5,6 +5,19 @@ package burn import ( "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + "github.com/AssetMantle/modules/modules/assets/internal/key" "github.com/AssetMantle/modules/modules/assets/internal/mappable" "github.com/AssetMantle/modules/modules/assets/internal/parameters" @@ -22,17 +35,6 @@ import ( baseLists "github.com/AssetMantle/modules/schema/lists/base" baseProperties "github.com/AssetMantle/modules/schema/properties/base" baseQualified "github.com/AssetMantle/modules/schema/qualified/base" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/stretchr/testify/require" - abciTypes "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" ) var ( diff --git a/modules/assets/internal/transactions/burn/message.go b/modules/assets/internal/transactions/burn/message.go index 44bf68eeb..5bdaa40b0 100644 --- a/modules/assets/internal/transactions/burn/message.go +++ b/modules/assets/internal/transactions/burn/message.go @@ -1,68 +1,64 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package burn import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/assets/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + AssetID ids.AssetID `json:"assetID" valid:"required~required field assetID missing"` +} + +var _ helpers.Message = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + var _, err = govalidator.ValidateStruct(message) + if err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, assetID types.ID) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - AssetID: *base.NewID(assetID.String()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, assetID ids.AssetID) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + AssetID: assetID, } } diff --git a/modules/assets/internal/transactions/burn/message.pb.go b/modules/assets/internal/transactions/burn/message.pb.go deleted file mode 100644 index 75002b47b..000000000 --- a/modules/assets/internal/transactions/burn/message.pb.go +++ /dev/null @@ -1,628 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/assets/internal/transactions/burn/message.proto - -package burn - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:" required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d"` - AssetID base.ID `protobuf:"bytes,3,opt,name=asset_i_d,json=assetID,proto3" json:"asset_i_d"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_a2c6284c4487d28c, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_a2c6284c4487d28c, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.assets.internal.transactions.burn.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.assets.internal.transactions.burn.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/assets/internal/transactions/burn/message.proto", fileDescriptor_a2c6284c4487d28c) -} - -var fileDescriptor_a2c6284c4487d28c = []byte{ - // 420 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0xbf, 0x6b, 0x14, 0x41, - 0x14, 0xc7, 0x77, 0x92, 0x23, 0x3f, 0xc6, 0x6e, 0x55, 0x08, 0x57, 0xec, 0x2e, 0x07, 0x42, 0x10, - 0x9c, 0x81, 0x58, 0x99, 0x2e, 0xcb, 0xc5, 0x70, 0x48, 0x14, 0x56, 0x2b, 0x9b, 0x63, 0x76, 0xe7, - 0x65, 0x33, 0xb8, 0x3b, 0xb3, 0xce, 0x9b, 0x15, 0x6c, 0x52, 0x5b, 0x8a, 0xa5, 0x55, 0xf0, 0xaf, - 0xf0, 0x4f, 0x48, 0x99, 0x52, 0x2c, 0x0e, 0xb9, 0x6b, 0xac, 0xfd, 0x0b, 0x64, 0x67, 0x13, 0x3c, - 0x4e, 0x8b, 0xa8, 0xd5, 0xbc, 0x81, 0xf7, 0x3e, 0xdf, 0x2f, 0xef, 0xfb, 0xe8, 0x51, 0x03, 0x16, - 0x15, 0x3a, 0xd0, 0x05, 0x4c, 0x51, 0xbe, 0xe2, 0xb5, 0x91, 0x6d, 0x05, 0xc8, 0x05, 0x22, 0x38, - 0xe4, 0x4a, 0x3b, 0xb0, 0x5a, 0x54, 0xdc, 0x59, 0xa1, 0x51, 0x14, 0x4e, 0x19, 0x8d, 0x3c, 0x6f, - 0xad, 0xe6, 0x35, 0x20, 0x8a, 0x12, 0x58, 0x63, 0x8d, 0x33, 0xe1, 0xa3, 0x15, 0x10, 0xbb, 0x02, - 0xb1, 0x1e, 0xc4, 0xae, 0x41, 0x6c, 0x19, 0xc4, 0x3a, 0xd0, 0xf0, 0x4e, 0x69, 0x4a, 0xe3, 0x29, - 0xbc, 0xab, 0x7a, 0xe0, 0xf0, 0xfe, 0xaa, 0x33, 0x2c, 0x4e, 0xa1, 0x16, 0xdc, 0xbd, 0x6d, 0x00, - 0x79, 0x2e, 0x10, 0xb8, 0x92, 0x7d, 0xef, 0xe8, 0xf3, 0x1a, 0xdd, 0x3c, 0xee, 0xed, 0x84, 0x1f, - 0x08, 0x1d, 0x9c, 0x58, 0x53, 0xef, 0x90, 0x84, 0xec, 0x6e, 0xa7, 0x67, 0x17, 0xb3, 0x38, 0xf8, - 0x3a, 0x8b, 0x0f, 0x4b, 0xe5, 0x4e, 0xdb, 0x9c, 0x15, 0xa6, 0xe6, 0x4b, 0xe4, 0x67, 0x1a, 0x96, - 0xbf, 0xcf, 0xc7, 0x4f, 0x7e, 0xd7, 0x61, 0x07, 0x45, 0x71, 0x20, 0xa5, 0x05, 0xc4, 0x1f, 0xb3, - 0xf8, 0xc1, 0x1b, 0x51, 0x29, 0xb9, 0x3f, 0x4a, 0x2c, 0xbc, 0x6e, 0x95, 0x05, 0x79, 0x76, 0x5d, - 0x24, 0x27, 0x0a, 0x2a, 0x99, 0x3c, 0xb6, 0xa6, 0x4e, 0x6a, 0x85, 0xa8, 0x74, 0x39, 0xca, 0xbc, - 0x97, 0xf0, 0x90, 0x6e, 0x75, 0xef, 0x54, 0x4d, 0xe5, 0xce, 0x5a, 0x42, 0x76, 0x6f, 0xed, 0xdd, - 0x63, 0xab, 0x0b, 0xeb, 0x75, 0x99, 0xd7, 0x65, 0x5e, 0x77, 0x32, 0x4e, 0x07, 0x9d, 0xfd, 0x6c, - 0xa3, 0x1b, 0x9e, 0x8c, 0xc3, 0x23, 0xba, 0xed, 0xd7, 0xe9, 0x39, 0xeb, 0x7f, 0xcf, 0xd9, 0xf4, - 0xd3, 0x93, 0xf1, 0xfe, 0xd6, 0xbb, 0xf3, 0x38, 0xf8, 0x7e, 0x1e, 0x07, 0xa3, 0xbb, 0xf4, 0xf6, - 0x8b, 0x5f, 0x89, 0x64, 0x80, 0x8d, 0xd1, 0x08, 0x7b, 0x9f, 0x08, 0x5d, 0x3f, 0xc6, 0x32, 0xfc, - 0x48, 0xe8, 0x20, 0x6d, 0xad, 0x0e, 0x53, 0xf6, 0xcf, 0x01, 0xb3, 0xab, 0x68, 0x86, 0x4f, 0xff, - 0x83, 0xf1, 0x07, 0x93, 0x69, 0x75, 0x31, 0x8f, 0xc8, 0xe5, 0x3c, 0x22, 0xdf, 0xe6, 0x11, 0x79, - 0xbf, 0x88, 0x82, 0xcb, 0x45, 0x14, 0x7c, 0x59, 0x44, 0xc1, 0xcb, 0xec, 0xc6, 0x69, 0xdf, 0xf8, - 0xde, 0xf3, 0x0d, 0x7f, 0x6b, 0x0f, 0x7f, 0x06, 0x00, 0x00, 0xff, 0xff, 0x01, 0x54, 0x9e, 0xce, - 0x33, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Burn(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Burn(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.assets.internal.transactions.burn.Msg/Burn", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Burn(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Burn(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Burn not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Burn_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Burn(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.assets.internal.transactions.burn.Msg/Burn", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Burn(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.assets.internal.transactions.burn.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Burn", - Handler: _Msg_Burn_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/assets/internal/transactions/burn/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.AssetID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.AssetID.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AssetID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.AssetID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/assets/internal/transactions/burn/message_test.go b/modules/assets/internal/transactions/burn/message_test.go index e2e5a3bb2..481b6a676 100644 --- a/modules/assets/internal/transactions/burn/message_test.go +++ b/modules/assets/internal/transactions/burn/message_test.go @@ -1,39 +1,257 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package burn import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/assets/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Burn_Message(t *testing.T) { - testAssetID := base.NewID("assetID") - testFromID := base.NewID("fromID") - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, err) - - testMessage := newMessage(fromAccAddress, testFromID, testAssetID) - require.Equal(t, message{From: fromAccAddress, FromID: testFromID, AssetID: testAssetID}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, message{}, messageFromInterface(nil)) - require.Equal(t, message{}, messagePrototype()) +var ( + immutables = baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables = baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())))) + classificationID = baseIDs.NewClassificationID(immutables, mutables) + testAssetID = baseIDs.NewAssetID(classificationID, immutables) + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = sdkTypes.AccAddressFromBech32(fromAddress) + fromID = baseIDs.NewIdentityID(classificationID, immutables) +) + +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{newMessage(fromAccAddress, fromID, testAssetID)}, newMessage(fromAccAddress, fromID, testAssetID).(message)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(newMessage(fromAccAddress, fromID, testAssetID)))}, + {"+ve", fields{}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{}))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID}, args{codec.New()}}, + {"+ve", fields{}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID}, false}, + {"-ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + assetID ids.AssetID + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, fromID, testAssetID}, message{fromAccAddress, fromID, testAssetID}}, + {"+ve with nil", args{}, message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.assetID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/assets/internal/transactions/burn/msg_server.go b/modules/assets/internal/transactions/burn/msg_server.go deleted file mode 100644 index 6caff655e..000000000 --- a/modules/assets/internal/transactions/burn/msg_server.go +++ /dev/null @@ -1,65 +0,0 @@ -package burn - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/burn" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Burn(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - assets := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(&message.AssetID)) - - asset := assets.Get(key.FromID(&message.AssetID)) - if asset == nil { - return nil, errors.EntityNotFound - } - - metaProperties, Error := supplement.GetMetaPropertiesFromResponse(msgServer.transactionKeeper.supplementAuxiliary.GetKeeper().Help(ctx, supplement.NewAuxiliaryRequest(asset.(mappables.InterNFT).GetBurn()))) - if Error != nil { - return nil, Error - } - - burnHeightMetaFact := metaProperties.Get(base.NewID(properties.Burn)) - if burnHeightMetaFact == nil { - return nil, errors.EntityNotFound - } - - burnHeight, Error := burnHeightMetaFact.GetMetaFact().GetData().AsHeight() - if Error != nil { - return nil, Error - } - - if burnHeight.Compare(base.NewHeight(ctx.BlockHeight())) > 0 { - return nil, errors.NotAuthorized - } - - if auxiliaryResponse := msgServer.transactionKeeper.burnAuxiliary.GetKeeper().Help(ctx, burn.NewAuxiliaryRequest(message.FromID, message.AssetID, sdkTypes.SmallestDec())); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - assets.Remove(asset) - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/assets/internal/transactions/burn/request.go b/modules/assets/internal/transactions/burn/request.go index 7a120416d..f9e5b4820 100644 --- a/modules/assets/internal/transactions/burn/request.go +++ b/modules/assets/internal/transactions/burn/request.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package burn @@ -9,15 +7,15 @@ import ( "encoding/json" "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -28,30 +26,30 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary burn asset transaction -// @Descrption burn asset +// Validate Request godoc +// @Summary Burn an asset transaction +// @Description Transaction for burning an asset. request body // @Accept text/plain // @Produce json // @Tags Assets -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body transactionRequest true "Transaction for burning an asset. request body" +// @Success 200 {object} transactionResponse "Message for a successful transaction." +// @Failure default {object} transactionResponse "Message for an unexpected error in the transaction." // @Router /assets/burn [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.AssetID), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.AssetID), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -60,19 +58,29 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + assetID, err := baseIDs.ReadAssetID(transactionRequest.AssetID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.AssetID), + fromID, + assetID, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/assets/internal/transactions/burn/request_test.go b/modules/assets/internal/transactions/burn/request_test.go index da683330c..fba031f6f 100644 --- a/modules/assets/internal/transactions/burn/request_test.go +++ b/modules/assets/internal/transactions/burn/request_test.go @@ -1,72 +1,259 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package burn import ( "encoding/json" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" + "fmt" + "reflect" "testing" -) -func Test_Burn_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.AssetID}) - cliContext := context.NewCLIContext().WithCodec(Codec) + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/rest" + "github.com/spf13/viper" - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "assetID") + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/utilities/transaction" +) - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", AssetID: "assetID"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) +var ( + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} +) - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", AssetID: ""}, requestFromCLI) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + assetID string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, fromID.String(), testAssetID.String()}, transactionRequest{testBaseRequest, fromID.String(), testAssetID.String()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.assetID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.AssetID, constants.FromID}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.AssetID.GetName(), testAssetID.String()) + viper.Set(constants.FromID.GetName(), fromID.String()) + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{BaseReq: testBaseRequest, FromID: fromID.String(), AssetID: testAssetID.String()}, args{cliCommand, cliContext}, newTransactionRequest(testBaseRequest, fromID.String(), testAssetID.String()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromJSON(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String()}, args{types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, fromID, testAssetID}))}, newTransactionRequest(testBaseRequest, fromID.String(), testAssetID.String()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("assetID")), msg) - require.Nil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String()}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error := newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", "assetID").MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String()}, newMessage(fromAccAddress, fromID, testAssetID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String()}, false}, + // {"+ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/assets/internal/transactions/burn/response.go b/modules/assets/internal/transactions/burn/response.go new file mode 100644 index 000000000..9411435ac --- /dev/null +++ b/modules/assets/internal/transactions/burn/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package burn + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/assets/internal/transactions/burn/response_test.go b/modules/assets/internal/transactions/burn/response_test.go new file mode 100644 index 000000000..6c9422491 --- /dev/null +++ b/modules/assets/internal/transactions/burn/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package burn + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Burn_Response(t *testing.T) { + testTransactionResponse := newTransactionResponse(constants.IncorrectFormat) + testTransactionResponse2 := newTransactionResponse(nil) + + require.Equal(t, transactionResponse{Success: false, Error: constants.IncorrectFormat}, testTransactionResponse) + require.Equal(t, false, testTransactionResponse.IsSuccessful()) + require.Equal(t, true, testTransactionResponse2.IsSuccessful()) + + require.Equal(t, constants.IncorrectFormat, testTransactionResponse.GetError()) + require.Equal(t, nil, testTransactionResponse2.GetError()) +} diff --git a/modules/assets/internal/transactions/burn/transaction.go b/modules/assets/internal/transactions/burn/transaction.go new file mode 100644 index 000000000..00de75c31 --- /dev/null +++ b/modules/assets/internal/transactions/burn/transaction.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package burn + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "burn", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.AssetID, +) diff --git a/modules/assets/internal/transactions/define/keeper.go b/modules/assets/internal/transactions/define/keeper.go new file mode 100644 index 000000000..56580acb4 --- /dev/null +++ b/modules/assets/internal/transactions/define/keeper.go @@ -0,0 +1,73 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/define" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/super" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/qualified/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + defineAuxiliary helpers.Auxiliary + superAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + immutables := base.NewImmutables(baseLists.NewPropertyList(append(message.ImmutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...)...)) + + mutables := base.NewMutables(baseLists.NewPropertyList(append(message.MutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...)) + + classificationID, err := define.GetClassificationIDFromResponse(transactionKeeper.defineAuxiliary.GetKeeper().Help(context, define.NewAuxiliaryRequest(immutables, mutables))) + if err != nil { + return newTransactionResponse(err) + } + + if auxiliaryResponse := transactionKeeper.superAuxiliary.GetKeeper().Help(context, super.NewAuxiliaryRequest(classificationID, message.FromID, mutables)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper = mapper + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case define.Auxiliary.GetName(): + transactionKeeper.defineAuxiliary = value + case super.Auxiliary.GetName(): + transactionKeeper.superAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(constants.UninitializedUsage) + } + } + + return transactionKeeper +} + +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/assets/internal/transactions/define/keeper_test.go b/modules/assets/internal/transactions/define/keeper_test.go new file mode 100644 index 000000000..979f694bf --- /dev/null +++ b/modules/assets/internal/transactions/define/keeper_test.go @@ -0,0 +1,191 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + "github.com/AssetMantle/modules/modules/assets/internal/parameters" + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/define" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/super" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +var ( + defineAuxiliary helpers.Auxiliary + superAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary +) + +type TestKeepers struct { + BurnKeeper helpers.TransactionKeeper +} + +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + defineAuxiliary = define.AuxiliaryMock.Initialize(Mapper, Parameters) + superAuxiliary = super.AuxiliaryMock.Initialize(Mapper, Parameters) + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + + keepers := TestKeepers{ + BurnKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), + } + + return context, keepers, Mapper, Parameters +} + +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + defineAuxiliary helpers.Auxiliary + superAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper, defineAuxiliary, superAuxiliary, authenticateAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, defineAuxiliary, superAuxiliary, authenticateAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + defineAuxiliary: tt.fields.defineAuxiliary, + superAuxiliary: tt.fields.superAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.in1, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, _ := createTestInput(t) + immutablePropertiesLists := baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutableMetaPropertiesLists := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutables := baseQualified.NewImmutables(immutableMetaPropertiesLists) + mutablePropertiesLists := baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutableMetaPropertiesLists := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutables := baseQualified.NewMutables(mutableMetaPropertiesLists) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + // testAssetID := baseIDs.NewAssetID(classificationID, immutables) + testAsset := base.NewAsset(classificationID, immutables, mutables) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + fromID := baseIDs.NewIdentityID(classificationID, immutables) + keepers.BurnKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testAsset)) + + type fields struct { + mapper helpers.Mapper + defineAuxiliary helpers.Auxiliary + superAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + context sdkTypes.Context + msg sdkTypes.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, defineAuxiliary, superAuxiliary, authenticateAuxiliary}, args{context, newMessage(fromAccAddress, fromID, immutableMetaPropertiesLists, immutablePropertiesLists, mutableMetaPropertiesLists, mutablePropertiesLists)}, newTransactionResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + defineAuxiliary: tt.fields.defineAuxiliary, + superAuxiliary: tt.fields.superAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/assets/internal/transactions/define/message.go b/modules/assets/internal/transactions/define/message.go index 0c43b1dbc..143b15a25 100644 --- a/modules/assets/internal/transactions/define/message.go +++ b/modules/assets/internal/transactions/define/message.go @@ -1,72 +1,83 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/assets/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ImmutableMetaProperties lists.PropertyList `json:"immutableMetaProperties" valid:"required~required field immutableMetaProperties missing"` + ImmutableProperties lists.PropertyList `json:"immutableProperties" valid:"required~required field immutableProperties missing"` + MutableMetaProperties lists.PropertyList `json:"mutableMetaProperties" valid:"required~required field mutableMetaProperties missing"` + MutableProperties lists.PropertyList `json:"mutableProperties" valid:"required~required field mutableProperties missing"` +} + +var _ helpers.Message = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + if len(message.ImmutableMetaProperties.GetList()) == 0 { + message.ImmutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.ImmutableProperties.GetList()) == 0 { + message.ImmutableProperties = base.NewPropertyList(nil) + } + if len(message.MutableMetaProperties.GetList()) == 0 { + message.MutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.MutableProperties.GetList()) == 0 { + message.MutableProperties = base.NewPropertyList(nil) + } + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } - -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, immutableMetaProperties types.MetaProperties, immutableProperties types.Properties, mutableMetaProperties types.MetaProperties, mutableProperties types.Properties) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - ImmutableMetaProperties: *base.NewMetaProperties(immutableMetaProperties.GetList()...), - ImmutableProperties: *base.NewProperties(immutableProperties.GetList()...), - MutableMetaProperties: *base.NewMetaProperties(mutableMetaProperties.GetList()...), - MutableProperties: *base.NewProperties(mutableProperties.GetList()...), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, immutableMetaProperties lists.PropertyList, immutableProperties lists.PropertyList, mutableMetaProperties lists.PropertyList, mutableProperties lists.PropertyList) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + ImmutableMetaProperties: immutableMetaProperties, + ImmutableProperties: immutableProperties, + MutableMetaProperties: mutableMetaProperties, + MutableProperties: mutableProperties, } } diff --git a/modules/assets/internal/transactions/define/message.pb.go b/modules/assets/internal/transactions/define/message.pb.go deleted file mode 100644 index dcd2b8d3e..000000000 --- a/modules/assets/internal/transactions/define/message.pb.go +++ /dev/null @@ -1,775 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/assets/internal/transactions/define/message.proto - -package define - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:" required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:" required~required field FromID missing"` - ImmutableMetaProperties base.MetaProperties `protobuf:"bytes,3,opt,name=immutable_meta_properties,json=immutableMetaProperties,proto3" json:"immutable_meta_properties" valid:" required~required field ImmutableMetaProperties missing"` - ImmutableProperties base.Properties `protobuf:"bytes,4,opt,name=immutable_properties,json=immutableProperties,proto3" json:"immutable_properties" valid:" required~required field ImmutableProperties missing"` - MutableMetaProperties base.MetaProperties `protobuf:"bytes,5,opt,name=mutable_meta_properties,json=mutableMetaProperties,proto3" json:"mutable_meta_properties" valid:" required~required field MutableMetaProperties missing"` - MutableProperties base.Properties `protobuf:"bytes,6,opt,name=mutable_properties,json=mutableProperties,proto3" json:"mutable_properties" valid:" required~required field MutableProperties missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_66bf2f2d30cab6ba, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_66bf2f2d30cab6ba, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.assets.internal.transactions.define.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.assets.internal.transactions.define.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/assets/internal/transactions/define/message.proto", fileDescriptor_66bf2f2d30cab6ba) -} - -var fileDescriptor_66bf2f2d30cab6ba = []byte{ - // 562 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x95, 0x41, 0x6b, 0x13, 0x4f, - 0x18, 0xc6, 0x77, 0xfe, 0xed, 0x3f, 0xad, 0xeb, 0xc9, 0x6d, 0x4b, 0x63, 0x0e, 0xbb, 0x4b, 0x40, - 0x28, 0x42, 0x67, 0x30, 0x82, 0x42, 0x14, 0xb1, 0x61, 0x2d, 0x06, 0x09, 0x96, 0xda, 0x93, 0x97, - 0xb0, 0xd9, 0x7d, 0xb3, 0x1d, 0xcc, 0xee, 0xac, 0xf3, 0x4e, 0x44, 0x2f, 0x3d, 0x7b, 0x14, 0x3f, - 0x41, 0x4e, 0xe2, 0xd5, 0x93, 0x5f, 0xa1, 0xc7, 0x1e, 0x45, 0x24, 0x48, 0x72, 0xf1, 0xdc, 0x4f, - 0x20, 0xd9, 0x6c, 0x48, 0x9a, 0xac, 0x66, 0x6d, 0x4f, 0x99, 0xec, 0xce, 0xfb, 0x3c, 0xbf, 0x79, - 0x06, 0x9e, 0xd5, 0xeb, 0x31, 0x48, 0xe4, 0xa8, 0x20, 0xf2, 0xa0, 0x89, 0xfe, 0x2b, 0x16, 0x0a, - 0xbf, 0xdb, 0x01, 0x64, 0x2e, 0x22, 0x28, 0x64, 0x3c, 0x52, 0x20, 0x23, 0xb7, 0xc3, 0x94, 0x74, - 0x23, 0x74, 0x3d, 0xc5, 0x45, 0x84, 0xcc, 0x87, 0x36, 0x8f, 0x80, 0x85, 0x80, 0xe8, 0x06, 0x40, - 0x63, 0x29, 0x94, 0x30, 0x1e, 0xcc, 0x49, 0xd1, 0x54, 0x8a, 0x8e, 0xa5, 0xe8, 0x44, 0x8a, 0xce, - 0x4a, 0xd1, 0xb1, 0x54, 0x69, 0x33, 0x10, 0x81, 0x48, 0x74, 0xd8, 0x68, 0x35, 0x96, 0x2c, 0xdd, - 0x9e, 0xa7, 0x43, 0xef, 0x18, 0x42, 0x97, 0xa9, 0x77, 0x31, 0x20, 0x6b, 0xb9, 0x08, 0x8c, 0xfb, - 0xe9, 0xde, 0x7b, 0xcb, 0xf7, 0x86, 0xa0, 0xdc, 0x03, 0x29, 0x62, 0x90, 0x8a, 0x03, 0xa6, 0x73, - 0x95, 0xe5, 0x73, 0xf1, 0xdc, 0x4c, 0xf9, 0xc7, 0x9a, 0xbe, 0xd6, 0x18, 0x1f, 0xde, 0xf8, 0x48, - 0xf4, 0xd5, 0xb6, 0x14, 0x61, 0x91, 0xd8, 0x64, 0xe7, 0x5a, 0xed, 0xe4, 0xb4, 0x6f, 0x69, 0xdf, - 0xfb, 0xd6, 0x93, 0x80, 0xab, 0xe3, 0x6e, 0x8b, 0x7a, 0x22, 0x64, 0x33, 0x0e, 0xcf, 0x23, 0x98, - 0xfd, 0xfb, 0xc2, 0x79, 0xb6, 0xe8, 0x47, 0xf7, 0x3c, 0x6f, 0xcf, 0xf7, 0x25, 0x20, 0x9e, 0xf7, - 0xad, 0xdd, 0x37, 0x6e, 0x87, 0xfb, 0xd5, 0xb2, 0x2d, 0xe1, 0x75, 0x97, 0x4b, 0xf0, 0x4f, 0x26, - 0x0b, 0xbb, 0xcd, 0xa1, 0xe3, 0xdb, 0xfb, 0x52, 0x84, 0x76, 0xc8, 0x11, 0x79, 0x14, 0x94, 0x0f, - 0x13, 0x16, 0xe3, 0xad, 0xbe, 0x3e, 0xfa, 0x6d, 0xf2, 0xa6, 0x5f, 0xfc, 0xcf, 0x26, 0x3b, 0xd7, - 0x2b, 0xb7, 0xe8, 0xfc, 0xf5, 0x8c, 0x7d, 0x69, 0xe2, 0x4b, 0x13, 0xdf, 0xba, 0x53, 0xbb, 0x3f, - 0xc2, 0x3f, 0xef, 0x5b, 0x2c, 0x8f, 0x6b, 0xdd, 0x99, 0xfa, 0x16, 0xda, 0xc9, 0x03, 0xe3, 0x2b, - 0xd1, 0x6f, 0xf2, 0x30, 0xec, 0x2a, 0xb7, 0xd5, 0x81, 0xe6, 0x28, 0xf1, 0xe6, 0x34, 0xbe, 0xe2, - 0x4a, 0xc2, 0x72, 0x27, 0x07, 0x4b, 0xe3, 0xc2, 0x5d, 0xd5, 0x9e, 0xa6, 0x5c, 0x8f, 0x97, 0x71, - 0xd5, 0x27, 0xde, 0x17, 0x05, 0xa6, 0xa0, 0xdb, 0x3c, 0x7b, 0x87, 0xf1, 0x89, 0xe8, 0x9b, 0x53, - 0xf2, 0x19, 0xe8, 0xd5, 0x04, 0x7a, 0x37, 0x07, 0xf4, 0x0c, 0xb0, 0x93, 0x02, 0x3f, 0xcc, 0x0d, - 0x9c, 0x05, 0xbb, 0xc1, 0x17, 0xdf, 0x1a, 0x5f, 0x88, 0xbe, 0xfd, 0xa7, 0x80, 0xff, 0xbf, 0x6c, - 0xc0, 0xfb, 0x29, 0xef, 0xa3, 0x65, 0xbc, 0x8d, 0xbf, 0xc7, 0xbb, 0x95, 0x1d, 0x6e, 0x8f, 0xe8, - 0x46, 0x46, 0xb4, 0x85, 0xcb, 0x44, 0x5b, 0x4b, 0x51, 0xab, 0x39, 0x51, 0xb3, 0x30, 0x6f, 0x2c, - 0xc4, 0x5a, 0x5d, 0x7f, 0xdf, 0xb3, 0xb4, 0x5f, 0x3d, 0x4b, 0x2b, 0x6f, 0xe9, 0x1b, 0x47, 0xd3, - 0x8e, 0x3a, 0x04, 0x8c, 0x45, 0x84, 0x50, 0xf9, 0x4c, 0xf4, 0x95, 0x06, 0x06, 0xa3, 0xb3, 0x14, - 0x9c, 0xa4, 0xb6, 0x0c, 0x87, 0x5e, 0xa1, 0xf4, 0x68, 0x5a, 0x21, 0xa5, 0x83, 0x2b, 0xa9, 0x64, - 0xa0, 0xd6, 0xa2, 0xd3, 0x81, 0x49, 0xce, 0x06, 0x26, 0xf9, 0x39, 0x30, 0xc9, 0x87, 0xa1, 0xa9, - 0x9d, 0x0d, 0x4d, 0xed, 0xdb, 0xd0, 0xd4, 0x5e, 0x1e, 0xe5, 0xee, 0xa5, 0x7f, 0xf8, 0x12, 0xb4, - 0x0a, 0x49, 0x2f, 0xde, 0xfd, 0x1d, 0x00, 0x00, 0xff, 0xff, 0xb6, 0x33, 0xd6, 0x65, 0x4f, 0x06, - 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Define(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Define(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.assets.internal.transactions.define.Msg/Define", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Define(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Define(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Define not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Define_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Define(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.assets.internal.transactions.define.Msg/Define", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Define(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.assets.internal.transactions.define.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Define", - Handler: _Msg_Define_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/assets/internal/transactions/define/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.MutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.ImmutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ImmutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/assets/internal/transactions/define/message_test.go b/modules/assets/internal/transactions/define/message_test.go index b1506a2af..e1e933c0d 100644 --- a/modules/assets/internal/transactions/define/message_test.go +++ b/modules/assets/internal/transactions/define/message_test.go @@ -1,47 +1,297 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/assets/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Define_Message(t *testing.T) { - testFromID := base.NewID("fromID") - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, err) - - immutableMetaProperties, err := base.ReadMetaProperties("defaultImmutableMeta1:S|defaultImmutableMeta1") - require.Equal(t, nil, err) - immutableProperties, err := base.ReadProperties("defaultImmutable1:S|defaultImmutable1") - require.Equal(t, nil, err) - mutableMetaProperties, err := base.ReadMetaProperties("defaultMutableMeta1:S|defaultMutableMeta1") - require.Equal(t, nil, err) - mutableProperties, err := base.ReadProperties("defaultMutable1:S|defaultMutable1") - require.Equal(t, nil, err) - - testMessage := newMessage(fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties) - require.Equal(t, Message{From: base.NewAccAddressFromSDKTypesAccAddress(fromAccAddress), FromID: testFromID, ImmutableMetaProperties: immutableMetaProperties, ImmutableProperties: immutableProperties, MutableMetaProperties: mutableMetaProperties, MutableProperties: mutableProperties}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +var ( + immutableMetaProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutableProperties = baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutables = baseQualified.NewImmutables(immutableMetaProperties) + mutableMetaProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutableProperties = baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutables = baseQualified.NewMutables(mutableMetaProperties) + classificationID = baseIDs.NewClassificationID(immutables, mutables) + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = sdkTypes.AccAddressFromBech32(fromAddress) + fromID = baseIDs.NewIdentityID(classificationID, immutables) +) + +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{newMessage(fromAccAddress, fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)}, newMessage(fromAccAddress, fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties).(message)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(newMessage(fromAccAddress, fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, false}, + {"-ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + immutableMetaProperties lists.PropertyList + immutableProperties lists.PropertyList + mutableMetaProperties lists.PropertyList + mutableProperties lists.PropertyList + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, newMessage(fromAccAddress, fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/assets/internal/transactions/define/msg_server.go b/modules/assets/internal/transactions/define/msg_server.go deleted file mode 100644 index d79fa76e9..000000000 --- a/modules/assets/internal/transactions/define/msg_server.go +++ /dev/null @@ -1,53 +0,0 @@ -package define - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/define" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/super" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Define(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - immutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(message.ImmutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - immutableProperties := base.NewProperties(append(immutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...)...) - - mutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(message.MutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - mutableProperties := base.NewProperties(append(mutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...) - - classificationID, Error := define.GetClassificationIDFromResponse(msgServer.transactionKeeper.defineAuxiliary.GetKeeper().Help(ctx, define.NewAuxiliaryRequest(immutableProperties, mutableProperties))) - if Error != nil { - return nil, Error - } - - if auxiliaryResponse := msgServer.transactionKeeper.superAuxiliary.GetKeeper().Help(ctx, super.NewAuxiliaryRequest(classificationID, &message.FromID, mutableProperties)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/assets/internal/transactions/define/request.go b/modules/assets/internal/transactions/define/request.go index 7d778db34..1b26f728a 100644 --- a/modules/assets/internal/transactions/define/request.go +++ b/modules/assets/internal/transactions/define/request.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define @@ -9,15 +7,19 @@ import ( "encoding/json" "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers/base" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -31,33 +33,40 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary define asset transaction -// @Descrption define asset with mutable immutable properties +// Validate godoc +// @Summary Define an asset transaction +// @Description Define asset with mutable immutable properties // @Accept text/plain // @Produce json // @Tags Assets -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body transactionRequest true "A transaction to define the asset." +// @Success 200 {object} transactionResponse "Message for a successful transaction." +// @Failure default {object} transactionResponse "Message for an unexpected error in the transaction." // @Router /assets/define [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + if err != nil { + return err + } + inputValidator := base.NewInputValidator(constants.PropertyExpression) + if !inputValidator.IsValid(transactionRequest.ImmutableProperties, transactionRequest.ImmutableMetaProperties, transactionRequest.MutableProperties, transactionRequest.MutableMetaProperties) { + return errorConstants.IncorrectFormat + } + return nil } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ImmutableMetaProperties), - cliCommand.ReadString(flags.ImmutableProperties), - cliCommand.ReadString(flags.MutableMetaProperties), - cliCommand.ReadString(flags.MutableProperties), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ImmutableMetaProperties), + cliCommand.ReadString(constants.ImmutableProperties), + cliCommand.ReadString(constants.MutableMetaProperties), + cliCommand.ReadString(constants.MutableProperties), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -66,42 +75,49 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + immutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableMetaProperties) + if err != nil { + return nil, err } - immutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.ImmutableMetaProperties) - if Error != nil { - return nil, Error + immutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableProperties) + if err != nil { + return nil, err } + immutableProperties = immutableProperties.ScrubData() - immutableProperties, Error := base.ReadProperties(transactionRequest.ImmutableProperties) - if Error != nil { - return nil, Error + mutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableMetaProperties) + if err != nil { + return nil, err } - mutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.MutableMetaProperties) - if Error != nil { - return nil, Error + mutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableProperties) + if err != nil { + return nil, err } + mutableProperties = mutableProperties.ScrubData() - mutableProperties, Error := base.ReadProperties(transactionRequest.MutableProperties) - if Error != nil { - return nil, Error + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), + fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/assets/internal/transactions/define/request_test.go b/modules/assets/internal/transactions/define/request_test.go index 193c22aaf..90652a9a1 100644 --- a/modules/assets/internal/transactions/define/request_test.go +++ b/modules/assets/internal/transactions/define/request_test.go @@ -1,107 +1,312 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define import ( "encoding/json" - cryptoCodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "fmt" + "reflect" "testing" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - vestingTypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" -) - -func Test_Define_Request(t *testing.T) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptocryptoCodec.RegisterCrypto(Codec) - vestingTypes.RegisterLegacyAminoCodec(Codec) - codec.RegisterEvidences(Codec) - - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.ImmutableMetaProperties, flags.ImmutableProperties, flags.MutableMetaProperties, flags.MutableProperties}) - cliContext := client.Context{}.WithLegacyAmino(Codec) - - immutableMetaPropertiesString := "defaultImmutableMeta1:S|defaultImmutableMeta1" - immutablePropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" - mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" - mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - - immutableMetaProperties, Error := base.ReadMetaProperties(immutableMetaPropertiesString) - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties(immutablePropertiesString) - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties(mutableMetaPropertiesString) - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties(mutablePropertiesString) - require.Equal(t, nil, Error) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString) - - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) - - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ImmutableMetaProperties: "", ImmutableProperties: "", MutableMetaProperties: "", MutableProperties: ""}, requestFromCLI) + "github.com/spf13/viper" - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) - - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/utilities/transaction" +) - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +var ( + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + immutableMetaPropertiesString = "testImmutableMeta1:S|immutableMeta" + immutableMetaProperties1 = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("testImmutableMeta1"), baseData.NewStringData("immutableMeta"))) + immutablePropertiesString = "testImmutable1:S|immutable" + immutableProperties1 = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("testImmutable1"), baseData.NewStringData("immutable"))) + mutableMetaPropertiesString = "testMutableMeta1:S|mutableMeta" + mutableMetaProperties1 = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("testMutableMeta1"), baseData.NewStringData("mutableMeta"))) + mutablePropertiesString = "testMutable1:S|mutable" + mutableProperties1 = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("testMutable1"), baseData.NewStringData("mutable"))) +) - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties), msg) - require.Nil(t, Error) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + immutableMetaProperties string + immutableProperties string + mutableMetaProperties string + mutableProperties string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, fromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, transactionRequest{testBaseRequest, fromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, "fromID", "randomString", immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.ImmutableMetaProperties, constants.ImmutableProperties, constants.MutableMetaProperties, constants.MutableProperties}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.ImmutableMetaProperties.GetName(), immutableMetaPropertiesString) + viper.Set(constants.ImmutableProperties.GetName(), immutablePropertiesString) + viper.Set(constants.MutableMetaProperties.GetName(), mutableMetaPropertiesString) + viper.Set(constants.MutableProperties.GetName(), mutablePropertiesString) + viper.Set(constants.FromID.GetName(), fromID.String()) + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, cliContext}, transactionRequest{testBaseRequest, fromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, "fromID", immutableMetaPropertiesString, "randomString", mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_FromJSON(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}))}, newTransactionRequest(testBaseRequest, fromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, "fromID", immutableMetaPropertiesString, immutablePropertiesString, "randomString", mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, fromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, "fromID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, "randomString").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, newMessage(fromAccAddress, fromID, immutableMetaProperties1, immutableProperties1.ScrubData(), mutableMetaProperties1, mutableProperties1.ScrubData()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.NewLegacyAmino()) - }) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, fromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/assets/internal/transactions/define/response.go b/modules/assets/internal/transactions/define/response.go new file mode 100644 index 000000000..bd134e694 --- /dev/null +++ b/modules/assets/internal/transactions/define/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/assets/internal/transactions/define/response_test.go b/modules/assets/internal/transactions/define/response_test.go new file mode 100644 index 000000000..fb19768c7 --- /dev/null +++ b/modules/assets/internal/transactions/define/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Define_Response(t *testing.T) { + testTransactionResponse := newTransactionResponse(constants.IncorrectFormat) + testTransactionResponse2 := newTransactionResponse(nil) + + require.Equal(t, transactionResponse{Success: false, Error: constants.IncorrectFormat}, testTransactionResponse) + require.Equal(t, false, testTransactionResponse.IsSuccessful()) + require.Equal(t, true, testTransactionResponse2.IsSuccessful()) + + require.Equal(t, constants.IncorrectFormat, testTransactionResponse.GetError()) + require.Equal(t, nil, testTransactionResponse2.GetError()) +} diff --git a/modules/assets/internal/transactions/define/transaction.go b/modules/assets/internal/transactions/define/transaction.go new file mode 100644 index 000000000..f4c9961d7 --- /dev/null +++ b/modules/assets/internal/transactions/define/transaction.go @@ -0,0 +1,25 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "define", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.ImmutableMetaProperties, + constants.ImmutableProperties, + constants.MutableMetaProperties, + constants.MutableProperties, +) diff --git a/modules/assets/internal/transactions/deputize/keeper.go b/modules/assets/internal/transactions/deputize/keeper.go new file mode 100644 index 000000000..d72f4b712 --- /dev/null +++ b/modules/assets/internal/transactions/deputize/keeper.go @@ -0,0 +1,57 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/deputize" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + deputizeAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + if auxiliaryResponse := transactionKeeper.deputizeAuxiliary.GetKeeper().Help(context, deputize.NewAuxiliaryRequest(message.FromID, message.ToID, message.ClassificationID, message.MaintainedProperties, message.CanMintAsset, message.CanBurnAsset, message.CanRenumerateAsset, message.CanAddMaintainer, message.CanRemoveMaintainer, message.CanMutateMaintainer)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + return newTransactionResponse(nil) +} +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case deputize.Auxiliary.GetName(): + transactionKeeper.deputizeAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(constants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/assets/internal/transactions/deputize/keeper_test.go b/modules/assets/internal/transactions/deputize/keeper_test.go new file mode 100644 index 000000000..e50bd9c35 --- /dev/null +++ b/modules/assets/internal/transactions/deputize/keeper_test.go @@ -0,0 +1,184 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + "github.com/AssetMantle/modules/modules/assets/internal/parameters" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/deputize" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +var ( + authenticateAuxiliary helpers.Auxiliary + deputizeAuxiliary helpers.Auxiliary +) + +type TestKeepers struct { + DeputizeKeeper helpers.TransactionKeeper +} + +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + deputizeAuxiliary = deputize.AuxiliaryMock.Initialize(Mapper, Parameters) + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + + keepers := TestKeepers{ + DeputizeKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), + } + + return context, keepers, Mapper, Parameters +} + +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + deputizeAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper, Parameters, authenticateAuxiliary, deputizeAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, authenticateAuxiliary, deputizeAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + deputizeAuxiliary: tt.fields.deputizeAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters := createTestInput(t) + immutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutables := baseQualified.NewImmutables(immutableProperties) + mutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutables := baseQualified.NewMutables(mutableProperties) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + testAsset := base.NewAsset(classificationID, immutables, mutables) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + fromID := baseIDs.NewIdentityID(classificationID, immutables) + keepers.DeputizeKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testAsset)) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + deputizeAuxiliary helpers.Auxiliary + } + type args struct { + context sdkTypes.Context + msg sdkTypes.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, Parameters, authenticateAuxiliary, deputizeAuxiliary}, args{context, newMessage(fromAccAddress, fromID, fromID, classificationID, mutableProperties, true, true, true, true, true, true)}, newTransactionResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + deputizeAuxiliary: tt.fields.deputizeAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/assets/internal/transactions/deputize/message.go b/modules/assets/internal/transactions/deputize/message.go index 8af9efd02..30df385db 100644 --- a/modules/assets/internal/transactions/deputize/message.go +++ b/modules/assets/internal/transactions/deputize/message.go @@ -1,74 +1,85 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/assets/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ToID ids.IdentityID `json:"toID" valid:"required~required field toID missing"` + ids.ClassificationID `json:"classificationID" valid:"required~required field classificationID missing"` + MaintainedProperties lists.PropertyList `json:"maintainedProperties" valid:"required~required field maintainedProperties missing"` + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + if len(message.MaintainedProperties.GetList()) == 0 { + message.MaintainedProperties = base.NewPropertyList(nil) + } + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, toID types.ID, classificationID types.ID, maintainedProperties types.Properties, addMaintainer bool, removeMaintainer bool, mutateMaintainer bool) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - ToID: *base.NewID(toID.String()), - ClassificationID: *base.NewID(classificationID.String()), - MaintainedProperties: *base.NewProperties(maintainedProperties.GetList()...), - AddMaintainer: addMaintainer, - RemoveMaintainer: removeMaintainer, - MutateMaintainer: mutateMaintainer, +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, toID ids.IdentityID, classificationID ids.ClassificationID, maintainedProperties lists.PropertyList, canMintAsset bool, canBurnAsset bool, canRenumerateAsset bool, canAddMaintainer bool, canRemoveMaintainer bool, canMutateMaintainer bool) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + ToID: toID, + ClassificationID: classificationID, + MaintainedProperties: maintainedProperties, + CanMintAsset: canMintAsset, + CanBurnAsset: canBurnAsset, + CanRenumerateAsset: canRenumerateAsset, + CanAddMaintainer: canAddMaintainer, + CanRemoveMaintainer: canRemoveMaintainer, + CanMutateMaintainer: canMutateMaintainer, } } diff --git a/modules/assets/internal/transactions/deputize/message.pb.go b/modules/assets/internal/transactions/deputize/message.pb.go deleted file mode 100644 index 80d222317..000000000 --- a/modules/assets/internal/transactions/deputize/message.pb.go +++ /dev/null @@ -1,832 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/assets/internal/transactions/deputize/message.proto - -package deputize - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - ToID base.ID `protobuf:"bytes,3,opt,name=to_i_d,json=toID,proto3" json:"to_i_d" valid:"required~required field ToID missing"` - ClassificationID base.ID `protobuf:"bytes,4,opt,name=classification_i_d,json=classificationID,proto3" json:"classification_i_d" valid:"required~required field ClassificationID missing"` - MaintainedProperties base.Properties `protobuf:"bytes,5,opt,name=maintained_properties,json=maintainedProperties,proto3" json:"maintained_properties" valid:"required~required field MaintainedProperties missing"` - AddMaintainer bool `protobuf:"varint,6,opt,name=add_maintainer,json=addMaintainer,proto3" json:"add_maintainer,omitempty"` - RemoveMaintainer bool `protobuf:"varint,7,opt,name=remove_maintainer,json=removeMaintainer,proto3" json:"remove_maintainer,omitempty"` - MutateMaintainer bool `protobuf:"varint,8,opt,name=mutate_maintainer,json=mutateMaintainer,proto3" json:"mutate_maintainer,omitempty"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_82246bffc874f60b, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_82246bffc874f60b, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.assets.internal.transactions.deputize.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.assets.internal.transactions.deputize.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/assets/internal/transactions/deputize/message.proto", fileDescriptor_82246bffc874f60b) -} - -var fileDescriptor_82246bffc874f60b = []byte{ - // 584 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x94, 0xcf, 0x6b, 0xd4, 0x40, - 0x14, 0xc7, 0x77, 0x6c, 0xdd, 0xae, 0x23, 0x4a, 0x8d, 0x2d, 0x2c, 0x3d, 0x24, 0x61, 0xa1, 0x50, - 0xfc, 0x31, 0x81, 0x2a, 0x22, 0x45, 0xc1, 0xae, 0xb1, 0x50, 0x4a, 0x51, 0xd6, 0xe2, 0xc1, 0xcb, - 0x32, 0xcd, 0xbc, 0x4d, 0x07, 0x37, 0x99, 0x74, 0xde, 0x6c, 0x45, 0x41, 0xcf, 0x1e, 0xf5, 0xe0, - 0xbd, 0x27, 0xf1, 0xe4, 0xdf, 0xd1, 0x63, 0x6f, 0x8a, 0x87, 0x45, 0xda, 0x8b, 0xe7, 0xfe, 0x05, - 0xb2, 0x49, 0xba, 0x49, 0xd7, 0xc2, 0xb6, 0xf4, 0x94, 0x49, 0xde, 0x77, 0xbe, 0x9f, 0xef, 0x84, - 0x79, 0x8f, 0xae, 0x25, 0xa0, 0x51, 0xa2, 0x81, 0x38, 0x80, 0x36, 0x8a, 0x37, 0x5e, 0xa4, 0x44, - 0xaf, 0x0b, 0xe8, 0x71, 0x44, 0x30, 0xe8, 0xc9, 0xd8, 0x80, 0x8e, 0x79, 0xd7, 0x33, 0x9a, 0xc7, - 0xc8, 0x03, 0x23, 0x55, 0x8c, 0x9e, 0x80, 0xa4, 0x67, 0xe4, 0x7b, 0xf0, 0x22, 0x40, 0xe4, 0x21, - 0xb0, 0x44, 0x2b, 0xa3, 0xac, 0xc7, 0x23, 0x66, 0x2c, 0x37, 0x63, 0x99, 0x19, 0x3b, 0x36, 0x63, - 0x65, 0x33, 0x76, 0x6c, 0x36, 0x37, 0x13, 0xaa, 0x50, 0xa5, 0x4e, 0xde, 0x60, 0x95, 0x99, 0xce, - 0xdd, 0x1a, 0x4d, 0x88, 0xc1, 0x16, 0x44, 0xdc, 0x33, 0xef, 0x12, 0x40, 0x6f, 0x93, 0x23, 0x78, - 0x52, 0xe4, 0xda, 0xc5, 0xf1, 0xda, 0x44, 0xab, 0x04, 0xb4, 0x91, 0x80, 0xd9, 0x9e, 0xc6, 0xcf, - 0x2a, 0x9d, 0x5a, 0xcf, 0x8e, 0x61, 0x7d, 0x21, 0x74, 0xb2, 0xa3, 0x55, 0x54, 0x27, 0x2e, 0x59, - 0xb8, 0xd2, 0xfc, 0xb0, 0xd7, 0x77, 0x2a, 0xbf, 0xfb, 0xce, 0xb3, 0x50, 0x9a, 0xad, 0xde, 0x26, - 0x0b, 0x54, 0xe4, 0x95, 0x08, 0xcf, 0x63, 0x28, 0xbf, 0xbe, 0xf4, 0xd7, 0xfe, 0xe7, 0xb1, 0xe5, - 0x20, 0x58, 0x16, 0x42, 0x03, 0xe2, 0x51, 0xdf, 0xb9, 0xb3, 0xc3, 0xbb, 0x52, 0x2c, 0x35, 0x34, - 0x6c, 0xf7, 0xa4, 0x06, 0xf1, 0xf1, 0x78, 0xe1, 0x76, 0x24, 0x74, 0x85, 0xbb, 0xa2, 0x55, 0xe4, - 0x46, 0x12, 0x51, 0xc6, 0x61, 0xa3, 0x95, 0x46, 0xb1, 0xde, 0xd2, 0xda, 0xe0, 0xd9, 0x96, 0x6d, - 0x51, 0xbf, 0xe4, 0x92, 0x85, 0xab, 0x8b, 0xf3, 0x6c, 0xf4, 0x3f, 0x67, 0x58, 0x96, 0x62, 0x59, - 0x8a, 0x5d, 0xf5, 0x9b, 0x0f, 0x06, 0xe9, 0x8f, 0xfa, 0x0e, 0x3b, 0x03, 0x74, 0xd5, 0x2f, 0xb0, - 0xd5, 0x4e, 0xfa, 0xc1, 0xda, 0xa6, 0x55, 0xa3, 0x52, 0xec, 0xc4, 0x79, 0xb0, 0xf7, 0x73, 0xec, - 0xb8, 0xb3, 0x6e, 0xa8, 0x32, 0x74, 0xd2, 0xa8, 0x55, 0xdf, 0xfa, 0x4a, 0xa8, 0x15, 0x74, 0x39, - 0xa2, 0xec, 0xc8, 0x80, 0x0f, 0xae, 0x47, 0xca, 0x9f, 0x3c, 0x0f, 0xff, 0x49, 0xce, 0x7f, 0x38, - 0x86, 0xff, 0xf4, 0x04, 0xa7, 0x9c, 0x65, 0x3a, 0x18, 0x29, 0x59, 0xdf, 0x09, 0x9d, 0x8d, 0xb8, - 0x8c, 0x0d, 0x97, 0x31, 0x88, 0x76, 0x71, 0x87, 0xea, 0x97, 0xd3, 0x68, 0x77, 0xcf, 0x10, 0xed, - 0xc5, 0x70, 0x53, 0xd3, 0xcf, 0x23, 0x3e, 0x1a, 0x13, 0x71, 0x7d, 0x88, 0x2c, 0x36, 0x17, 0x31, - 0x67, 0xa2, 0x53, 0xca, 0xd6, 0x3c, 0xbd, 0xce, 0x85, 0x68, 0x0f, 0x6b, 0xba, 0x5e, 0x75, 0xc9, - 0x42, 0xad, 0x75, 0x8d, 0x0b, 0x31, 0xf4, 0xd3, 0xd6, 0x6d, 0x7a, 0x43, 0x43, 0xa4, 0x76, 0xa0, - 0xac, 0x9c, 0x4a, 0x95, 0xd3, 0x59, 0xe1, 0xa4, 0x38, 0xea, 0x19, 0x6e, 0x4e, 0x88, 0x6b, 0x99, - 0x38, 0x2b, 0x14, 0xe2, 0xa5, 0xda, 0xa7, 0x5d, 0xa7, 0xf2, 0x77, 0xd7, 0xa9, 0x34, 0x66, 0xe9, - 0xcd, 0x8d, 0xa2, 0xd1, 0x5b, 0x80, 0x89, 0x8a, 0x11, 0x16, 0x7f, 0x10, 0x3a, 0xb1, 0x8e, 0xa1, - 0xf5, 0x8d, 0xd0, 0x9a, 0x9f, 0xf7, 0xbe, 0xb5, 0xc2, 0x2e, 0x34, 0x3b, 0x58, 0xde, 0xc1, 0x73, - 0xad, 0x0b, 0xfa, 0x9c, 0x12, 0xb8, 0x99, 0xec, 0x1d, 0xd8, 0x64, 0xff, 0xc0, 0x26, 0x7f, 0x0e, - 0x6c, 0xf2, 0xf9, 0xd0, 0xae, 0xec, 0x1f, 0xda, 0x95, 0x5f, 0x87, 0x76, 0xe5, 0xf5, 0xab, 0x33, - 0x0f, 0x86, 0x73, 0x8d, 0xd5, 0xcd, 0x6a, 0x3a, 0x9a, 0xee, 0xfd, 0x0b, 0x00, 0x00, 0xff, 0xff, - 0x60, 0x40, 0x81, 0xd6, 0x9e, 0x05, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Deputize(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Deputize(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.assets.internal.transactions.deputize.Msg/Deputize", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Deputize(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Deputize(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deputize not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Deputize_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Deputize(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.assets.internal.transactions.deputize.Msg/Deputize", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Deputize(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.assets.internal.transactions.deputize.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Deputize", - Handler: _Msg_Deputize_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/assets/internal/transactions/deputize/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.MutateMaintainer { - i-- - if m.MutateMaintainer { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x40 - } - if m.RemoveMaintainer { - i-- - if m.RemoveMaintainer { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x38 - } - if m.AddMaintainer { - i-- - if m.AddMaintainer { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x30 - } - { - size, err := m.MaintainedProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.ClassificationID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ToID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ToID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ClassificationID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MaintainedProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - if m.AddMaintainer { - n += 2 - } - if m.RemoveMaintainer { - n += 2 - } - if m.MutateMaintainer { - n += 2 - } - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ToID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ToID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaintainedProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MaintainedProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AddMaintainer", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.AddMaintainer = bool(v != 0) - case 7: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field RemoveMaintainer", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.RemoveMaintainer = bool(v != 0) - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MutateMaintainer", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.MutateMaintainer = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/assets/internal/transactions/deputize/message_test.go b/modules/assets/internal/transactions/deputize/message_test.go index 9eee73f5f..add09ba61 100644 --- a/modules/assets/internal/transactions/deputize/message_test.go +++ b/modules/assets/internal/transactions/deputize/message_test.go @@ -1,44 +1,359 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" - "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/assets/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" +) + +var ( + immutables = baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutableMetaProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutables = baseQualified.NewMutables(mutableMetaProperties) + classificationID = baseIDs.NewClassificationID(immutables, mutables) + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = sdkTypes.AccAddressFromBech32(fromAddress) + fromID = baseIDs.NewIdentityID(classificationID, immutables) ) -func Test_Deputize_Message(t *testing.T) { +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{newMessage(fromAccAddress, fromID, fromID, classificationID, mutableMetaProperties, true, true, true, true, true, true)}, newMessage(fromAccAddress, fromID, fromID, classificationID, mutableMetaProperties, true, true, true, true, true, true).(message)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + tests := []struct { + name string + fields fields + want []byte + }{{"+ve", fields{fromAccAddress, fromID, fromID, classificationID, mutableMetaProperties, true, true, true, true, true, true}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(newMessage(fromAccAddress, fromID, fromID, classificationID, mutableMetaProperties, true, true, true, true, true, true)))}} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} - testFromID := base.NewID("fromID") - testToID := base.NewID("toID") - testClassificationID := base.NewID("classificationID") +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID, mutableMetaProperties, true, true, true, true, true, true}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve with nil", fields{}, args{codec.New()}}, + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID, mutableMetaProperties, true, true, true, true, true, true}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + me.RegisterCodec(tt.args.codec) + }) + } +} - maintainedProperty := "maintainedProperty:S|maintainedProperty" - maintainedProperties, Error := base.ReadProperties(maintainedProperty) - require.Equal(t, nil, Error) +func Test_message_Route(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID, mutableMetaProperties, true, true, true, true, true, true}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} - testMessage := newMessage(fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false) - require.Equal(t, Message{From: base.NewAccAddressFromSDKTypesAccAddress(fromAccAddress), FromID: testFromID, ToID: testToID, ClassificationID: testClassificationID, MaintainedProperties: maintainedProperties, AddMaintainer: false, RemoveMaintainer: false, MutateMaintainer: false}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +func Test_message_Type(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID, mutableMetaProperties, true, true, true, true, true, true}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"-ve", fields{}, true}, + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID, mutableMetaProperties, true, true, true, true, true, true}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + toID ids.IdentityID + classificationID ids.ClassificationID + maintainedProperties lists.PropertyList + canMintAsset bool + canBurnAsset bool + canRenumerateAsset bool + canAddMaintainer bool + canRemoveMaintainer bool + canMutateMaintainer bool + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{}, message{}}, + {"+ve", args{fromAccAddress, fromID, fromID, classificationID, mutableMetaProperties, true, true, true, true, true, true}, message{fromAccAddress, fromID, fromID, classificationID, mutableMetaProperties, true, true, true, true, true, true}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.toID, tt.args.classificationID, tt.args.maintainedProperties, tt.args.canMintAsset, tt.args.canBurnAsset, tt.args.canRenumerateAsset, tt.args.canAddMaintainer, tt.args.canRemoveMaintainer, tt.args.canMutateMaintainer); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/assets/internal/transactions/deputize/msg_server.go b/modules/assets/internal/transactions/deputize/msg_server.go deleted file mode 100644 index 1651304d2..000000000 --- a/modules/assets/internal/transactions/deputize/msg_server.go +++ /dev/null @@ -1,31 +0,0 @@ -package deputize - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/deputize" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Deputize(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - if auxiliaryResponse := msgServer.transactionKeeper.deputizeAuxiliary.GetKeeper().Help(ctx, deputize.NewAuxiliaryRequest(&message.FromID, &message.ToID, &message.ClassificationID, &message.MaintainedProperties, message.AddMaintainer, message.RemoveMaintainer, message.MutateMaintainer)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/assets/internal/transactions/deputize/request.go b/modules/assets/internal/transactions/deputize/request.go index b3b78c612..6cca6da15 100644 --- a/modules/assets/internal/transactions/deputize/request.go +++ b/modules/assets/internal/transactions/deputize/request.go @@ -1,22 +1,25 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( "encoding/json" + + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -25,42 +28,55 @@ type transactionRequest struct { ToID string `json:"toID" valid:"required~required field toID missing, matches(^[A-Za-z0-9-_=.|]+$)~invalid field toID"` ClassificationID string `json:"classificationID" valid:"required~required field classificationID missing, matches(^[A-Za-z0-9-_=.]+$)~invalid field classificationID"` MaintainedProperties string `json:"maintainedProperties" valid:"required~required field maintainedProperties missing, matches(^.*$)~invalid field maintainedProperties"` - AddMaintainer bool `json:"addMaintainer"` - RemoveMaintainer bool `json:"removeMaintainer"` - MutateMaintainer bool `json:"mutateMaintainer"` + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` } var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary deputize asset transaction -// @Descrption deputize asset +// Validate godoc +// @Summary Deputize an asset transaction +// @Description Deputize asset // @Accept text/plain // @Produce json // @Tags Assets // @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /assets/deputize [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + if err != nil { + return err + } + inputValidator := base.NewInputValidator(constants.PropertyExpression) + if !inputValidator.IsValid(transactionRequest.MaintainedProperties) { + return errorConstants.IncorrectFormat + } + return nil } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ToID), - cliCommand.ReadString(flags.ClassificationID), - cliCommand.ReadString(flags.MaintainedProperties), - cliCommand.ReadBool(flags.AddMaintainer), - cliCommand.ReadBool(flags.RemoveMaintainer), - cliCommand.ReadBool(flags.MutateMaintainer), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ToID), + cliCommand.ReadString(constants.ClassificationID), + cliCommand.ReadString(constants.MaintainedProperties), + cliCommand.ReadBool(constants.CanMintAsset), + cliCommand.ReadBool(constants.CanBurnAsset), + cliCommand.ReadBool(constants.CanRenumerateAsset), + cliCommand.ReadBool(constants.CanAddMaintainer), + cliCommand.ReadBool(constants.CanRemoveMaintainer), + cliCommand.ReadBool(constants.CanMutateMaintainer), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -69,43 +85,64 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + maintainedProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MaintainedProperties) + if err != nil { + return nil, err + } + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + toID, err := baseIDs.ReadIdentityID(transactionRequest.ToID) + if err != nil { + return nil, err } - maintainedProperties, Error := base.ReadProperties(transactionRequest.MaintainedProperties) - if Error != nil { - return nil, Error + classificationID, err := baseIDs.ReadClassificationID(transactionRequest.ClassificationID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.ToID), - base.NewID(transactionRequest.ClassificationID), + fromID, + toID, + classificationID, maintainedProperties, - transactionRequest.AddMaintainer, - transactionRequest.RemoveMaintainer, - transactionRequest.MutateMaintainer, + transactionRequest.CanMintAsset, + transactionRequest.CanBurnAsset, + transactionRequest.CanRenumerateAsset, + transactionRequest.CanAddMaintainer, + transactionRequest.CanRemoveMaintainer, + transactionRequest.CanMutateMaintainer, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} } -func newTransactionRequest(baseReq rest.BaseReq, fromID string, toID string, classificationID string, maintainedProperties string, addMaintainer bool, removeMaintainer bool, mutateMaintainer bool) helpers.TransactionRequest { +func newTransactionRequest(baseReq rest.BaseReq, fromID string, toID string, classificationID string, maintainedProperties string, canMintAsset bool, canBurnAsset bool, canRenumerateAsset bool, canAddMaintainer bool, canRemoveMaintainer bool, canMutateMaintainer bool) helpers.TransactionRequest { return transactionRequest{ BaseReq: baseReq, FromID: fromID, ToID: toID, ClassificationID: classificationID, MaintainedProperties: maintainedProperties, - AddMaintainer: addMaintainer, - RemoveMaintainer: removeMaintainer, - MutateMaintainer: mutateMaintainer, + CanMintAsset: canMintAsset, + CanBurnAsset: canBurnAsset, + CanRenumerateAsset: canRenumerateAsset, + CanAddMaintainer: canAddMaintainer, + CanRemoveMaintainer: canRemoveMaintainer, + CanMutateMaintainer: canMutateMaintainer, } } diff --git a/modules/assets/internal/transactions/deputize/request_test.go b/modules/assets/internal/transactions/deputize/request_test.go index 7f14836c3..b108cc72e 100644 --- a/modules/assets/internal/transactions/deputize/request_test.go +++ b/modules/assets/internal/transactions/deputize/request_test.go @@ -1,82 +1,377 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( "encoding/json" - cryptoCodec "github.com/cosmos/cosmos-sdk/crypto/codec" - vestingTypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" + "fmt" + "reflect" "testing" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" -) - -func Test_Deputize_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptocryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vestingTypes.RegisterLegacyAminoCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.ToID, flags.ClassificationID, flags.MaintainedProperties, flags.AddMaintainer, flags.RemoveMaintainer, flags.MutateMaintainer}) - cliContext := client.Context{}.WithLegacyAmino(Codec) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - maintainedProperty := "maintainedProperties:S|maintainedProperties" - maintainedProperties, Error := base.ReadProperties(maintainedProperty) - require.Equal(t, nil, Error) + "github.com/spf13/viper" - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID", maintainedProperty, false, false, false) + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/utilities/transaction" +) - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ToID: "toID", ClassificationID: "classificationID", MaintainedProperties: maintainedProperty, AddMaintainer: false, RemoveMaintainer: false, MutateMaintainer: false}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) +var ( + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + mutableMetaPropertiesString = "testMutableMeta1:S|mutableMeta" + mutableMetaProperties1 = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("testMutableMeta1"), baseData.NewStringData("mutableMeta"))) +) - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ToID: "", ClassificationID: "", MaintainedProperties: "", AddMaintainer: false, RemoveMaintainer: false, MutateMaintainer: false}, requestFromCLI) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + toID string + classificationID string + maintainedProperties string + canMintAsset bool + canBurnAsset bool + canRenumerateAsset bool + canAddMaintainer bool + canRemoveMaintainer bool + canMutateMaintainer bool + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), fmt.Sprint(mutableMetaProperties), true, true, true, true, true, true}, transactionRequest{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), fmt.Sprint(mutableMetaProperties), true, true, true, true, true, true}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.toID, tt.args.classificationID, tt.args.maintainedProperties, tt.args.canMintAsset, tt.args.canBurnAsset, tt.args.canRenumerateAsset, tt.args.canAddMaintainer, tt.args.canRemoveMaintainer, tt.args.canMutateMaintainer); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.ToID, constants.FromID, constants.ClassificationID, constants.MaintainedProperties, constants.CanMintAsset, constants.CanBurnAsset, constants.CanRenumerateAsset, constants.CanAddMaintainer, constants.CanRemoveMaintainer, constants.CanMutateMaintainer}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.ToID.GetName(), fromID.String()) + viper.Set(constants.FromID.GetName(), fromID.String()) + viper.Set(constants.ClassificationID.GetName(), classificationID.String()) + viper.Set(constants.MaintainedProperties.GetName(), mutableMetaPropertiesString) + viper.Set(constants.CanMintAsset.GetName(), true) + viper.Set(constants.CanBurnAsset.GetName(), true) + viper.Set(constants.CanRenumerateAsset.GetName(), true) + viper.Set(constants.CanAddMaintainer.GetName(), true) + viper.Set(constants.CanRemoveMaintainer.GetName(), true) + viper.Set(constants.CanMutateMaintainer.GetName(), true) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{}, args{cliCommand, cliContext}, transactionRequest{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), mutableMetaPropertiesString, true, true, true, true, true, true}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromJSON(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), fmt.Sprint(mutableMetaProperties), true, true, true, true, true, true}, args{types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, fromID, fromID, classificationID, mutableMetaProperties, true, true, true, true, true, true}))}, transactionRequest{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), fmt.Sprint(mutableMetaProperties), true, true, true, true, true, true}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("toID"), base.NewID("classificationID"), maintainedProperties, false, false, false), msg) - require.Nil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), fmt.Sprint(mutableMetaProperties), true, true, true, true, true, true}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error := newTransactionRequest(rest.BaseReq{From: "randomString", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "toID", "classificationID", maintainedProperty, false, false, false).MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), mutableMetaPropertiesString, true, true, true, true, true, true}, newMessage(fromAccAddress, fromID, fromID, classificationID, mutableMetaProperties1, true, true, true, true, true, true), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error = newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID", "randomString", false, false, false).MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), fmt.Sprint(mutableMetaProperties), true, true, true, true, true, true}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.NewLegacyAmino()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve with nil", fields{}, true}, + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), fmt.Sprint(mutableMetaProperties), true, true, true, true, true, true}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/assets/internal/transactions/deputize/response.go b/modules/assets/internal/transactions/deputize/response.go new file mode 100644 index 000000000..f6c13abcf --- /dev/null +++ b/modules/assets/internal/transactions/deputize/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/assets/internal/transactions/deputize/response_test.go b/modules/assets/internal/transactions/deputize/response_test.go new file mode 100644 index 000000000..b78c699e0 --- /dev/null +++ b/modules/assets/internal/transactions/deputize/response_test.go @@ -0,0 +1,25 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Deputize_Response(t *testing.T) { + + testTransactionResponse := newTransactionResponse(constants.IncorrectFormat) + testTransactionResponse2 := newTransactionResponse(nil) + + require.Equal(t, transactionResponse{Success: false, Error: constants.IncorrectFormat}, testTransactionResponse) + require.Equal(t, false, testTransactionResponse.IsSuccessful()) + require.Equal(t, true, testTransactionResponse2.IsSuccessful()) + + require.Equal(t, constants.IncorrectFormat, testTransactionResponse.GetError()) + require.Equal(t, nil, testTransactionResponse2.GetError()) +} diff --git a/modules/assets/internal/transactions/deputize/transaction.go b/modules/assets/internal/transactions/deputize/transaction.go new file mode 100644 index 000000000..ba0b78dd2 --- /dev/null +++ b/modules/assets/internal/transactions/deputize/transaction.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "deputize", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.ToID, + constants.ClassificationID, + constants.MaintainedProperties, + constants.CanMintAsset, + constants.CanBurnAsset, + constants.CanRenumerateAsset, + constants.CanAddMaintainer, + constants.CanRemoveMaintainer, + constants.CanMutateMaintainer, +) diff --git a/modules/assets/internal/transactions/mint/keeper.go b/modules/assets/internal/transactions/mint/keeper.go new file mode 100644 index 000000000..028ffc05e --- /dev/null +++ b/modules/assets/internal/transactions/mint/keeper.go @@ -0,0 +1,104 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mint + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/verify" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/mint" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties" + "github.com/AssetMantle/modules/schema/properties/constants" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + conformAuxiliary helpers.Auxiliary + mintAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + maintainersVerifyAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + + if auxiliaryResponse := transactionKeeper.maintainersVerifyAuxiliary.GetKeeper().Help(context, verify.NewAuxiliaryRequest(message.ClassificationID, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(append(message.ImmutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...)...)) + + assetID := baseIDs.NewAssetID(message.ClassificationID, immutables) + + assets := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(assetID)) + if assets.Get(key.NewKey(assetID)) != nil { + return newTransactionResponse(errorConstants.EntityAlreadyExists) + } + + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(append(message.MutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...)) + + if auxiliaryResponse := transactionKeeper.conformAuxiliary.GetKeeper().Help(context, conform.NewAuxiliaryRequest(message.ClassificationID, immutables, mutables)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + split := sdkTypes.SmallestDec() + + if metaPropertyList := baseLists.NewPropertyList(append(message.ImmutableMetaProperties.GetList(), message.MutableMetaProperties.GetList()...)...); metaPropertyList.GetProperty(constants.SupplyProperty.GetID()) != nil { + split = metaPropertyList.GetProperty(constants.SupplyProperty.GetID()).(properties.MetaProperty).GetData().(data.DecData).Get() + } + + if auxiliaryResponse := transactionKeeper.mintAuxiliary.GetKeeper().Help(context, mint.NewAuxiliaryRequest(message.ToID, assetID, split)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + assets.Add(mappable.NewMappable(base.NewAsset(message.ClassificationID, immutables, mutables))) + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case conform.Auxiliary.GetName(): + transactionKeeper.conformAuxiliary = value + case mint.Auxiliary.GetName(): + transactionKeeper.mintAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + case verify.Auxiliary.GetName(): + transactionKeeper.maintainersVerifyAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} + +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/assets/internal/transactions/mint/keeper_test.go b/modules/assets/internal/transactions/mint/keeper_test.go new file mode 100644 index 000000000..4cb040907 --- /dev/null +++ b/modules/assets/internal/transactions/mint/keeper_test.go @@ -0,0 +1,203 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mint + +import ( + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + "github.com/AssetMantle/modules/modules/assets/internal/parameters" + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/verify" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/mint" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +var ( + conformAuxiliary helpers.Auxiliary + mintAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + maintainersVerifyAuxiliary helpers.Auxiliary +) + +type TestKeepers struct { + MintKeeper helpers.TransactionKeeper +} + +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + mintAuxiliary = mint.AuxiliaryMock.Initialize(Mapper, Parameters) + conformAuxiliary = conform.AuxiliaryMock.Initialize(Mapper, Parameters) + maintainersVerifyAuxiliary = verify.AuxiliaryMock.Initialize(Mapper, Parameters) + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + + keepers := TestKeepers{ + MintKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), + } + + return context, keepers, Mapper, Parameters +} + +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + conformAuxiliary helpers.Auxiliary + mintAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + maintainersVerifyAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper, Parameters, conformAuxiliary, mintAuxiliary, authenticateAuxiliary, maintainersVerifyAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, conformAuxiliary, mintAuxiliary, authenticateAuxiliary, maintainersVerifyAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + conformAuxiliary: tt.fields.conformAuxiliary, + mintAuxiliary: tt.fields.mintAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + maintainersVerifyAuxiliary: tt.fields.maintainersVerifyAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters := createTestInput(t) + immutableProperties := baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutables := baseQualified.NewImmutables(immutableMetaProperties) + mutableProperties := baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutables := baseQualified.NewMutables(mutableMetaProperties) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + testAsset := base.NewAsset(classificationID, immutables, mutables) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + fromID := baseIDs.NewIdentityID(classificationID, immutables) + keepers.MintKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testAsset)) + + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + conformAuxiliary helpers.Auxiliary + mintAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + maintainersVerifyAuxiliary helpers.Auxiliary + } + type args struct { + context sdkTypes.Context + msg sdkTypes.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, Parameters, conformAuxiliary, mintAuxiliary, authenticateAuxiliary, maintainersVerifyAuxiliary}, args{context, newMessage(fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)}, newTransactionResponse(nil)}, + {"+ve Entity Already Exists", fields{Mapper, Parameters, conformAuxiliary, mintAuxiliary, authenticateAuxiliary, maintainersVerifyAuxiliary}, args{context, newMessage(fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)}, newTransactionResponse(errorConstants.EntityAlreadyExists)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + conformAuxiliary: tt.fields.conformAuxiliary, + mintAuxiliary: tt.fields.mintAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + maintainersVerifyAuxiliary: tt.fields.maintainersVerifyAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/assets/internal/transactions/mint/message.go b/modules/assets/internal/transactions/mint/message.go index a0ea85505..0fcca01c8 100644 --- a/modules/assets/internal/transactions/mint/message.go +++ b/modules/assets/internal/transactions/mint/message.go @@ -1,73 +1,87 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mint import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/assets/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ToID ids.IdentityID `json:"toID" valid:"required~required field toID missing"` + ids.ClassificationID `json:"classificationID" valid:"required~required field classificationID missing"` + ImmutableMetaProperties lists.PropertyList `json:"immutableMetaProperties" valid:"required~required field immutableMetaProperties missing"` + ImmutableProperties lists.PropertyList `json:"immutableProperties" valid:"required~required field immutableProperties missing"` + MutableMetaProperties lists.PropertyList `json:"mutableMetaProperties" valid:"required~required field mutableMetaProperties missing"` + MutableProperties lists.PropertyList `json:"mutableProperties" valid:"required~required field mutableProperties missing"` +} + +var _ helpers.Message = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + if len(message.ImmutableMetaProperties.GetList()) == 0 { + message.ImmutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.ImmutableProperties.GetList()) == 0 { + message.ImmutableProperties = base.NewPropertyList(nil) + } + if len(message.MutableMetaProperties.GetList()) == 0 { + message.MutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.MutableProperties.GetList()) == 0 { + message.MutableProperties = base.NewPropertyList(nil) + } + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, toID types.ID, classificationID types.ID, immutableMetaProperties types.MetaProperties, immutableProperties types.Properties, mutableMetaProperties types.MetaProperties, mutableProperties types.Properties) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - ToID: *base.NewID(toID.String()), - ClassificationID: *base.NewID(classificationID.String()), - ImmutableMetaProperties: *base.NewMetaProperties(immutableMetaProperties.GetList()...), - ImmutableProperties: *base.NewProperties(immutableProperties.GetList()...), - MutableMetaProperties: *base.NewMetaProperties(mutableMetaProperties.GetList()...), - MutableProperties: *base.NewProperties(mutableProperties.GetList()...), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, toID ids.IdentityID, classificationID ids.ClassificationID, immutableMetaProperties lists.PropertyList, immutableProperties lists.PropertyList, mutableMetaProperties lists.PropertyList, mutableProperties lists.PropertyList) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + ToID: toID, + ClassificationID: classificationID, + ImmutableMetaProperties: immutableMetaProperties, + ImmutableProperties: immutableProperties, + MutableMetaProperties: mutableMetaProperties, + MutableProperties: mutableProperties, } } diff --git a/modules/assets/internal/transactions/mint/message.pb.go b/modules/assets/internal/transactions/mint/message.pb.go deleted file mode 100644 index 60b12060b..000000000 --- a/modules/assets/internal/transactions/mint/message.pb.go +++ /dev/null @@ -1,870 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/assets/internal/transactions/mint/message.proto - -package mint - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - ToID base.ID `protobuf:"bytes,3,opt,name=to_i_d,json=toID,proto3" json:"to_i_d" valid:"required~required field ToID missing"` - ClassificationID base.ID `protobuf:"bytes,4,opt,name=classification_i_d,json=classificationID,proto3" json:"classification_i_d" valid:"required~required field ClassificationID missing"` - ImmutableMetaProperties base.MetaProperties `protobuf:"bytes,5,opt,name=immutable_meta_properties,json=immutableMetaProperties,proto3" json:"immutable_meta_properties" valid:"required~required field ImmutableMetaProperties missing"` - ImmutableProperties base.Properties `protobuf:"bytes,6,opt,name=immutable_properties,json=immutableProperties,proto3" json:"immutable_properties" valid:"required~required field ImmutableProperties missing"` - MutableMetaProperties base.MetaProperties `protobuf:"bytes,7,opt,name=mutable_meta_properties,json=mutableMetaProperties,proto3" json:"mutable_meta_properties" valid:"required~required field MutableMetaProperties missing"` - MutableProperties base.Properties `protobuf:"bytes,8,opt,name=mutable_properties,json=mutableProperties,proto3" json:"mutable_properties" valid:"required~required field MutableProperties missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_5a1647e226e29e8e, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5a1647e226e29e8e, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "modules.assets.internal.transactions.mint.Message") - proto.RegisterType((*TransactionResponse)(nil), "modules.assets.internal.transactions.mint.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/assets/internal/transactions/mint/message.proto", fileDescriptor_5a1647e226e29e8e) -} - -var fileDescriptor_5a1647e226e29e8e = []byte{ - // 616 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x95, 0x3f, 0x6f, 0xd3, 0x4e, - 0x18, 0xc7, 0x7d, 0xbf, 0xe6, 0x97, 0xb6, 0xc7, 0x02, 0xd7, 0x56, 0x2d, 0x1d, 0xec, 0x28, 0x12, - 0x52, 0x41, 0x70, 0x16, 0x01, 0x55, 0x50, 0xc4, 0x9f, 0xa6, 0x29, 0x55, 0x84, 0x22, 0x50, 0xe9, - 0xc4, 0x12, 0x5d, 0xec, 0x8b, 0x7b, 0xc2, 0xf6, 0xb9, 0x7e, 0x2e, 0x20, 0x90, 0x40, 0x62, 0x63, - 0x84, 0x81, 0x99, 0x2e, 0xec, 0x4c, 0xbc, 0x86, 0x8e, 0x1d, 0x11, 0x43, 0x04, 0xed, 0xc2, 0xdc, - 0x57, 0x80, 0xec, 0xb8, 0x8a, 0x9b, 0x1a, 0xec, 0x74, 0xca, 0x25, 0x77, 0xdf, 0xfb, 0x7c, 0xee, - 0xd1, 0xa3, 0x27, 0x78, 0x23, 0xe0, 0x21, 0x08, 0x50, 0xdc, 0xb7, 0x78, 0x1b, 0xec, 0xe7, 0xa6, - 0x27, 0xed, 0x9e, 0xcb, 0xc1, 0x64, 0x00, 0x5c, 0x81, 0x29, 0x7c, 0xc5, 0x43, 0x9f, 0xb9, 0xa6, - 0x0a, 0x99, 0x0f, 0xcc, 0x52, 0x42, 0xfa, 0x60, 0x7a, 0xc2, 0x57, 0xa6, 0xc7, 0x01, 0x98, 0xc3, - 0x69, 0x10, 0x4a, 0x25, 0xc9, 0xe5, 0x24, 0x48, 0x07, 0x41, 0x7a, 0x1c, 0xa4, 0xe9, 0x20, 0x8d, - 0x82, 0x8b, 0xb3, 0x8e, 0x74, 0x64, 0x9c, 0x32, 0xa3, 0xd5, 0xe0, 0x82, 0xc5, 0xda, 0xa8, 0x09, - 0x58, 0xdb, 0xdc, 0x63, 0xa6, 0x7a, 0x15, 0x70, 0x30, 0x3b, 0x0c, 0xb8, 0x19, 0x84, 0x32, 0xe0, - 0xa1, 0x12, 0x1c, 0x92, 0xcc, 0x72, 0x7e, 0xc6, 0xe3, 0x8a, 0x3d, 0x19, 0xcd, 0x5d, 0xc9, 0xcf, - 0x09, 0x7b, 0x70, 0xb6, 0xfa, 0x6b, 0x1a, 0x4f, 0xb6, 0x06, 0x4f, 0x25, 0x1f, 0x11, 0x2e, 0x75, - 0x43, 0xe9, 0x2d, 0xa0, 0x0a, 0x5a, 0x9a, 0xae, 0xbf, 0xd9, 0xeb, 0x1b, 0xda, 0x8f, 0xbe, 0xb1, - 0xee, 0x08, 0xb5, 0xdd, 0xeb, 0x50, 0x4b, 0x7a, 0x66, 0xea, 0xe6, 0xc7, 0x3e, 0x4f, 0x7f, 0x7d, - 0xda, 0x78, 0x74, 0x9a, 0x43, 0x57, 0x2d, 0x6b, 0xd5, 0xb6, 0x43, 0x0e, 0x70, 0xd4, 0x37, 0xae, - 0xbe, 0x60, 0xae, 0xb0, 0x57, 0xaa, 0x21, 0xdf, 0xe9, 0x89, 0x90, 0xdb, 0x6f, 0x8f, 0x17, 0x95, - 0xae, 0xe0, 0xae, 0x5d, 0x79, 0x18, 0x4a, 0xaf, 0xe2, 0x09, 0x00, 0xe1, 0x3b, 0xd5, 0xcd, 0x58, - 0x85, 0xbc, 0xc4, 0x53, 0xd1, 0x67, 0x5b, 0xb4, 0xed, 0x85, 0xff, 0x2a, 0x68, 0xe9, 0x5c, 0xed, - 0x12, 0x1d, 0x79, 0x1e, 0x1d, 0x60, 0x69, 0x8c, 0xa5, 0x31, 0xb6, 0xd9, 0xa8, 0x2f, 0x47, 0xf6, - 0x47, 0x7d, 0x83, 0x16, 0x80, 0x36, 0x1b, 0x43, 0x6c, 0xb9, 0x1b, 0xff, 0x40, 0x76, 0x70, 0x59, - 0xc9, 0x18, 0x3b, 0x31, 0x0e, 0xf6, 0x66, 0x82, 0xcd, 0x7b, 0xeb, 0x96, 0x4c, 0x43, 0x4b, 0x4a, - 0x36, 0x1b, 0xe4, 0x13, 0xc2, 0xc4, 0x72, 0x19, 0x80, 0xe8, 0x0a, 0x8b, 0x45, 0x2d, 0x15, 0xf3, - 0x4b, 0xe3, 0xf0, 0x1f, 0x24, 0xfc, 0x5b, 0x39, 0xfc, 0xb5, 0x13, 0x9c, 0xb4, 0xcb, 0x79, 0x6b, - 0x64, 0x8b, 0x7c, 0x43, 0xf8, 0xa2, 0xf0, 0xbc, 0x9e, 0x62, 0x1d, 0x97, 0xb7, 0xa3, 0x96, 0x6b, - 0x0f, 0x7b, 0x75, 0xe1, 0xff, 0x58, 0xef, 0x7a, 0x01, 0xbd, 0xd6, 0x89, 0x66, 0xad, 0x6f, 0x24, - 0xaa, 0xf7, 0x73, 0x54, 0x9b, 0xc7, 0xe8, 0x93, 0xf9, 0xa1, 0xf1, 0xbc, 0xc8, 0x3e, 0x41, 0xbe, - 0x20, 0x3c, 0x3b, 0x14, 0x4f, 0x39, 0x97, 0x63, 0xe7, 0x6b, 0x05, 0x9c, 0x53, 0xbe, 0x6b, 0x89, - 0xef, 0x9d, 0xa2, 0xbe, 0x59, 0xae, 0x33, 0xe2, 0xf4, 0x2e, 0xf9, 0x8a, 0xf0, 0xfc, 0xdf, 0xca, - 0x3b, 0x79, 0xd6, 0xf2, 0xae, 0x27, 0xba, 0x77, 0x73, 0x74, 0x5b, 0xff, 0x2e, 0xee, 0x5c, 0x76, - 0x69, 0x3f, 0x23, 0x4c, 0x32, 0x0a, 0x3b, 0x75, 0x96, 0xc2, 0xae, 0x26, 0xa6, 0xb7, 0x8b, 0x99, - 0x66, 0x59, 0x5e, 0x38, 0x55, 0xd4, 0x95, 0xa9, 0xf7, 0xbb, 0x86, 0xf6, 0x7b, 0xd7, 0xd0, 0xaa, - 0x73, 0x78, 0x66, 0x6b, 0x38, 0xa6, 0x37, 0x39, 0x04, 0xd2, 0x07, 0x5e, 0x7b, 0x87, 0xf0, 0x44, - 0x0b, 0x1c, 0xf2, 0x1a, 0x97, 0x5a, 0xc2, 0x57, 0xa4, 0x46, 0x0b, 0x0f, 0x79, 0x9a, 0x8c, 0xcc, - 0xc5, 0x7b, 0x63, 0x64, 0x32, 0x1c, 0xea, 0xee, 0xde, 0x81, 0x8e, 0xf6, 0x0f, 0x74, 0xf4, 0xf3, - 0x40, 0x47, 0x1f, 0x0e, 0x75, 0x6d, 0xff, 0x50, 0xd7, 0xbe, 0x1f, 0xea, 0xda, 0xb3, 0xcd, 0xc2, - 0x53, 0xb7, 0xf0, 0x7f, 0x5a, 0xa7, 0x1c, 0xcf, 0xfc, 0x1b, 0x7f, 0x02, 0x00, 0x00, 0xff, 0xff, - 0xbb, 0x4b, 0x98, 0x92, 0x17, 0x07, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Mint(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Mint(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/modules.assets.internal.transactions.mint.Msg/Mint", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Mint(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Mint(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Mint not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Mint_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Mint(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/modules.assets.internal.transactions.mint.Msg/Mint", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Mint(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "modules.assets.internal.transactions.mint.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Mint", - Handler: _Msg_Mint_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/assets/internal/transactions/mint/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - { - size, err := m.MutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size, err := m.ImmutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.ImmutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.ClassificationID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ToID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ToID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ClassificationID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ToID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ToID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/assets/internal/transactions/mint/message_test.go b/modules/assets/internal/transactions/mint/message_test.go index 45b94f5e0..ac820fda7 100644 --- a/modules/assets/internal/transactions/mint/message_test.go +++ b/modules/assets/internal/transactions/mint/message_test.go @@ -1,49 +1,325 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mint import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" - "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/assets/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" +) + +var ( + immutableMetaProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutableProperties = baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutables = baseQualified.NewImmutables(immutableMetaProperties) + mutableMetaProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutableProperties = baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutables = baseQualified.NewMutables(mutableMetaProperties) + classificationID = baseIDs.NewClassificationID(immutables, mutables) + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = sdkTypes.AccAddressFromBech32(fromAddress) + fromID = baseIDs.NewIdentityID(classificationID, immutables) ) -func Test_Mint_Message(t *testing.T) { - - testFromID := base.NewID("fromID") - testToID := base.NewID("toID") - testClassificationID := base.NewID("classificationID") - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - immutableMetaProperties, Error := base.ReadMetaProperties("defaultImmutableMeta1:S|defaultImmutableMeta1") - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties("defaultImmutable1:S|defaultImmutable1") - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties("defaultMutableMeta1:S|defaultMutableMeta1") - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties("defaultMutable1:S|defaultMutable1") - require.Equal(t, nil, Error) - - testMessage := newMessage(fromAccAddress, testFromID, testToID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties) - require.Equal(t, Message{From: base.NewAccAddressFromSDKTypesAccAddress(fromAccAddress), FromID: testFromID, ToID: testToID, ClassificationID: testClassificationID, ImmutableMetaProperties: immutableMetaProperties, ImmutableProperties: immutableProperties, MutableMetaProperties: mutableMetaProperties, MutableProperties: mutableProperties}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{newMessage(fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)}, newMessage(fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties).(message)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(newMessage(fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve with nil", fields{}, args{codec.New()}}, + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, false}, + {"-ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + toID ids.IdentityID + classificationID ids.ClassificationID + immutableMetaProperties lists.PropertyList + immutableProperties lists.PropertyList + mutableMetaProperties lists.PropertyList + mutableProperties lists.PropertyList + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve with nil", args{}, message{}}, + {"+ve", args{fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, newMessage(fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.toID, tt.args.classificationID, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/assets/internal/transactions/mint/msg_server.go b/modules/assets/internal/transactions/mint/msg_server.go deleted file mode 100644 index 61fa57f4f..000000000 --- a/modules/assets/internal/transactions/mint/msg_server.go +++ /dev/null @@ -1,73 +0,0 @@ -package mint - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - propertiesConstants "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/conform" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/mint" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Mint(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - immutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(message.ImmutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - immutableProperties := base.NewProperties(append(immutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...)...) - - assetID := key.NewAssetID(&message.ClassificationID, immutableProperties) - - assets := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(assetID)) - if assets.Get(key.FromID(assetID)) != nil { - return nil, errors.EntityAlreadyExists - } - - mutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(message.MutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - mutableProperties := base.NewProperties(append(mutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...) - - if auxiliaryResponse := msgServer.transactionKeeper.conformAuxiliary.GetKeeper().Help(ctx, conform.NewAuxiliaryRequest(&message.ClassificationID, immutableProperties, mutableProperties)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - split := sdkTypes.SmallestDec() - - if metaProperties := base.NewMetaProperties(append(message.ImmutableMetaProperties.GetList(), message.MutableMetaProperties.GetList()...)...); metaProperties.Get(base.NewID(propertiesConstants.Lock)) != nil { - if split, Error = metaProperties.Get(base.NewID(propertiesConstants.Lock)).GetMetaFact().GetData().AsDec(); Error != nil { - return nil, errors.MetaDataError - } - } - - if auxiliaryResponse := msgServer.transactionKeeper.mintAuxiliary.GetKeeper().Help(ctx, mint.NewAuxiliaryRequest(message.ToID, assetID, split)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - assets.Add(mappable.NewAsset(assetID, immutableProperties, mutableProperties)) - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/assets/internal/transactions/mint/request.go b/modules/assets/internal/transactions/mint/request.go index 4d3ec1df0..fa2692b8e 100644 --- a/modules/assets/internal/transactions/mint/request.go +++ b/modules/assets/internal/transactions/mint/request.go @@ -1,23 +1,25 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mint import ( "encoding/json" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -33,35 +35,42 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary mint asset transaction -// @Descrption mint asset with mutable immutable properties +// Validate godoc +// @Summary Mint an asset transaction +// @Description Mint asset with mutable immutable properties // @Accept text/plain // @Produce json // @Tags Assets -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body transactionRequest true "A transaction to mint the asset." +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /assets/mint [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + if err != nil { + return err + } + inputValidator := base.NewInputValidator(constants.PropertyExpression) + if !inputValidator.IsValid(transactionRequest.ImmutableProperties, transactionRequest.ImmutableMetaProperties, transactionRequest.MutableProperties, transactionRequest.MutableMetaProperties) { + return errorConstants.IncorrectFormat + } + return nil } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ToID), - cliCommand.ReadString(flags.ClassificationID), - cliCommand.ReadString(flags.ImmutableMetaProperties), - cliCommand.ReadString(flags.ImmutableProperties), - cliCommand.ReadString(flags.MutableMetaProperties), - cliCommand.ReadString(flags.MutableProperties), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ToID), + cliCommand.ReadString(constants.ClassificationID), + cliCommand.ReadString(constants.ImmutableMetaProperties), + cliCommand.ReadString(constants.ImmutableProperties), + cliCommand.ReadString(constants.MutableMetaProperties), + cliCommand.ReadString(constants.MutableProperties), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -70,44 +79,61 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + immutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableMetaProperties) + if err != nil { + return nil, err + } + + immutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableProperties) + if err != nil { + return nil, err + } + immutableProperties = immutableProperties.ScrubData() + + mutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableMetaProperties) + if err != nil { + return nil, err } - immutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.ImmutableMetaProperties) - if Error != nil { - return nil, Error + mutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableProperties) + if err != nil { + return nil, err } + mutableProperties = mutableProperties.ScrubData() - immutableProperties, Error := base.ReadProperties(transactionRequest.ImmutableProperties) - if Error != nil { - return nil, Error + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err } - mutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.MutableMetaProperties) - if Error != nil { - return nil, Error + toID, err := baseIDs.ReadIdentityID(transactionRequest.ToID) + if err != nil { + return nil, err } - mutableProperties, Error := base.ReadProperties(transactionRequest.MutableProperties) - if Error != nil { - return nil, Error + classificationID, err := baseIDs.ReadClassificationID(transactionRequest.ClassificationID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.ToID), - base.NewID(transactionRequest.ClassificationID), + fromID, + toID, + classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/assets/internal/transactions/mint/request_test.go b/modules/assets/internal/transactions/mint/request_test.go index d2793df68..141a490f5 100644 --- a/modules/assets/internal/transactions/mint/request_test.go +++ b/modules/assets/internal/transactions/mint/request_test.go @@ -1,105 +1,340 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mint import ( "encoding/json" - cryptoCodec "github.com/cosmos/cosmos-sdk/crypto/codec" - vestingTypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" + "fmt" + "reflect" "testing" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" -) - -func Test_Mint_Request(t *testing.T) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptocryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vestingTypes.RegisterLegacyAminoCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.ToID, flags.ClassificationID, flags.ImmutableMetaProperties, flags.ImmutableProperties, flags.MutableMetaProperties, flags.MutableProperties}) - cliContext := client.Context{}.WithLegacyAmino(Codec) - - immutableMetaPropertiesString := "defaultImmutableMeta1:S|defaultImmutableMeta1" - immutablePropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" - mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" - mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - - immutableMetaProperties, Error := base.ReadMetaProperties(immutableMetaPropertiesString) - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties(immutablePropertiesString) - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties(mutableMetaPropertiesString) - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties(mutablePropertiesString) - require.Equal(t, nil, Error) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString) - - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ToID: "toID", ClassificationID: "classificationID", ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) - - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ToID: "", ClassificationID: "", ImmutableMetaProperties: "", ImmutableProperties: "", MutableMetaProperties: "", MutableProperties: ""}, requestFromCLI) + "github.com/spf13/viper" - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/utilities/transaction" +) - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +var ( + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + immutableMetaPropertiesString = "testImmutableMeta1:S|immutableMeta" + immutableMetaProperties1 = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("testImmutableMeta1"), baseData.NewStringData("immutableMeta"))) + immutablePropertiesString = "testImmutable1:S|immutable" + immutableProperties1 = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("testImmutable1"), baseData.NewStringData("immutable"))) + mutableMetaPropertiesString = "testMutableMeta1:S|mutableMeta" + mutableMetaProperties1 = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("testMutableMeta1"), baseData.NewStringData("mutableMeta"))) + mutablePropertiesString = "testMutable1:S|mutable" + mutableProperties1 = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("testMutable1"), baseData.NewStringData("mutable"))) +) - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + toID string + classificationID string + immutableMetaProperties string + immutableProperties string + mutableMetaProperties string + mutableProperties string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, transactionRequest{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.toID, tt.args.classificationID, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("toID"), base.NewID("classificationID"), immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties), msg) - require.Nil(t, Error) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", "toID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.AssetID, constants.FromID, constants.ToID, constants.ClassificationID, constants.ImmutableMetaProperties, constants.ImmutableProperties, constants.MutableMetaProperties, constants.MutableProperties}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.FromID.GetName(), fromID.String()) + viper.Set(constants.ToID.GetName(), fromID.String()) + viper.Set(constants.ClassificationID.GetName(), classificationID.String()) + viper.Set(constants.ImmutableMetaProperties.GetName(), immutableMetaPropertiesString) + viper.Set(constants.ImmutableProperties.GetName(), immutablePropertiesString) + viper.Set(constants.MutableMetaProperties.GetName(), mutableMetaPropertiesString) + viper.Set(constants.MutableProperties.GetName(), mutablePropertiesString) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{}, args{cliCommand, cliContext}, transactionRequest{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID", "randomString", immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_FromJSON(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}))}, newTransactionRequest(testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID", immutableMetaPropertiesString, "randomString", mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, "randomString", mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, newMessage(fromAccAddress, fromID, fromID, classificationID, immutableMetaProperties1, immutableProperties1.ScrubData(), mutableMetaProperties1, mutableProperties1.ScrubData()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, "randomString").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.NewLegacyAmino()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/assets/internal/transactions/mint/response.go b/modules/assets/internal/transactions/mint/response.go new file mode 100644 index 000000000..8c0153870 --- /dev/null +++ b/modules/assets/internal/transactions/mint/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mint + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/assets/internal/transactions/mint/response_test.go b/modules/assets/internal/transactions/mint/response_test.go new file mode 100644 index 000000000..6220c1207 --- /dev/null +++ b/modules/assets/internal/transactions/mint/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mint + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Mint_Response(t *testing.T) { + testTransactionResponse := newTransactionResponse(constants.IncorrectFormat) + testTransactionResponse2 := newTransactionResponse(nil) + + require.Equal(t, transactionResponse{Success: false, Error: constants.IncorrectFormat}, testTransactionResponse) + require.Equal(t, false, testTransactionResponse.IsSuccessful()) + require.Equal(t, true, testTransactionResponse2.IsSuccessful()) + + require.Equal(t, constants.IncorrectFormat, testTransactionResponse.GetError()) + require.Equal(t, nil, testTransactionResponse2.GetError()) +} diff --git a/modules/assets/internal/transactions/mint/transaction.go b/modules/assets/internal/transactions/mint/transaction.go new file mode 100644 index 000000000..49b802a5a --- /dev/null +++ b/modules/assets/internal/transactions/mint/transaction.go @@ -0,0 +1,27 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mint + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "mint", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.ToID, + constants.FromID, + constants.ClassificationID, + constants.ImmutableMetaProperties, + constants.ImmutableProperties, + constants.MutableMetaProperties, + constants.MutableProperties, +) diff --git a/modules/assets/internal/transactions/mutate/keeper.go b/modules/assets/internal/transactions/mutate/keeper.go new file mode 100644 index 000000000..5a9721963 --- /dev/null +++ b/modules/assets/internal/transactions/mutate/keeper.go @@ -0,0 +1,84 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mutate + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/maintain" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + authenticateAuxiliary helpers.Auxiliary + maintainAuxiliary helpers.Auxiliary + conformAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + assets := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.AssetID)) + + Mappable := assets.Get(key.NewKey(message.AssetID)) + if Mappable == nil { + return newTransactionResponse(constants.EntityNotFound) + } + asset := Mappable.(documents.Asset) + + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(append(message.MutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...)) + + if auxiliaryResponse := transactionKeeper.maintainAuxiliary.GetKeeper().Help(context, maintain.NewAuxiliaryRequest(asset.GetClassificationID(), message.FromID, mutables)); auxiliaryResponse.IsSuccessful() { + if auxiliaryResponse := transactionKeeper.conformAuxiliary.GetKeeper().Help(context, conform.NewAuxiliaryRequest(asset.GetClassificationID(), nil, asset.GetMutables().Mutate(mutables.GetMutablePropertyList().GetList()...))); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + } else { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + assets.Mutate(mappable.NewMappable(base.NewAsset(asset.GetClassificationID(), asset.GetImmutables(), asset.GetMutables().Mutate(mutables.GetMutablePropertyList().GetList()...)))) + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper = mapper + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case conform.Auxiliary.GetName(): + transactionKeeper.conformAuxiliary = value + case maintain.Auxiliary.GetName(): + transactionKeeper.maintainAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(constants.UninitializedUsage) + } + } + + return transactionKeeper +} + +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/assets/internal/transactions/mutate/keeper_test.go b/modules/assets/internal/transactions/mutate/keeper_test.go new file mode 100644 index 000000000..00a8da352 --- /dev/null +++ b/modules/assets/internal/transactions/mutate/keeper_test.go @@ -0,0 +1,192 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mutate + +import ( + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + "github.com/AssetMantle/modules/modules/assets/internal/parameters" + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/maintain" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +var ( + authenticateAuxiliary helpers.Auxiliary + maintainAuxiliary helpers.Auxiliary + conformAuxiliary helpers.Auxiliary +) + +type TestKeepers struct { + MutateKeeper helpers.TransactionKeeper +} + +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + maintainAuxiliary = maintain.AuxiliaryMock.Initialize(Mapper, Parameters) + conformAuxiliary = conform.AuxiliaryMock.Initialize(Mapper, Parameters) + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + + keepers := TestKeepers{ + MutateKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), + } + + return context, keepers, Mapper, Parameters +} + +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + authenticateAuxiliary helpers.Auxiliary + maintainAuxiliary helpers.Auxiliary + conformAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper, authenticateAuxiliary, maintainAuxiliary, conformAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, authenticateAuxiliary, maintainAuxiliary, conformAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + maintainAuxiliary: tt.fields.maintainAuxiliary, + conformAuxiliary: tt.fields.conformAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.in1, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, _ := createTestInput(t) + immutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutables := baseQualified.NewImmutables(immutableMetaProperties) + mutableMetaproperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutableproperties := baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutables := baseQualified.NewMutables(mutableMetaproperties) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + testAssetID := baseIDs.NewAssetID(classificationID, immutables) + testAsset := base.NewAsset(classificationID, immutables, mutables) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + fromID := baseIDs.NewIdentityID(classificationID, immutables) + keepers.MutateKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testAsset)) + + type fields struct { + mapper helpers.Mapper + authenticateAuxiliary helpers.Auxiliary + maintainAuxiliary helpers.Auxiliary + conformAuxiliary helpers.Auxiliary + } + type args struct { + context sdkTypes.Context + msg sdkTypes.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, authenticateAuxiliary, maintainAuxiliary, conformAuxiliary}, args{context, newMessage(fromAccAddress, fromID, testAssetID, mutableMetaproperties, mutableproperties)}, newTransactionResponse(nil)}, + {"+ve Entity Not Found", fields{Mapper, authenticateAuxiliary, maintainAuxiliary, conformAuxiliary}, args{context, newMessage(fromAccAddress, fromID, baseIDs.PrototypeAssetID(), mutableMetaproperties, mutableproperties)}, newTransactionResponse(errorConstants.EntityNotFound)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + maintainAuxiliary: tt.fields.maintainAuxiliary, + conformAuxiliary: tt.fields.conformAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/assets/internal/transactions/mutate/message.go b/modules/assets/internal/transactions/mutate/message.go index b6d000b31..daa9cfa0d 100644 --- a/modules/assets/internal/transactions/mutate/message.go +++ b/modules/assets/internal/transactions/mutate/message.go @@ -1,70 +1,75 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mutate import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/assets/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + AssetID ids.AssetID `json:"assetID" valid:"required~required field assetID missing"` + MutableMetaProperties lists.PropertyList `json:"mutableMetaProperties" valid:"required~required field mutableMetaProperties missing"` + MutableProperties lists.PropertyList `json:"mutableProperties" valid:"required~required field mutableProperties missing"` +} + +var _ helpers.Message = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + if len(message.MutableProperties.GetList()) == 0 { + message.MutableProperties = base.NewPropertyList(nil) + } + if len(message.MutableMetaProperties.GetList()) == 0 { + message.MutableMetaProperties = base.NewPropertyList(nil) + } + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, assetID types.ID, mutableMetaProperties types.MetaProperties, mutableProperties types.Properties) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - AssetID: *base.NewID(assetID.String()), - MutableMetaProperties: *base.NewMetaProperties(mutableMetaProperties.GetList()...), - MutableProperties: *base.NewProperties(mutableProperties.GetList()...), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, assetID ids.AssetID, mutableMetaProperties lists.PropertyList, mutableProperties lists.PropertyList) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + AssetID: assetID, + MutableMetaProperties: mutableMetaProperties, + MutableProperties: mutableProperties, } } diff --git a/modules/assets/internal/transactions/mutate/message.pb.go b/modules/assets/internal/transactions/mutate/message.pb.go deleted file mode 100644 index 01288d1be..000000000 --- a/modules/assets/internal/transactions/mutate/message.pb.go +++ /dev/null @@ -1,727 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/assets/internal/transactions/mutate/message.proto - -package mutate - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - AssetID base.ID `protobuf:"bytes,3,opt,name=asset_i_d,json=assetID,proto3" json:"asset_i_d" valid:"required~required field AssetID missing"` - MutableMetaProperties base.MetaProperties `protobuf:"bytes,4,opt,name=mutable_meta_properties,json=mutableMetaProperties,proto3" json:"mutable_meta_properties" valid:"required~required field MutableMetaProperties missing"` - MutableProperties base.Properties `protobuf:"bytes,5,opt,name=mutable_properties,json=mutableProperties,proto3" json:"mutable_properties" valid:"required~required field MutableProperties missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_595c2732186bdf0e, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_595c2732186bdf0e, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.assets.internal.transactions.mutate.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.assets.internal.transactions.mutate.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/assets/internal/transactions/mutate/message.proto", fileDescriptor_595c2732186bdf0e) -} - -var fileDescriptor_595c2732186bdf0e = []byte{ - // 535 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x94, 0x4f, 0x8b, 0xd3, 0x40, - 0x18, 0x87, 0x13, 0xf7, 0x7f, 0x3c, 0x19, 0x5d, 0x5c, 0x7a, 0x48, 0x4a, 0x41, 0x58, 0x44, 0x67, - 0xb0, 0xc2, 0x8a, 0x2b, 0x1e, 0x5a, 0xba, 0x42, 0x91, 0xe2, 0xb2, 0xee, 0xc9, 0x4b, 0x99, 0x26, - 0x6f, 0xb3, 0x83, 0x9d, 0x4c, 0x9c, 0x77, 0xaa, 0x28, 0xe8, 0xd9, 0xa3, 0x7e, 0x02, 0x7b, 0xf4, - 0xe8, 0xc7, 0xd8, 0xe3, 0x1e, 0xc5, 0x43, 0x91, 0xf6, 0xe2, 0xd5, 0xfd, 0x04, 0x92, 0x49, 0x4a, - 0xb3, 0xb5, 0xd0, 0x2e, 0x7b, 0xca, 0x64, 0x26, 0xef, 0xef, 0x79, 0xc2, 0xcc, 0x3b, 0x4e, 0x33, - 0x01, 0x85, 0x1c, 0x35, 0xc4, 0x01, 0xb4, 0x31, 0x7c, 0x4d, 0x85, 0x0c, 0xfb, 0x3d, 0x40, 0xca, - 0x10, 0x41, 0x23, 0xe5, 0xb1, 0x06, 0x15, 0xb3, 0x1e, 0xd5, 0x8a, 0xc5, 0xc8, 0x02, 0xcd, 0x65, - 0x8c, 0x54, 0xf4, 0x35, 0xd3, 0x40, 0x05, 0x20, 0xb2, 0x08, 0x48, 0xa2, 0xa4, 0x96, 0xee, 0x93, - 0x99, 0x28, 0x92, 0x47, 0x91, 0x2c, 0x8a, 0x4c, 0xa2, 0x48, 0x31, 0x8a, 0x64, 0x51, 0xa5, 0x5b, - 0x91, 0x8c, 0xa4, 0xc9, 0xa1, 0xe9, 0x28, 0x8b, 0x2c, 0x55, 0x67, 0xed, 0x30, 0x38, 0x01, 0xc1, - 0xa8, 0x7e, 0x9f, 0x00, 0xd2, 0x0e, 0x43, 0xa0, 0x89, 0x92, 0x09, 0x28, 0xcd, 0x01, 0xf3, 0x9a, - 0xbd, 0xc5, 0x35, 0x02, 0x34, 0x3b, 0x9c, 0xad, 0xbb, 0xbb, 0xb8, 0x8e, 0x87, 0xd9, 0xb7, 0x95, - 0xbf, 0x6b, 0xce, 0x46, 0x2b, 0xfb, 0x79, 0xf7, 0xab, 0xed, 0xac, 0x76, 0x95, 0x14, 0x3b, 0x76, - 0xd9, 0xde, 0xdd, 0xaa, 0x7f, 0x3c, 0x1d, 0xfa, 0xd6, 0xaf, 0xa1, 0x7f, 0x10, 0x71, 0x7d, 0xd2, - 0xef, 0x90, 0x40, 0x0a, 0x5a, 0x48, 0x7e, 0x11, 0x43, 0xf1, 0xf5, 0x65, 0xe3, 0xf9, 0xff, 0x1c, - 0x52, 0x0b, 0x82, 0x5a, 0x18, 0x2a, 0x40, 0x3c, 0x1f, 0xfa, 0xf7, 0xde, 0xb2, 0x1e, 0x0f, 0xf7, - 0x2b, 0x0a, 0xde, 0xf4, 0xb9, 0x82, 0xf0, 0xd3, 0x64, 0x50, 0xee, 0x72, 0xe8, 0x85, 0xe5, 0x67, - 0x4a, 0x8a, 0xb2, 0xe0, 0x88, 0x3c, 0x8e, 0x2a, 0x47, 0x46, 0xc5, 0x7d, 0xe7, 0x6c, 0xa6, 0xcf, - 0x36, 0x6f, 0x87, 0x3b, 0xd7, 0xca, 0xf6, 0xee, 0xf5, 0xea, 0x1d, 0x32, 0xbb, 0x3b, 0x19, 0x96, - 0x18, 0x2c, 0x31, 0xd8, 0x66, 0xa3, 0xbe, 0x97, 0xda, 0x9f, 0x0f, 0x7d, 0xb2, 0x04, 0xb4, 0xd9, - 0x98, 0x62, 0xd7, 0xbb, 0x66, 0xc2, 0xfd, 0xe0, 0x6c, 0x99, 0xdd, 0x36, 0xe4, 0x95, 0xcb, 0x90, - 0x1f, 0xe5, 0x64, 0xba, 0x80, 0x5c, 0x4b, 0xe3, 0x8b, 0xe8, 0x0d, 0x96, 0xcd, 0xb8, 0x3f, 0x6c, - 0xe7, 0x76, 0x7a, 0x9a, 0x3a, 0x3d, 0x68, 0xa7, 0x3b, 0xdc, 0x9e, 0x1e, 0x8d, 0x9d, 0x55, 0xa3, - 0xf2, 0x60, 0x09, 0x95, 0xd6, 0x85, 0xb3, 0x51, 0x3f, 0xc8, 0xb5, 0x9e, 0x2e, 0xd0, 0x6a, 0x65, - 0xe0, 0x8b, 0xd5, 0x53, 0xc9, 0x6d, 0x31, 0x6f, 0xdd, 0xfd, 0x66, 0x3b, 0xee, 0x44, 0xb9, 0x60, - 0xbb, 0x66, 0x6c, 0xef, 0x2f, 0x61, 0x5b, 0x30, 0xad, 0xe5, 0xa6, 0x8f, 0x97, 0x33, 0x9d, 0x67, - 0x79, 0x43, 0xcc, 0xae, 0xed, 0x6f, 0x7e, 0x1e, 0xf8, 0xd6, 0x9f, 0x81, 0x6f, 0x55, 0xb6, 0x9d, - 0x9b, 0xc7, 0xd3, 0xc6, 0x3d, 0x02, 0x4c, 0x64, 0x8c, 0x50, 0xfd, 0x6e, 0x3b, 0x2b, 0x2d, 0x8c, - 0xdc, 0x81, 0xed, 0xac, 0xb7, 0x4c, 0x2f, 0xbb, 0x0d, 0x72, 0x85, 0x9b, 0x80, 0xe4, 0x7d, 0x55, - 0x3a, 0xbc, 0x52, 0xca, 0x1c, 0xd5, 0x7a, 0x7c, 0x3a, 0xf2, 0xec, 0xb3, 0x91, 0x67, 0xff, 0x1e, - 0x79, 0xf6, 0x97, 0xb1, 0x67, 0x9d, 0x8d, 0x3d, 0xeb, 0xe7, 0xd8, 0xb3, 0x5e, 0x1d, 0x2f, 0xdd, - 0xac, 0x97, 0xb8, 0x1e, 0x3b, 0xeb, 0xe6, 0xb2, 0x78, 0xf8, 0x2f, 0x00, 0x00, 0xff, 0xff, 0xfd, - 0xcb, 0x9d, 0x1b, 0x64, 0x05, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Mutate(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Mutate(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.assets.internal.transactions.mutate.Msg/Mutate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Mutate(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Mutate(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Mutate not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Mutate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Mutate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.assets.internal.transactions.mutate.Msg/Mutate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Mutate(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.assets.internal.transactions.mutate.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Mutate", - Handler: _Msg_Mutate_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/assets/internal/transactions/mutate/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.MutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.AssetID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.AssetID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AssetID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.AssetID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/assets/internal/transactions/mutate/message_test.go b/modules/assets/internal/transactions/mutate/message_test.go index 49608f75f..f9e3c71f7 100644 --- a/modules/assets/internal/transactions/mutate/message_test.go +++ b/modules/assets/internal/transactions/mutate/message_test.go @@ -1,44 +1,285 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mutate import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/assets/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Mutate_Message(t *testing.T) { - testFromID := base.NewID("fromID") - testAssetID := base.NewID("assetID") - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, err) - - mutableMetaProperties, err := base.ReadMetaProperties("defaultMutableMeta1:S|defaultMutableMeta1") - require.Equal(t, nil, err) - mutableProperties, err := base.ReadProperties("defaultMutable1:S|defaultMutable1") - require.Equal(t, nil, err) - - testMessage := newMessage(fromAccAddress, testFromID, testAssetID, mutableMetaProperties, mutableProperties) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, AssetID: testAssetID, MutableMetaProperties: mutableMetaProperties, MutableProperties: mutableProperties}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +var ( + immutableMetaProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutables = baseQualified.NewImmutables(immutableMetaProperties) + mutableMetaProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutableProperties = baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutables = baseQualified.NewMutables(mutableMetaProperties) + classificationID = baseIDs.NewClassificationID(immutables, mutables) + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = sdkTypes.AccAddressFromBech32(fromAddress) + fromID = baseIDs.NewIdentityID(classificationID, immutables) + testAssetID = baseIDs.NewAssetID(classificationID, immutables) +) + +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{newMessage(fromAccAddress, fromID, testAssetID, mutableMetaProperties, mutableProperties)}, newMessage(fromAccAddress, fromID, testAssetID, mutableMetaProperties, mutableProperties).(message)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID, mutableMetaProperties, mutableProperties}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(newMessage(fromAccAddress, fromID, testAssetID, mutableMetaProperties, mutableProperties)))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID, mutableMetaProperties, mutableProperties}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID, mutableMetaProperties, mutableProperties}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID, mutableMetaProperties, mutableProperties}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID, mutableMetaProperties, mutableProperties}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID, mutableMetaProperties, mutableProperties}, false}, + {"+ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + assetID ids.AssetID + mutableMetaProperties lists.PropertyList + mutableProperties lists.PropertyList + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve with nil", args{}, message{}}, + {"+ve", args{fromAccAddress, fromID, testAssetID, mutableMetaProperties, mutableProperties}, newMessage(fromAccAddress, fromID, testAssetID, mutableMetaProperties, mutableProperties)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.assetID, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/assets/internal/transactions/mutate/msg_server.go b/modules/assets/internal/transactions/mutate/msg_server.go deleted file mode 100644 index 86abacd3c..000000000 --- a/modules/assets/internal/transactions/mutate/msg_server.go +++ /dev/null @@ -1,58 +0,0 @@ -package mutate - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/conform" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/maintain" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Mutate(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - assets := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(&message.AssetID)) - - asset := assets.Get(key.FromID(&message.AssetID)) - if asset == nil { - return nil, errors.EntityNotFound - } - - mutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(message.MutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - mutableProperties := base.NewProperties(append(mutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...) - - if auxiliaryResponse := msgServer.transactionKeeper.conformAuxiliary.GetKeeper().Help(ctx, conform.NewAuxiliaryRequest(asset.(mappables.InterNFT).GetClassificationID(), nil, mutableProperties)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - if auxiliaryResponse := msgServer.transactionKeeper.maintainAuxiliary.GetKeeper().Help(ctx, maintain.NewAuxiliaryRequest(asset.(mappables.InterNFT).GetClassificationID(), &message.FromID, mutableProperties)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - assets.Mutate(mappable.NewAsset(asset.(mappables.InterNFT).GetID(), asset.(mappables.InterNFT).GetImmutableProperties(), asset.(mappables.InterNFT).GetMutableProperties().Mutate(mutableProperties.GetList()...))) - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/assets/internal/transactions/mutate/request.go b/modules/assets/internal/transactions/mutate/request.go index 83ad2f77a..09062a6b3 100644 --- a/modules/assets/internal/transactions/mutate/request.go +++ b/modules/assets/internal/transactions/mutate/request.go @@ -1,23 +1,25 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mutate import ( "encoding/json" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -30,32 +32,39 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary mutate asset transaction -// @Descrption mutate asset +// Validate godoc +// @Summary Mutate an asset transaction +// @Description Mutate asset // @Accept text/plain // @Produce json // @Tags Assets -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body transactionRequest true "A transaction to mutate an asset." +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /assets/mutate [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + if err != nil { + return err + } + inputValidator := base.NewInputValidator(constants.PropertyExpression) + if !inputValidator.IsValid(transactionRequest.MutableProperties, transactionRequest.MutableMetaProperties) { + return errorConstants.IncorrectFormat + } + return nil } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.AssetID), - cliCommand.ReadString(flags.MutableMetaProperties), - cliCommand.ReadString(flags.MutableProperties), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.AssetID), + cliCommand.ReadString(constants.MutableMetaProperties), + cliCommand.ReadString(constants.MutableProperties), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -64,31 +73,42 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + mutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableMetaProperties) + if err != nil { + return nil, err + } + + mutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableProperties) + if err != nil { + return nil, err } + mutableProperties = mutableProperties.ScrubData() - mutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.MutableMetaProperties) - if Error != nil { - return nil, Error + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err } - mutableProperties, Error := base.ReadProperties(transactionRequest.MutableProperties) - if Error != nil { - return nil, Error + assetID, err := baseIDs.ReadAssetID(transactionRequest.AssetID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.AssetID), + fromID, + assetID, mutableMetaProperties, mutableProperties, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/assets/internal/transactions/mutate/request_test.go b/modules/assets/internal/transactions/mutate/request_test.go index d59a4c6a9..486d79050 100644 --- a/modules/assets/internal/transactions/mutate/request_test.go +++ b/modules/assets/internal/transactions/mutate/request_test.go @@ -1,90 +1,294 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mutate import ( "encoding/json" + "fmt" + "reflect" "testing" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" -) - -func Test_Define_Request(t *testing.T) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.AssetID, flags.MutableMetaProperties, flags.MutableProperties}) - cliContext := context.NewCLIContext().WithCodec(Codec) - - mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" - mutablePropertiesString := "defaultMutable1:S|defaultMutable1" + "github.com/spf13/viper" - mutableMetaProperties, Error := base.ReadMetaProperties(mutableMetaPropertiesString) - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties(mutablePropertiesString) - require.Equal(t, nil, Error) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "assetID", mutableMetaPropertiesString, mutablePropertiesString) - - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", AssetID: "assetID", MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/utilities/transaction" +) - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", MutableMetaProperties: "", MutableProperties: ""}, requestFromCLI) +var ( + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + mutableMetaPropertiesString = "testMutableMeta1:S|mutableMeta" + mutableMetaProperties1 = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("testMutableMeta1"), baseData.NewStringData("mutableMeta"))) + mutablePropertiesString = "testMutable1:S|mutable" + mutableProperties1 = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("testMutable1"), baseData.NewStringData("mutable"))) +) - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + assetID string + mutableMetaProperties string + mutableProperties string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, fromID.String(), testAssetID.String(), mutableMetaPropertiesString, mutablePropertiesString}, transactionRequest{testBaseRequest, fromID.String(), testAssetID.String(), mutableMetaPropertiesString, mutablePropertiesString}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.assetID, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.AssetID, constants.FromID, constants.MutableMetaProperties, constants.MutableProperties}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.AssetID.GetName(), testAssetID.String()) + viper.Set(constants.FromID.GetName(), fromID.String()) + viper.Set(constants.MutableMetaProperties.GetName(), mutableMetaPropertiesString) + viper.Set(constants.MutableProperties.GetName(), mutablePropertiesString) + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + MutableMetaProperties string + MutableProperties string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String(), mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, cliContext}, transactionRequest{testBaseRequest, fromID.String(), testAssetID.String(), mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("assetID"), mutableMetaProperties, mutableProperties), msg) - require.Nil(t, Error) +func Test_transactionRequest_FromJSON(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + MutableMetaProperties string + MutableProperties string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String(), mutableMetaPropertiesString, mutablePropertiesString}, args{types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, fromID, testAssetID, mutableMetaProperties, mutableProperties}))}, newTransactionRequest(testBaseRequest, fromID.String(), testAssetID.String(), mutableMetaPropertiesString, mutablePropertiesString), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", "assetID", mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String(), mutableMetaPropertiesString, mutablePropertiesString}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, "fromID", "assetID", "randomString", mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String(), mutableMetaPropertiesString, mutablePropertiesString}, newMessage(fromAccAddress, fromID, testAssetID, mutableMetaProperties1, mutableProperties1.ScrubData()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, "fromID", "assetID", mutableMetaPropertiesString, "randomString").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + MutableMetaProperties string + MutableProperties string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String(), mutableMetaPropertiesString, mutablePropertiesString}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String(), mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/assets/internal/transactions/mutate/response.go b/modules/assets/internal/transactions/mutate/response.go new file mode 100644 index 000000000..d21b7c28b --- /dev/null +++ b/modules/assets/internal/transactions/mutate/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mutate + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/assets/internal/transactions/mutate/response_test.go b/modules/assets/internal/transactions/mutate/response_test.go new file mode 100644 index 000000000..6aa0b18f7 --- /dev/null +++ b/modules/assets/internal/transactions/mutate/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mutate + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Mutate_Response(t *testing.T) { + testTransactionResponse := newTransactionResponse(constants.IncorrectFormat) + testTransactionResponse2 := newTransactionResponse(nil) + + require.Equal(t, transactionResponse{Success: false, Error: constants.IncorrectFormat}, testTransactionResponse) + require.Equal(t, false, testTransactionResponse.IsSuccessful()) + require.Equal(t, true, testTransactionResponse2.IsSuccessful()) + + require.Equal(t, constants.IncorrectFormat, testTransactionResponse.GetError()) + require.Equal(t, nil, testTransactionResponse2.GetError()) +} diff --git a/modules/assets/internal/transactions/mutate/transaction.go b/modules/assets/internal/transactions/mutate/transaction.go new file mode 100644 index 000000000..20fa7371a --- /dev/null +++ b/modules/assets/internal/transactions/mutate/transaction.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mutate + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "mutate", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.AssetID, + constants.FromID, + constants.MutableMetaProperties, + constants.MutableProperties, +) diff --git a/modules/assets/internal/transactions/prototype.go b/modules/assets/internal/transactions/prototype.go new file mode 100644 index 000000000..f72b218b0 --- /dev/null +++ b/modules/assets/internal/transactions/prototype.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transactions + +import ( + "github.com/AssetMantle/modules/modules/assets/internal/transactions/burn" + "github.com/AssetMantle/modules/modules/assets/internal/transactions/define" + "github.com/AssetMantle/modules/modules/assets/internal/transactions/deputize" + "github.com/AssetMantle/modules/modules/assets/internal/transactions/mint" + "github.com/AssetMantle/modules/modules/assets/internal/transactions/mutate" + "github.com/AssetMantle/modules/modules/assets/internal/transactions/renumerate" + "github.com/AssetMantle/modules/modules/assets/internal/transactions/revoke" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Transactions { + return baseHelpers.NewTransactions( + burn.Transaction, + define.Transaction, + deputize.Transaction, + mint.Transaction, + mutate.Transaction, + renumerate.Transaction, + revoke.Transaction, + ) +} diff --git a/modules/assets/internal/transactions/prototype_test.go b/modules/assets/internal/transactions/prototype_test.go new file mode 100644 index 000000000..13de233b4 --- /dev/null +++ b/modules/assets/internal/transactions/prototype_test.go @@ -0,0 +1,32 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transactions + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/assets/internal/transactions/burn" + "github.com/AssetMantle/modules/modules/assets/internal/transactions/define" + "github.com/AssetMantle/modules/modules/assets/internal/transactions/deputize" + "github.com/AssetMantle/modules/modules/assets/internal/transactions/mint" + "github.com/AssetMantle/modules/modules/assets/internal/transactions/mutate" + "github.com/AssetMantle/modules/modules/assets/internal/transactions/renumerate" + "github.com/AssetMantle/modules/modules/assets/internal/transactions/revoke" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + want := baseHelpers.NewTransactions(burn.Transaction, + define.Transaction, + deputize.Transaction, + mint.Transaction, + mutate.Transaction, + renumerate.Transaction, + revoke.Transaction) + + require.Equal(t, Prototype().Get(""), want.Get("")) + +} diff --git a/modules/assets/internal/transactions/renumerate/keeper.go b/modules/assets/internal/transactions/renumerate/keeper.go new file mode 100644 index 000000000..76a46cb65 --- /dev/null +++ b/modules/assets/internal/transactions/renumerate/keeper.go @@ -0,0 +1,95 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package renumerate + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/maintain" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/renumerate" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/documents" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties" + "github.com/AssetMantle/modules/schema/properties/constants" + "github.com/AssetMantle/modules/schema/qualified/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + maintainAuxiliary helpers.Auxiliary + renumerateAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + assets := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.AssetID)) + + Mappable := assets.Get(key.NewKey(message.AssetID)) + if Mappable == nil { + return newTransactionResponse(errorConstants.EntityNotFound) + } + asset := Mappable.(documents.Asset) + + if auxiliaryResponse := transactionKeeper.maintainAuxiliary.GetKeeper().Help(context, maintain.NewAuxiliaryRequest(asset.GetClassificationID(), message.FromID, base.NewMutables(baseLists.NewPropertyList(constants.SupplyProperty)))); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + metaProperties, err := supplement.GetMetaPropertiesFromResponse(transactionKeeper.supplementAuxiliary.GetKeeper().Help(context, supplement.NewAuxiliaryRequest(asset.GetSupply()))) + if err != nil { + return newTransactionResponse(err) + } + + if supplyMetaProperty := metaProperties.GetProperty(constants.SupplyProperty.GetID()); supplyMetaProperty != nil && supplyMetaProperty.IsMeta() { + value := supplyMetaProperty.(properties.MetaProperty).GetData().(data.DecData).Get() + if auxiliaryResponse := transactionKeeper.renumerateAuxiliary.GetKeeper().Help(context, renumerate.NewAuxiliaryRequest(message.FromID, message.AssetID, value)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + } else { + return newTransactionResponse(errorConstants.MetaDataError) + } + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper = mapper + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case maintain.Auxiliary.GetName(): + transactionKeeper.maintainAuxiliary = value + case renumerate.Auxiliary.GetName(): + transactionKeeper.renumerateAuxiliary = value + case supplement.Auxiliary.GetName(): + transactionKeeper.supplementAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} + +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/assets/internal/transactions/renumerate/keeper_test.go b/modules/assets/internal/transactions/renumerate/keeper_test.go index 4bf223da4..21f473f9c 100644 --- a/modules/assets/internal/transactions/renumerate/keeper_test.go +++ b/modules/assets/internal/transactions/renumerate/keeper_test.go @@ -5,6 +5,19 @@ package renumerate import ( "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + "github.com/AssetMantle/modules/modules/assets/internal/key" "github.com/AssetMantle/modules/modules/assets/internal/mappable" "github.com/AssetMantle/modules/modules/assets/internal/parameters" @@ -23,17 +36,6 @@ import ( "github.com/AssetMantle/modules/schema/properties" baseProperties "github.com/AssetMantle/modules/schema/properties/base" baseQualified "github.com/AssetMantle/modules/schema/qualified/base" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/stretchr/testify/require" - abciTypes "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" ) var ( diff --git a/modules/assets/internal/transactions/renumerate/message.go b/modules/assets/internal/transactions/renumerate/message.go index 6d8cd8b15..553dc4cb1 100644 --- a/modules/assets/internal/transactions/renumerate/message.go +++ b/modules/assets/internal/transactions/renumerate/message.go @@ -1,68 +1,63 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package renumerate import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/assets/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + AssetID ids.AssetID `json:"assetID" valid:"required~required field assetID missing"` +} + +var _ helpers.Message = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, assetID types.ID) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - AssetID: *base.NewID(assetID.String()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, assetID ids.AssetID) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + AssetID: assetID, } } diff --git a/modules/assets/internal/transactions/renumerate/message.pb.go b/modules/assets/internal/transactions/renumerate/message.pb.go deleted file mode 100644 index 2fba7acfd..000000000 --- a/modules/assets/internal/transactions/renumerate/message.pb.go +++ /dev/null @@ -1,629 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/assets/internal/transactions/renumerate/message.proto - -package renumerate - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - AssetID base.ID `protobuf:"bytes,3,opt,name=asset_i_d,json=assetID,proto3" json:"asset_i_d" valid:"required~required field AssetID missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_5bc713cdf152725d, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5bc713cdf152725d, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "modules.assets.internal.transactions.renumerate.Message") - proto.RegisterType((*TransactionResponse)(nil), "modules.assets.internal.transactions.renumerate.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/assets/internal/transactions/renumerate/message.proto", fileDescriptor_5bc713cdf152725d) -} - -var fileDescriptor_5bc713cdf152725d = []byte{ - // 437 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x93, 0xbf, 0x8b, 0x13, 0x41, - 0x14, 0xc7, 0x77, 0x8c, 0xdc, 0x8f, 0xb1, 0x5b, 0x15, 0x8e, 0x14, 0xbb, 0x4b, 0x40, 0x38, 0x44, - 0x66, 0xe0, 0x04, 0x95, 0xeb, 0x12, 0xa2, 0x70, 0x48, 0x10, 0xa2, 0x85, 0xd8, 0x84, 0xc9, 0xce, - 0xcb, 0xde, 0x60, 0x66, 0x26, 0xce, 0x9b, 0x28, 0x0a, 0x5a, 0x5b, 0x58, 0x28, 0x58, 0x5a, 0xdc, - 0x9f, 0x73, 0xe5, 0x95, 0x62, 0x11, 0x24, 0x69, 0xac, 0xef, 0x2f, 0x90, 0xcc, 0x5e, 0xcc, 0x72, - 0x0a, 0x66, 0xab, 0x7d, 0xfb, 0x98, 0xef, 0xfb, 0x7c, 0x87, 0xf7, 0x1d, 0xda, 0x9b, 0x80, 0x43, - 0x85, 0x1e, 0x4c, 0x0e, 0x03, 0x94, 0x2f, 0xb9, 0xb6, 0x72, 0x3a, 0x06, 0xe4, 0x02, 0x11, 0x3c, - 0x72, 0x65, 0x3c, 0x38, 0x23, 0xc6, 0xdc, 0x3b, 0x61, 0x50, 0xe4, 0x5e, 0x59, 0x83, 0xdc, 0x81, - 0x99, 0x6a, 0x70, 0xc2, 0x03, 0xd7, 0x80, 0x28, 0x0a, 0x60, 0x13, 0x67, 0xbd, 0x8d, 0x57, 0x72, - 0x56, 0xca, 0xd9, 0x4a, 0xce, 0xaa, 0x72, 0xb6, 0x96, 0x37, 0x6f, 0x14, 0xb6, 0xb0, 0x41, 0xcb, - 0x97, 0x55, 0x39, 0xa6, 0x79, 0xfb, 0xb2, 0x2b, 0xcc, 0x8f, 0x41, 0x0b, 0xee, 0xdf, 0x4e, 0x00, - 0xf9, 0x50, 0x20, 0x70, 0x25, 0xcb, 0xb3, 0xad, 0x6f, 0x0d, 0xba, 0xdd, 0x2b, 0x4d, 0xc4, 0x5f, - 0x08, 0xbd, 0x3a, 0x72, 0x56, 0xef, 0x91, 0x8c, 0xec, 0xef, 0x76, 0xde, 0x9f, 0xce, 0xd2, 0xe8, - 0xc7, 0x2c, 0x7d, 0x58, 0x28, 0x7f, 0x3c, 0x1d, 0xb2, 0xdc, 0x6a, 0x5e, 0x99, 0xfc, 0xc4, 0x40, - 0xf5, 0xf7, 0x69, 0xf7, 0xf1, 0xdf, 0x1c, 0xd6, 0xce, 0xf3, 0xb6, 0x94, 0x0e, 0x10, 0xcf, 0x67, - 0xe9, 0x9d, 0xd7, 0x62, 0xac, 0xe4, 0x61, 0xcb, 0xc1, 0xab, 0xa9, 0x72, 0x20, 0x3f, 0xac, 0x8a, - 0x6c, 0xa4, 0x60, 0x2c, 0xb3, 0x47, 0xce, 0xea, 0x4c, 0x2b, 0x44, 0x65, 0x8a, 0x56, 0x3f, 0x58, - 0x89, 0xdf, 0xd0, 0x9d, 0xe5, 0x77, 0xa0, 0x06, 0x72, 0xef, 0x4a, 0x46, 0xf6, 0xaf, 0x1d, 0xdc, - 0x62, 0x97, 0xae, 0xc7, 0x4a, 0x2c, 0x0b, 0x58, 0x16, 0xb0, 0x47, 0xdd, 0xce, 0xbd, 0xa5, 0xfb, - 0xf3, 0x59, 0xca, 0x36, 0x80, 0x1e, 0x75, 0xd7, 0xd8, 0xad, 0x51, 0x68, 0xc4, 0xef, 0xe8, 0x6e, - 0xd8, 0x42, 0x20, 0x37, 0xea, 0x90, 0xef, 0x5f, 0x90, 0xf9, 0x7f, 0xc8, 0xed, 0xe5, 0xf8, 0x2a, - 0x7a, 0x5b, 0x94, 0x9d, 0xc3, 0x9d, 0x8f, 0x27, 0x69, 0xf4, 0xeb, 0x24, 0x8d, 0x5a, 0x37, 0xe9, - 0xf5, 0x67, 0xeb, 0xdd, 0xf7, 0x01, 0x27, 0xd6, 0x20, 0x1c, 0x7c, 0x25, 0xb4, 0xd1, 0xc3, 0x22, - 0xfe, 0x44, 0x28, 0xed, 0xff, 0x89, 0x43, 0xfc, 0x80, 0xd5, 0x0c, 0x10, 0xbb, 0x58, 0x7d, 0xb3, - 0x5b, 0x5b, 0xf9, 0x0f, 0x5b, 0x1d, 0x77, 0x3a, 0x4f, 0xc8, 0xd9, 0x3c, 0x21, 0x3f, 0xe7, 0x09, - 0xf9, 0xbc, 0x48, 0xa2, 0xb3, 0x45, 0x12, 0x7d, 0x5f, 0x24, 0xd1, 0x8b, 0xe7, 0x1b, 0x67, 0xa8, - 0xe6, 0x0b, 0x1a, 0x6e, 0x85, 0x1c, 0xdf, 0xfd, 0x1d, 0x00, 0x00, 0xff, 0xff, 0x14, 0x88, 0x22, - 0x93, 0x8b, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Renumerate(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Renumerate(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/modules.assets.internal.transactions.renumerate.Msg/Renumerate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Renumerate(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Renumerate(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Renumerate not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Renumerate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Renumerate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/modules.assets.internal.transactions.renumerate.Msg/Renumerate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Renumerate(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "modules.assets.internal.transactions.renumerate.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Renumerate", - Handler: _Msg_Renumerate_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/assets/internal/transactions/renumerate/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.AssetID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.AssetID.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AssetID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.AssetID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/assets/internal/transactions/renumerate/message_test.go b/modules/assets/internal/transactions/renumerate/message_test.go index ec033fe11..2fc69c3df 100644 --- a/modules/assets/internal/transactions/renumerate/message_test.go +++ b/modules/assets/internal/transactions/renumerate/message_test.go @@ -1,39 +1,256 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package renumerate import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/assets/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Renumerate_Message(t *testing.T) { - testAssetID := base.NewID("assetID") - testFromID := base.NewID("fromID") - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, err) - - testMessage := newMessage(fromAccAddress, testFromID, testAssetID) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, AssetID: testAssetID}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +var ( + immutableMetaProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutables = baseQualified.NewImmutables(immutableMetaProperties) + mutableMetaProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutables = baseQualified.NewMutables(mutableMetaProperties) + classificationID = baseIDs.NewClassificationID(immutables, mutables) + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = sdkTypes.AccAddressFromBech32(fromAddress) + fromID = baseIDs.NewIdentityID(classificationID, immutables) + testAssetID = baseIDs.NewAssetID(classificationID, immutables) +) + +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{newMessage(fromAccAddress, fromID, testAssetID)}, newMessage(fromAccAddress, fromID, testAssetID).(message)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(newMessage(fromAccAddress, fromID, testAssetID)))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + AssetID ids.AssetID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, fromID, testAssetID}, false}, + {"+ve with Nil", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + assetID ids.AssetID + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, fromID, testAssetID}, message{fromAccAddress, fromID, testAssetID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.assetID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/assets/internal/transactions/renumerate/msg_server.go b/modules/assets/internal/transactions/renumerate/msg_server.go deleted file mode 100644 index 57d7cd711..000000000 --- a/modules/assets/internal/transactions/renumerate/msg_server.go +++ /dev/null @@ -1,60 +0,0 @@ -package renumerate - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/maintain" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/renumerate" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Renumerate(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - assets := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(&message.AssetID)) - - asset := assets.Get(key.FromID(&message.AssetID)) - if asset == nil { - return nil, errors.EntityNotFound - } - - if auxiliaryResponse := msgServer.transactionKeeper.maintainAuxiliary.GetKeeper().Help(ctx, maintain.NewAuxiliaryRequest(asset.(mappables.InterNFT).GetClassificationID(), &message.FromID, base.NewProperties(base.NewProperty(base.NewID(properties.Value), nil)))); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - metaProperties, Error := supplement.GetMetaPropertiesFromResponse(msgServer.transactionKeeper.supplementAuxiliary.GetKeeper().Help(ctx, supplement.NewAuxiliaryRequest(asset.(mappables.InterNFT).GetValue()))) - if Error != nil { - return nil, Error - } - - if valueMetaProperty := metaProperties.Get(base.NewID(properties.Value)); valueMetaProperty != nil { - if value, Error := valueMetaProperty.GetMetaFact().GetData().AsDec(); Error != nil { - return nil, Error - } else if auxiliaryResponse := msgServer.transactionKeeper.renumerateAuxiliary.GetKeeper().Help(ctx, renumerate.NewAuxiliaryRequest(message.FromID, message.AssetID, value)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - } else { - return nil, errors.MetaDataError - } - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/assets/internal/transactions/renumerate/request.go b/modules/assets/internal/transactions/renumerate/request.go index 52683365a..78b8fab78 100644 --- a/modules/assets/internal/transactions/renumerate/request.go +++ b/modules/assets/internal/transactions/renumerate/request.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package renumerate @@ -9,15 +7,15 @@ import ( "encoding/json" "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -28,30 +26,30 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary renumerate asset transaction -// @Descrption renumerate asset with mutable immutable properties +// Validate godoc +// @Summary Renumerate an asset transaction +// @Description Renumerate asset with mutable immutable properties // @Accept text/plain // @Produce json // @Tags Assets -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body body transactionRequest true "A transaction to renumerate an asset." +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /assets/renumerate [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.AssetID), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.AssetID), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -60,19 +58,29 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + assetID, err := baseIDs.ReadAssetID(transactionRequest.AssetID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.AssetID), + fromID, + assetID, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/assets/internal/transactions/renumerate/request_test.go b/modules/assets/internal/transactions/renumerate/request_test.go index 84d083771..b05fe9f2b 100644 --- a/modules/assets/internal/transactions/renumerate/request_test.go +++ b/modules/assets/internal/transactions/renumerate/request_test.go @@ -1,74 +1,258 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package renumerate import ( "encoding/json" + "fmt" + "reflect" "testing" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/stretchr/testify/require" + "github.com/spf13/viper" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Renumerate_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.AssetID}) - cliContext := context.NewCLIContext().WithCodec(Codec) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, err) - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "assetID") - - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", AssetID: "assetID"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) +var ( + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} +) - requestFromCLI, err := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, err) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", AssetID: ""}, requestFromCLI) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + assetID string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, fromID.String(), testAssetID.String()}, transactionRequest{testBaseRequest, fromID.String(), testAssetID.String()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.assetID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, err := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, err) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, err := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, err) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.AssetID, constants.FromID}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.AssetID.GetName(), testAssetID.String()) + viper.Set(constants.FromID.GetName(), fromID.String()) + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String()}, args{cliCommand, cliContext}, newTransactionRequest(testBaseRequest, fromID.String(), testAssetID.String()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromJSON(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String()}, args{types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, fromID, testAssetID}))}, newTransactionRequest(testBaseRequest, fromID.String(), testAssetID.String()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, err := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("assetID")), msg) - require.Nil(t, err) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String()}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg2, err := newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", "assetID").MakeMsg() - require.NotNil(t, err) - require.Nil(t, msg2) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String()}, newMessage(fromAccAddress, fromID, testAssetID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + AssetID string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testAssetID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + AssetID: tt.fields.AssetID, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/assets/internal/transactions/renumerate/response.go b/modules/assets/internal/transactions/renumerate/response.go new file mode 100644 index 000000000..c65b33f10 --- /dev/null +++ b/modules/assets/internal/transactions/renumerate/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package renumerate + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/assets/internal/transactions/renumerate/response_test.go b/modules/assets/internal/transactions/renumerate/response_test.go new file mode 100644 index 000000000..449c9bb59 --- /dev/null +++ b/modules/assets/internal/transactions/renumerate/response_test.go @@ -0,0 +1,25 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package renumerate + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Renumerate_Response(t *testing.T) { + + testTransactionResponse := newTransactionResponse(constants.IncorrectFormat) + testTransactionResponse2 := newTransactionResponse(nil) + + require.Equal(t, transactionResponse{Success: false, Error: constants.IncorrectFormat}, testTransactionResponse) + require.Equal(t, false, testTransactionResponse.IsSuccessful()) + require.Equal(t, true, testTransactionResponse2.IsSuccessful()) + + require.Equal(t, constants.IncorrectFormat, testTransactionResponse.GetError()) + require.Equal(t, nil, testTransactionResponse2.GetError()) +} diff --git a/modules/assets/internal/transactions/renumerate/transaction.go b/modules/assets/internal/transactions/renumerate/transaction.go new file mode 100644 index 000000000..731048a24 --- /dev/null +++ b/modules/assets/internal/transactions/renumerate/transaction.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package renumerate + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "renumerate", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.AssetID, +) diff --git a/modules/assets/internal/transactions/revoke/keeper.go b/modules/assets/internal/transactions/revoke/keeper.go new file mode 100644 index 000000000..534b5fe1b --- /dev/null +++ b/modules/assets/internal/transactions/revoke/keeper.go @@ -0,0 +1,57 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/revoke" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + revokeAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + if auxiliaryResponse := transactionKeeper.revokeAuxiliary.GetKeeper().Help(context, revoke.NewAuxiliaryRequest(message.FromID, message.ToID, message.ClassificationID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + return newTransactionResponse(nil) +} +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case revoke.Auxiliary.GetName(): + transactionKeeper.revokeAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(constants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/assets/internal/transactions/revoke/keeper_test.go b/modules/assets/internal/transactions/revoke/keeper_test.go new file mode 100644 index 000000000..f4e4d2390 --- /dev/null +++ b/modules/assets/internal/transactions/revoke/keeper_test.go @@ -0,0 +1,184 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/assets/internal/key" + "github.com/AssetMantle/modules/modules/assets/internal/mappable" + "github.com/AssetMantle/modules/modules/assets/internal/parameters" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/revoke" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +var ( + authenticateAuxiliary helpers.Auxiliary + revokeAuxiliary helpers.Auxiliary +) + +type TestKeepers struct { + RevokeKeeper helpers.TransactionKeeper +} + +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + revokeAuxiliary = revoke.AuxiliaryMock.Initialize(Mapper, Parameters) + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + + keepers := TestKeepers{ + RevokeKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), + } + + return context, keepers, Mapper, Parameters +} + +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + revokeAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper, Parameters, authenticateAuxiliary, revokeAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, authenticateAuxiliary, revokeAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + revokeAuxiliary: tt.fields.revokeAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters := createTestInput(t) + immutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutables := baseQualified.NewImmutables(immutableProperties) + mutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutables := baseQualified.NewMutables(mutableProperties) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + testAsset := base.NewAsset(classificationID, immutables, mutables) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + fromID := baseIDs.NewIdentityID(classificationID, immutables) + keepers.RevokeKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testAsset)) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + revokeAuxiliary helpers.Auxiliary + } + type args struct { + context sdkTypes.Context + msg sdkTypes.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, Parameters, authenticateAuxiliary, revokeAuxiliary}, args{context, newMessage(fromAccAddress, fromID, fromID, classificationID)}, newTransactionResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + revokeAuxiliary: tt.fields.revokeAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/assets/internal/transactions/revoke/message.go b/modules/assets/internal/transactions/revoke/message.go index 0393380a7..ab29c829f 100644 --- a/modules/assets/internal/transactions/revoke/message.go +++ b/modules/assets/internal/transactions/revoke/message.go @@ -1,70 +1,66 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/assets/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ToID ids.IdentityID `json:"toID" valid:"required~required field toID missing"` + ids.ClassificationID `json:"classificationID" valid:"required~required field classificationID missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, toID types.ID, classificationID types.ID) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - ToID: *base.NewID(toID.String()), - ClassificationID: *base.NewID(classificationID.String()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, toID ids.IdentityID, classificationID ids.ClassificationID) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + ToID: toID, + ClassificationID: classificationID, } } diff --git a/modules/assets/internal/transactions/revoke/message.pb.go b/modules/assets/internal/transactions/revoke/message.pb.go deleted file mode 100644 index 42415e989..000000000 --- a/modules/assets/internal/transactions/revoke/message.pb.go +++ /dev/null @@ -1,677 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/assets/internal/transactions/revoke/message.proto - -package revoke - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - ToID base.ID `protobuf:"bytes,3,opt,name=to_i_d,json=toID,proto3" json:"to_i_d" valid:"required~required field AssetID missing"` - ClassificationID base.ID `protobuf:"bytes,4,opt,name=classification_i_d,json=classificationID,proto3" json:"classification_i_d" valid:"required~required field ClassificationID missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_c0499c6bfc25037c, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_c0499c6bfc25037c, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.assets.internal.transactions.revoke.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.assets.internal.transactions.revoke.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/assets/internal/transactions/revoke/message.proto", fileDescriptor_c0499c6bfc25037c) -} - -var fileDescriptor_c0499c6bfc25037c = []byte{ - // 473 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0xcf, 0x6b, 0x13, 0x41, - 0x14, 0x80, 0x77, 0x6c, 0x88, 0x75, 0xbd, 0xc8, 0xaa, 0x50, 0x7a, 0xd8, 0x5d, 0x02, 0x42, 0x11, - 0x99, 0x81, 0x0a, 0x2a, 0xf5, 0x62, 0xe2, 0x2a, 0x04, 0x29, 0x4a, 0xec, 0xc9, 0x4b, 0x98, 0xec, - 0xbc, 0x6c, 0x87, 0xee, 0xce, 0xc4, 0x79, 0x93, 0x8a, 0x07, 0x3d, 0x7b, 0xd4, 0x83, 0xf7, 0x1c, - 0x3d, 0xf9, 0x77, 0xf4, 0xd8, 0xa3, 0x78, 0x08, 0x92, 0x5c, 0x3c, 0xf7, 0x2f, 0x90, 0x9d, 0x4d, - 0xe9, 0x1a, 0x85, 0x36, 0xf4, 0xb4, 0xb3, 0x3f, 0xf8, 0xbe, 0x8f, 0x9d, 0x37, 0x7e, 0x77, 0x04, - 0x06, 0x25, 0x5a, 0x50, 0x29, 0xf4, 0x51, 0x1c, 0xb0, 0x42, 0x8b, 0x71, 0x0e, 0xc8, 0x38, 0x22, - 0x58, 0x64, 0x52, 0x59, 0x30, 0x8a, 0xe7, 0xcc, 0x1a, 0xae, 0x90, 0xa7, 0x56, 0x6a, 0x85, 0xcc, - 0xc0, 0xa1, 0x3e, 0x00, 0x56, 0x00, 0x22, 0xcf, 0x80, 0x8e, 0x8c, 0xb6, 0x3a, 0x78, 0xbc, 0x84, - 0xa2, 0x0b, 0x14, 0xad, 0x50, 0xf4, 0x14, 0x45, 0xeb, 0x28, 0x5a, 0xa1, 0x36, 0x6f, 0x65, 0x3a, - 0xd3, 0x8e, 0xc3, 0xca, 0x55, 0x85, 0xdc, 0xbc, 0xbb, 0x5c, 0x87, 0xe9, 0x3e, 0x14, 0x9c, 0xd9, - 0xf7, 0x23, 0x40, 0x36, 0xe0, 0x08, 0x4c, 0x8a, 0xea, 0xdb, 0xd6, 0xf7, 0x86, 0x7f, 0x75, 0xb7, - 0x0a, 0x0a, 0xbe, 0x10, 0xbf, 0x31, 0x34, 0xba, 0xd8, 0x20, 0x31, 0xd9, 0xba, 0xd6, 0xf9, 0x70, - 0x34, 0x8d, 0xbc, 0x9f, 0xd3, 0xe8, 0x59, 0x26, 0xed, 0xfe, 0x78, 0x40, 0x53, 0x5d, 0xb0, 0x1a, - 0xf9, 0xa5, 0x82, 0xfa, 0xed, 0xeb, 0xe4, 0xc5, 0xbf, 0x1e, 0xda, 0x4e, 0xd3, 0xb6, 0x10, 0x06, - 0x10, 0x4f, 0xa6, 0xd1, 0xbd, 0x43, 0x9e, 0x4b, 0xb1, 0xd3, 0x32, 0xf0, 0x76, 0x2c, 0x0d, 0x88, - 0x8f, 0xa7, 0x8b, 0x78, 0x28, 0x21, 0x17, 0xf1, 0x73, 0xa3, 0x8b, 0xb8, 0x90, 0x88, 0x52, 0x65, - 0xad, 0x9e, 0x4b, 0x09, 0xde, 0xf9, 0xeb, 0xe5, 0xb5, 0x2f, 0xfb, 0x62, 0xe3, 0x4a, 0x4c, 0xb6, - 0xae, 0x6f, 0xdf, 0xa1, 0xcb, 0x7f, 0xac, 0xd2, 0x52, 0xa7, 0xa5, 0x4e, 0xdb, 0x4d, 0x3a, 0x0f, - 0xca, 0xfa, 0x93, 0x69, 0x44, 0x2f, 0x20, 0xed, 0x26, 0x67, 0xda, 0xe6, 0xd0, 0x3d, 0x08, 0xac, - 0xdf, 0xb4, 0xda, 0x69, 0xd7, 0x56, 0xd1, 0x3e, 0x5c, 0x68, 0xd9, 0x39, 0xda, 0x76, 0xb9, 0xbb, - 0x75, 0x6f, 0xc3, 0xea, 0x6e, 0x12, 0x7c, 0x25, 0x7e, 0x90, 0xe6, 0x1c, 0x51, 0x0e, 0x65, 0xca, - 0xcb, 0xbd, 0x76, 0x09, 0x8d, 0x55, 0x12, 0x9e, 0x2c, 0x12, 0x1e, 0x9d, 0x93, 0xf0, 0xf4, 0x2f, - 0x4f, 0xbd, 0xe5, 0x46, 0xba, 0xf4, 0x6a, 0x67, 0xfd, 0xd3, 0x24, 0xf2, 0x7e, 0x4f, 0x22, 0xaf, - 0x75, 0xdb, 0xbf, 0xb9, 0x77, 0x36, 0x89, 0x3d, 0xc0, 0x91, 0x56, 0x08, 0xdb, 0xdf, 0x88, 0xbf, - 0xb6, 0x8b, 0x59, 0x30, 0x21, 0x7e, 0xb3, 0xe7, 0x86, 0x33, 0x48, 0xe8, 0x25, 0x46, 0x9b, 0x2e, - 0x86, 0x72, 0xf3, 0xd5, 0xa5, 0x28, 0xff, 0x49, 0xed, 0xa8, 0xa3, 0x59, 0x48, 0x8e, 0x67, 0x21, - 0xf9, 0x35, 0x0b, 0xc9, 0xe7, 0x79, 0xe8, 0x1d, 0xcf, 0x43, 0xef, 0xc7, 0x3c, 0xf4, 0xde, 0xec, - 0x5d, 0x78, 0xd2, 0x57, 0x38, 0xef, 0x83, 0xa6, 0x3b, 0x69, 0xf7, 0xff, 0x04, 0x00, 0x00, 0xff, - 0xff, 0xa8, 0x28, 0xdb, 0x5e, 0x35, 0x04, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Revoke(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Revoke(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.assets.internal.transactions.revoke.Msg/Revoke", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Revoke(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Revoke(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Revoke not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Revoke_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Revoke(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.assets.internal.transactions.revoke.Msg/Revoke", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Revoke(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.assets.internal.transactions.revoke.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Revoke", - Handler: _Msg_Revoke_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/assets/internal/transactions/revoke/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.ClassificationID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ToID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ToID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ClassificationID.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ToID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ToID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/assets/internal/transactions/revoke/message_test.go b/modules/assets/internal/transactions/revoke/message_test.go index d13f7fa97..988c93d62 100644 --- a/modules/assets/internal/transactions/revoke/message_test.go +++ b/modules/assets/internal/transactions/revoke/message_test.go @@ -1,41 +1,269 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/assets/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Revoke_Message(t *testing.T) { - testFromID := base.NewID("fromID") - testToID := base.NewID("toID") - testClassificationID := base.NewID("classificationID") - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, err) - - require.Equal(t, nil, err) - - testMessage := newMessage(fromAccAddress, testFromID, testToID, testClassificationID) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, ToID: testToID, ClassificationID: testClassificationID}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +var ( + immutableMetaProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutables = baseQualified.NewImmutables(immutableMetaProperties) + mutableMetaProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutables = baseQualified.NewMutables(mutableMetaProperties) + classificationID = baseIDs.NewClassificationID(immutables, mutables) + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = sdkTypes.AccAddressFromBech32(fromAddress) + fromID = baseIDs.NewIdentityID(classificationID, immutables) +) + +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{newMessage(fromAccAddress, fromID, fromID, classificationID)}, newMessage(fromAccAddress, fromID, fromID, classificationID).(message)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(newMessage(fromAccAddress, fromID, fromID, classificationID)))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, classificationID}, false}, + {"-ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_newMessage(t *testing.T) { + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + toID ids.IdentityID + classificationID ids.ClassificationID + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve with nil", args{}, message{}}, + {"+ve", args{fromAccAddress, fromID, fromID, classificationID}, newMessage(fromAccAddress, fromID, fromID, classificationID)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.toID, tt.args.classificationID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/assets/internal/transactions/revoke/msg_server.go b/modules/assets/internal/transactions/revoke/msg_server.go deleted file mode 100644 index 175ff93d0..000000000 --- a/modules/assets/internal/transactions/revoke/msg_server.go +++ /dev/null @@ -1,31 +0,0 @@ -package revoke - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/revoke" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Revoke(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - if auxiliaryResponse := msgServer.transactionKeeper.revokeAuxiliary.GetKeeper().Help(ctx, revoke.NewAuxiliaryRequest(&message.FromID, &message.ToID, &message.ClassificationID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/assets/internal/transactions/revoke/request.go b/modules/assets/internal/transactions/revoke/request.go index 069bf114a..ace0f755a 100644 --- a/modules/assets/internal/transactions/revoke/request.go +++ b/modules/assets/internal/transactions/revoke/request.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke @@ -9,15 +7,15 @@ import ( "encoding/json" "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/assets/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -29,31 +27,31 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary revoke asset transaction -// @Descrption revoke asset +// Validate Request godoc +// @Summary Revoke a maintainer for an asset classification transaction +// @Description Revoke asset // @Accept text/plain // @Produce json // @Tags Assets -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body body transactionRequest true "A transaction to revoke an asset." +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for unexpected error response." // @Router /assets/revoke [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ToID), - cliCommand.ReadString(flags.ClassificationID), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ToID), + cliCommand.ReadString(constants.ClassificationID), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -62,20 +60,35 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + toID, err := baseIDs.ReadIdentityID(transactionRequest.ToID) + if err != nil { + return nil, err + } + + classificationID, err := baseIDs.ReadClassificationID(transactionRequest.ClassificationID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.ToID), - base.NewID(transactionRequest.ClassificationID), + fromID, + toID, + classificationID, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/assets/internal/transactions/revoke/request_test.go b/modules/assets/internal/transactions/revoke/request_test.go index 351344516..6372cf62f 100644 --- a/modules/assets/internal/transactions/revoke/request_test.go +++ b/modules/assets/internal/transactions/revoke/request_test.go @@ -1,80 +1,272 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke import ( "encoding/json" + "fmt" + "reflect" "testing" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/stretchr/testify/require" + "github.com/spf13/viper" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Revoke_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.ToID, flags.ClassificationID, flags.MaintainedProperties, flags.AddMaintainer, flags.RemoveMaintainer, flags.MutateMaintainer}) - cliContext := context.NewCLIContext().WithCodec(Codec) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, err) - - require.Equal(t, nil, err) - - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID") - - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ToID: "toID", ClassificationID: "classificationID"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) +var ( + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} +) - requestFromCLI, err := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, err) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ToID: "", ClassificationID: ""}, requestFromCLI) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + toID string + classificationID string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, fromID.String(), fromID.String(), classificationID.String()}, transactionRequest{testBaseRequest, fromID.String(), fromID.String(), classificationID.String()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.toID, tt.args.classificationID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, err := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, err) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, err := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, err) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.ToID, constants.ClassificationID}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.FromID.GetName(), fromID.String()) + viper.Set(constants.ToID.GetName(), fromID.String()) + viper.Set(constants.ClassificationID.GetName(), classificationID.String()) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String()}, args{cliCommand, cliContext}, newTransactionRequest(testBaseRequest, fromID.String(), fromID.String(), classificationID.String()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromJSON(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String()}, args{types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, fromID, fromID, classificationID}))}, newTransactionRequest(testBaseRequest, fromID.String(), fromID.String(), classificationID.String()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, err := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("toID"), base.NewID("classificationID")), msg) - require.Nil(t, err) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String()}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg2, err := newTransactionRequest(rest.BaseReq{From: "randomString", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "toID", "classificationID").MakeMsg() - require.NotNil(t, err) - require.Nil(t, msg2) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String()}, newMessage(fromAccAddress, fromID, fromID, classificationID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg2, err = newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID").MakeMsg() - require.Nil(t, err) - require.NotNil(t, msg2) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), classificationID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/assets/internal/transactions/revoke/response.go b/modules/assets/internal/transactions/revoke/response.go new file mode 100644 index 000000000..f4e2a16c2 --- /dev/null +++ b/modules/assets/internal/transactions/revoke/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/assets/internal/transactions/revoke/response_test.go b/modules/assets/internal/transactions/revoke/response_test.go new file mode 100644 index 000000000..fb57c3e0c --- /dev/null +++ b/modules/assets/internal/transactions/revoke/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Revoke_Response(t *testing.T) { + testTransactionResponse := newTransactionResponse(constants.IncorrectFormat) + testTransactionResponse2 := newTransactionResponse(nil) + + require.Equal(t, transactionResponse{Success: false, Error: constants.IncorrectFormat}, testTransactionResponse) + require.Equal(t, false, testTransactionResponse.IsSuccessful()) + require.Equal(t, true, testTransactionResponse2.IsSuccessful()) + + require.Equal(t, constants.IncorrectFormat, testTransactionResponse.GetError()) + require.Equal(t, nil, testTransactionResponse2.GetError()) +} diff --git a/modules/assets/internal/transactions/revoke/transaction.go b/modules/assets/internal/transactions/revoke/transaction.go new file mode 100644 index 000000000..94603fa7c --- /dev/null +++ b/modules/assets/internal/transactions/revoke/transaction.go @@ -0,0 +1,23 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "revoke", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.ToID, + constants.ClassificationID, +) diff --git a/modules/assets/prototype.go b/modules/assets/prototype.go new file mode 100644 index 000000000..bd54ba43e --- /dev/null +++ b/modules/assets/prototype.go @@ -0,0 +1,32 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package assets + +import ( + "github.com/AssetMantle/modules/modules/assets/auxiliaries" + "github.com/AssetMantle/modules/modules/assets/internal/block" + "github.com/AssetMantle/modules/modules/assets/internal/genesis" + "github.com/AssetMantle/modules/modules/assets/internal/mapper" + "github.com/AssetMantle/modules/modules/assets/internal/module" + "github.com/AssetMantle/modules/modules/assets/internal/parameters" + "github.com/AssetMantle/modules/modules/assets/internal/queries" + "github.com/AssetMantle/modules/modules/assets/internal/simulator" + "github.com/AssetMantle/modules/modules/assets/internal/transactions" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Module { + return baseHelpers.NewModule( + module.Name, + auxiliaries.Prototype, + genesis.Prototype, + mapper.Prototype, + parameters.Prototype, + queries.Prototype, + simulator.Prototype, + transactions.Prototype, + block.Prototype, + ) +} diff --git a/modules/assets/prototype_test.go b/modules/assets/prototype_test.go new file mode 100644 index 000000000..01555be48 --- /dev/null +++ b/modules/assets/prototype_test.go @@ -0,0 +1,36 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package assets + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/assets/internal/block" + "github.com/AssetMantle/modules/modules/assets/internal/genesis" + "github.com/AssetMantle/modules/modules/assets/internal/mapper" + "github.com/AssetMantle/modules/modules/assets/internal/module" + "github.com/AssetMantle/modules/modules/assets/internal/parameters" + "github.com/AssetMantle/modules/modules/assets/internal/queries" + "github.com/AssetMantle/modules/modules/assets/internal/simulator" + "github.com/AssetMantle/modules/modules/assets/internal/transactions" + "github.com/AssetMantle/modules/modules/classifications/auxiliaries" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Name(), baseHelpers.NewModule( + module.Name, + auxiliaries.Prototype, + genesis.Prototype, + mapper.Prototype, + parameters.Prototype, + queries.Prototype, + simulator.Prototype, + transactions.Prototype, + block.Prototype, + ).Name()) + +} diff --git a/modules/classifications/auxiliaries/conform/auxiliary.go b/modules/classifications/auxiliaries/conform/auxiliary.go new file mode 100644 index 000000000..362a8fd7f --- /dev/null +++ b/modules/classifications/auxiliaries/conform/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package conform + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "conform", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "conform", + keeperPrototypeMock, +) diff --git a/modules/classifications/auxiliaries/conform/keeper.go b/modules/classifications/auxiliaries/conform/keeper.go new file mode 100644 index 000000000..a23e8bd23 --- /dev/null +++ b/modules/classifications/auxiliaries/conform/keeper.go @@ -0,0 +1,65 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package conform + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/schema/documents" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + classifications := auxiliaryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(auxiliaryRequest.ClassificationID)) + + Mappable := classifications.Get(key.NewKey(auxiliaryRequest.ClassificationID)) + if Mappable == nil { + return newAuxiliaryResponse(errorConstants.EntityNotFound) + } + classification := Mappable.(documents.Classification) + + if auxiliaryRequest.Immutables != nil { + if len(auxiliaryRequest.Immutables.GetImmutablePropertyList().GetList()) != len(classification.GetImmutables().GetImmutablePropertyList().GetList()) { + return newAuxiliaryResponse(errorConstants.IncorrectFormat) + } + + for _, immutableProperty := range classification.GetImmutables().GetImmutablePropertyList().GetList() { + if property := auxiliaryRequest.Immutables.GetImmutablePropertyList().GetProperty(immutableProperty.GetID()); property == nil || immutableProperty.GetDataID().GetHashID().Compare(baseIDs.GenerateHashID()) != 0 && property.GetDataID().GetHashID().Compare(immutableProperty.GetDataID().GetHashID()) != 0 { + return newAuxiliaryResponse(errorConstants.IncorrectFormat) + } + } + } + + if auxiliaryRequest.Mutables != nil { + if len(auxiliaryRequest.Mutables.GetMutablePropertyList().GetList()) != len(classification.GetMutables().GetMutablePropertyList().GetList()) { + return newAuxiliaryResponse(errorConstants.IncorrectFormat) + } + + for _, mutableProperty := range classification.GetMutables().GetMutablePropertyList().GetList() { + if property := auxiliaryRequest.Mutables.GetMutablePropertyList().GetProperty(mutableProperty.GetID()); property == nil { + return newAuxiliaryResponse(errorConstants.IncorrectFormat) + } + } + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeper{mapper: mapper} +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/classifications/auxiliaries/conform/keeper_mock.go b/modules/classifications/auxiliaries/conform/keeper_mock.go new file mode 100644 index 000000000..68e2b11fe --- /dev/null +++ b/modules/classifications/auxiliaries/conform/keeper_mock.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package conform + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/data/constants" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeperMock)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(_ sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + if auxiliaryRequest.Mutables.GetMutablePropertyList().GetProperty(baseIDs.NewPropertyID(baseIDs.NewStringID("conformError"), constants.IDDataID)) != nil { + return newAuxiliaryResponse(errorConstants.MockError) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/classifications/auxiliaries/conform/keeper_test.go b/modules/classifications/auxiliaries/conform/keeper_test.go new file mode 100644 index 000000000..4de18790d --- /dev/null +++ b/modules/classifications/auxiliaries/conform/keeper_test.go @@ -0,0 +1,162 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package conform + +import ( + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/modules/classifications/internal/mappable" + "github.com/AssetMantle/modules/modules/classifications/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type TestKeepers struct { + ConformKeeper helpers.AuxiliaryKeeper +} + +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + keepers := TestKeepers{ + ConformKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.AuxiliaryKeeper), + } + + return context, keepers, Mapper, Parameters +} + +func Test_auxiliaryKeeper_Help(t *testing.T) { + context, keepers, Mapper, _ := createTestInput(t) + mutables1 := baseQualified.NewMutables(baseLists.NewPropertyList()) + immutables1 := baseQualified.NewImmutables(baseLists.NewPropertyList()) + testClassificationID1 := baseIDs.NewClassificationID(immutables1, mutables1) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + keepers.ConformKeeper.(auxiliaryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(baseDocuments.NewClassification(immutables, mutables))) + type fields struct { + mapper helpers.Mapper + } + type args struct { + context sdkTypes.Context + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + fields fields + args args + want helpers.AuxiliaryResponse + }{ + {"+ve Entity Not Found", fields{Mapper}, args{context, NewAuxiliaryRequest(testClassificationID1, immutables1, mutables1)}, newAuxiliaryResponse(constants.EntityNotFound)}, + {"+ve", fields{Mapper}, args{context, NewAuxiliaryRequest(classificationID, immutables, mutables)}, newAuxiliaryResponse(nil)}, + {"+ve Incorrect Format", fields{Mapper}, args{context, NewAuxiliaryRequest(classificationID, immutables1, mutables)}, newAuxiliaryResponse(constants.IncorrectFormat)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryKeeper := auxiliaryKeeper{ + mapper: tt.fields.mapper, + } + if got := auxiliaryKeeper.Help(tt.args.context, tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Help() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_auxiliaryKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + in2 []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve with nil", fields{}, args{}, auxiliaryKeeper{}}, + {"+ve", fields{Mapper}, args{Mapper, Parameters, []interface{}{}}, auxiliaryKeeper{Mapper}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + au := auxiliaryKeeper{ + mapper: tt.fields.mapper, + } + if got := au.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.AuxiliaryKeeper + }{ + {"+ve", auxiliaryKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/classifications/auxiliaries/conform/request.go b/modules/classifications/auxiliaries/conform/request.go new file mode 100644 index 000000000..b9d97be09 --- /dev/null +++ b/modules/classifications/auxiliaries/conform/request.go @@ -0,0 +1,42 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package conform + +import ( + "github.com/asaskevich/govalidator" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/qualified" +) + +type auxiliaryRequest struct { + ids.ClassificationID + qualified.Immutables + qualified.Mutables +} + +var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) + +func (auxiliaryRequest auxiliaryRequest) Validate() error { + _, err := govalidator.ValidateStruct(auxiliaryRequest) + return err +} + +func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { + switch value := request.(type) { + case auxiliaryRequest: + return value + default: + return auxiliaryRequest{} + } +} + +func NewAuxiliaryRequest(classificationID ids.ClassificationID, immutables qualified.Immutables, mutables qualified.Mutables) helpers.AuxiliaryRequest { + return auxiliaryRequest{ + ClassificationID: classificationID, + Immutables: immutables, + Mutables: mutables, + } +} diff --git a/modules/classifications/auxiliaries/conform/request_test.go b/modules/classifications/auxiliaries/conform/request_test.go new file mode 100644 index 000000000..9b0b5530f --- /dev/null +++ b/modules/classifications/auxiliaries/conform/request_test.go @@ -0,0 +1,98 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package conform + +import ( + "reflect" + "testing" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/qualified" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +func TestNewAuxiliaryRequest(t *testing.T) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + type args struct { + classificationID ids.ClassificationID + immutables qualified.Immutables + mutables qualified.Mutables + } + tests := []struct { + name string + args args + want helpers.AuxiliaryRequest + }{ + {"+ve", args{classificationID, immutables, mutables}, auxiliaryRequest{classificationID, immutables, mutables}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewAuxiliaryRequest(tt.args.classificationID, tt.args.immutables, tt.args.mutables); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewAuxiliaryRequest() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_auxiliaryRequestFromInterface(t *testing.T) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + type args struct { + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + args args + want auxiliaryRequest + }{ + {"+ve", args{NewAuxiliaryRequest(classificationID, immutables, mutables)}, auxiliaryRequest{classificationID, immutables, mutables}}, + {"+ve with nil", args{}, auxiliaryRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := auxiliaryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("auxiliaryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_auxiliaryRequest_Validate(t *testing.T) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + type fields struct { + ClassificationID ids.ClassificationID + Immutables qualified.Immutables + Mutables qualified.Mutables + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve with nil", fields{}, false}, + {"+ve", fields{classificationID, immutables, mutables}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryRequest := auxiliaryRequest{ + ClassificationID: tt.fields.ClassificationID, + Immutables: tt.fields.Immutables, + Mutables: tt.fields.Mutables, + } + if err := auxiliaryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/modules/classifications/auxiliaries/conform/response.go b/modules/classifications/auxiliaries/conform/response.go new file mode 100644 index 000000000..a3b219b41 --- /dev/null +++ b/modules/classifications/auxiliaries/conform/response.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package conform + +import "github.com/AssetMantle/modules/schema/helpers" + +type auxiliaryResponse struct { + Success bool `json:"success"` + Error error `json:"error"` +} + +var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) + +func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { + return auxiliaryResponse.Success +} +func (auxiliaryResponse auxiliaryResponse) GetError() error { + return auxiliaryResponse.Error +} +func newAuxiliaryResponse(error error) helpers.AuxiliaryResponse { + success := true + if error != nil { + success = false + } + + return auxiliaryResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/classifications/auxiliaries/conform/response_test.go b/modules/classifications/auxiliaries/conform/response_test.go new file mode 100644 index 000000000..fb03eb556 --- /dev/null +++ b/modules/classifications/auxiliaries/conform/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package conform + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Conform_Response(t *testing.T) { + testAuxiliaryResponse := newAuxiliaryResponse(nil) + require.Equal(t, auxiliaryResponse{Success: true, Error: nil}, testAuxiliaryResponse) + require.Equal(t, true, testAuxiliaryResponse.IsSuccessful()) + require.Equal(t, nil, testAuxiliaryResponse.GetError()) + + testAuxiliaryResponse2 := newAuxiliaryResponse(constants.IncorrectFormat) + require.Equal(t, auxiliaryResponse{Success: false, Error: constants.IncorrectFormat}, testAuxiliaryResponse2) + require.Equal(t, false, testAuxiliaryResponse2.IsSuccessful()) + require.Equal(t, constants.IncorrectFormat, testAuxiliaryResponse2.GetError()) +} diff --git a/modules/classifications/auxiliaries/define/auxiliary.go b/modules/classifications/auxiliaries/define/auxiliary.go new file mode 100644 index 000000000..312de6f3e --- /dev/null +++ b/modules/classifications/auxiliaries/define/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "define", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "define", + keeperPrototypeMock, +) diff --git a/modules/classifications/auxiliaries/define/keeper.go b/modules/classifications/auxiliaries/define/keeper.go new file mode 100644 index 000000000..2995f903c --- /dev/null +++ b/modules/classifications/auxiliaries/define/keeper.go @@ -0,0 +1,54 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/modules/classifications/internal/mappable" + "github.com/AssetMantle/modules/modules/classifications/internal/module" + "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/utilities/property" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + + if len(auxiliaryRequest.Immutables.GetImmutablePropertyList().GetList())+len(auxiliaryRequest.Mutables.GetMutablePropertyList().GetList()) > module.MaxPropertyCount { + return newAuxiliaryResponse(nil, errorConstants.InvalidRequest) + } + + if property.Duplicate(append(auxiliaryRequest.Immutables.GetImmutablePropertyList().GetList(), auxiliaryRequest.Mutables.GetMutablePropertyList().GetList()...)) { + return newAuxiliaryResponse(nil, errorConstants.InvalidRequest) + } + + classificationID := baseIDs.NewClassificationID(auxiliaryRequest.Immutables, auxiliaryRequest.Mutables) + + classifications := auxiliaryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(classificationID)) + if classifications.Get(key.NewKey(classificationID)) != nil { + return newAuxiliaryResponse(classificationID, errorConstants.EntityAlreadyExists) + } + + classifications.Add(mappable.NewMappable(base.NewClassification(auxiliaryRequest.Immutables, auxiliaryRequest.Mutables))) + + return newAuxiliaryResponse(classificationID, nil) +} + +func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeper{mapper: mapper} +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/classifications/auxiliaries/define/keeper_mock.go b/modules/classifications/auxiliaries/define/keeper_mock.go new file mode 100644 index 000000000..da102a0e2 --- /dev/null +++ b/modules/classifications/auxiliaries/define/keeper_mock.go @@ -0,0 +1,38 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeperMock)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(_ sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + + if len(auxiliaryRequest.Immutables.GetImmutablePropertyList().GetList())+len(auxiliaryRequest.Mutables.GetMutablePropertyList().GetList()) > module.MaxPropertyCount { + return newAuxiliaryResponse(nil, errorConstants.InvalidRequest) + } + + classificationID := baseIDs.NewClassificationID(auxiliaryRequest.Immutables, auxiliaryRequest.Mutables) + + return newAuxiliaryResponse(classificationID, nil) +} + +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/classifications/auxiliaries/define/keeper_test.go b/modules/classifications/auxiliaries/define/keeper_test.go index 9545cd11f..1dac7a4f5 100644 --- a/modules/classifications/auxiliaries/define/keeper_test.go +++ b/modules/classifications/auxiliaries/define/keeper_test.go @@ -5,10 +5,11 @@ package define import ( "fmt" - "github.com/AssetMantle/modules/schema/properties" "reflect" "testing" + "github.com/AssetMantle/modules/schema/properties" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" "github.com/cosmos/cosmos-sdk/codec" @@ -41,9 +42,9 @@ type TestKeepers struct { func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { var Codec = codec.New() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() diff --git a/modules/classifications/auxiliaries/define/request.go b/modules/classifications/auxiliaries/define/request.go new file mode 100644 index 000000000..34121b97f --- /dev/null +++ b/modules/classifications/auxiliaries/define/request.go @@ -0,0 +1,39 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + "github.com/asaskevich/govalidator" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/qualified" +) + +type auxiliaryRequest struct { + qualified.Immutables `json:"immutables" valid:"required~required field immutableProperties missing"` + qualified.Mutables `json:"mutables" valid:"required~required field mutableProperties missing"` +} + +var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) + +func (auxiliaryRequest auxiliaryRequest) Validate() error { + _, err := govalidator.ValidateStruct(auxiliaryRequest) + return err +} + +func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { + switch value := request.(type) { + case auxiliaryRequest: + return value + default: + return auxiliaryRequest{} + } +} + +func NewAuxiliaryRequest(immutables qualified.Immutables, mutables qualified.Mutables) helpers.AuxiliaryRequest { + return auxiliaryRequest{ + Immutables: immutables, + Mutables: mutables, + } +} diff --git a/modules/classifications/auxiliaries/define/request_test.go b/modules/classifications/auxiliaries/define/request_test.go new file mode 100644 index 000000000..084c8e560 --- /dev/null +++ b/modules/classifications/auxiliaries/define/request_test.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + "testing" + + "github.com/stretchr/testify/require" + + baseData "github.com/AssetMantle/modules/schema/data/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +func Test_Define_Request(t *testing.T) { + + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + + testAuxiliaryRequest := NewAuxiliaryRequest(immutables, mutables) + + require.Equal(t, auxiliaryRequest{Immutables: immutables, Mutables: mutables}, testAuxiliaryRequest) + require.Equal(t, nil, testAuxiliaryRequest.Validate()) + require.Equal(t, testAuxiliaryRequest, auxiliaryRequestFromInterface(testAuxiliaryRequest)) + require.Equal(t, auxiliaryRequest{}, auxiliaryRequestFromInterface(nil)) + +} diff --git a/modules/classifications/auxiliaries/define/response.go b/modules/classifications/auxiliaries/define/response.go index 0d617c844..227f92c38 100644 --- a/modules/classifications/auxiliaries/define/response.go +++ b/modules/classifications/auxiliaries/define/response.go @@ -1,20 +1,18 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" ) type auxiliaryResponse struct { - Success bool `json:"success"` - Error error `json:"error"` - ClassificationID types.ID `json:"classificationID"` + Success bool `json:"success"` + Error error `json:"error"` + ids.ClassificationID `json:"classificationID"` } var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) @@ -26,7 +24,7 @@ func (auxiliaryResponse auxiliaryResponse) GetError() error { return auxiliaryResponse.Error } -func newAuxiliaryResponse(classificationID types.ID, error error) helpers.AuxiliaryResponse { +func newAuxiliaryResponse(classificationID ids.ClassificationID, error error) helpers.AuxiliaryResponse { if error != nil { return auxiliaryResponse{ Success: false, @@ -41,7 +39,7 @@ func newAuxiliaryResponse(classificationID types.ID, error error) helpers.Auxili } } -func GetClassificationIDFromResponse(response helpers.AuxiliaryResponse) (types.ID, error) { +func GetClassificationIDFromResponse(response helpers.AuxiliaryResponse) (ids.ClassificationID, error) { switch value := response.(type) { case auxiliaryResponse: if value.IsSuccessful() { @@ -50,6 +48,6 @@ func GetClassificationIDFromResponse(response helpers.AuxiliaryResponse) (types. return value.ClassificationID, value.GetError() default: - return nil, errors.InvalidRequest + return nil, constants.InvalidRequest } } diff --git a/modules/classifications/auxiliaries/define/response_test.go b/modules/classifications/auxiliaries/define/response_test.go new file mode 100644 index 000000000..cfa70b64d --- /dev/null +++ b/modules/classifications/auxiliaries/define/response_test.go @@ -0,0 +1,133 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + "reflect" + "testing" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +func createTestInput() ids.ClassificationID { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + + return classificationID +} + +func TestGetClassificationIDFromResponse(t *testing.T) { + classificationID := createTestInput() + type args struct { + response helpers.AuxiliaryResponse + } + tests := []struct { + name string + args args + want ids.ClassificationID + wantErr bool + }{ + {"+ve", args{newAuxiliaryResponse(classificationID, nil)}, classificationID, false}, + {"+ve", args{newAuxiliaryResponse(nil, nil)}, nil, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := GetClassificationIDFromResponse(tt.args.response) + if (err != nil) != tt.wantErr { + t.Errorf("GetClassificationIDFromResponse() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetClassificationIDFromResponse() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_auxiliaryResponse_GetError(t *testing.T) { + classificationID := createTestInput() + type fields struct { + Success bool + Error error + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{true, nil, classificationID}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryResponse := auxiliaryResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + ClassificationID: tt.fields.ClassificationID, + } + if err := auxiliaryResponse.GetError(); (err != nil) != tt.wantErr { + t.Errorf("GetError() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_auxiliaryResponse_IsSuccessful(t *testing.T) { + classificationID := createTestInput() + type fields struct { + Success bool + Error error + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want bool + }{ + {"+ve", fields{true, nil, classificationID}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryResponse := auxiliaryResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + ClassificationID: tt.fields.ClassificationID, + } + if got := auxiliaryResponse.IsSuccessful(); got != tt.want { + t.Errorf("IsSuccessful() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_newAuxiliaryResponse(t *testing.T) { + classificationID := createTestInput() + type args struct { + classificationID ids.ClassificationID + error error + } + tests := []struct { + name string + args args + want helpers.AuxiliaryResponse + }{ + {"+ve", args{classificationID, nil}, auxiliaryResponse{true, nil, classificationID}}, + {"-ve", args{classificationID, constants.EntityNotFound}, auxiliaryResponse{false, constants.EntityNotFound, classificationID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newAuxiliaryResponse(tt.args.classificationID, tt.args.error); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newAuxiliaryResponse() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/classifications/auxiliaries/member/auxiliary.go b/modules/classifications/auxiliaries/member/auxiliary.go new file mode 100644 index 000000000..c2881ab5f --- /dev/null +++ b/modules/classifications/auxiliaries/member/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package member + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "member", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "member", + keeperPrototypeMock, +) diff --git a/modules/classifications/auxiliaries/member/keeper.go b/modules/classifications/auxiliaries/member/keeper.go new file mode 100644 index 000000000..d88174161 --- /dev/null +++ b/modules/classifications/auxiliaries/member/keeper.go @@ -0,0 +1,65 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package member + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/schema/documents" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + classifications := auxiliaryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(auxiliaryRequest.ClassificationID)) + + Mappable := classifications.Get(key.NewKey(auxiliaryRequest.ClassificationID)) + if Mappable == nil { + return newAuxiliaryResponse(errorConstants.EntityNotFound) + } + classification := Mappable.(documents.Classification) + + if auxiliaryRequest.Immutables != nil { + if len(auxiliaryRequest.Immutables.GetImmutablePropertyList().GetList()) > len(classification.GetImmutables().GetImmutablePropertyList().GetList()) { + return newAuxiliaryResponse(errorConstants.IncorrectFormat) + } + + for _, immutableProperty := range auxiliaryRequest.Immutables.GetImmutablePropertyList().GetList() { + if property := classification.GetImmutables().GetImmutablePropertyList().GetProperty(immutableProperty.GetID()); property == nil || immutableProperty.GetDataID().GetHashID().Compare(baseIDs.GenerateHashID()) != 0 && property.GetDataID().GetHashID().Compare(immutableProperty.GetDataID().GetHashID()) != 0 { + return newAuxiliaryResponse(errorConstants.IncorrectFormat) + } + } + } + + if auxiliaryRequest.Mutables != nil { + if len(auxiliaryRequest.Mutables.GetMutablePropertyList().GetList()) > len(classification.GetMutables().GetMutablePropertyList().GetList()) { + return newAuxiliaryResponse(errorConstants.IncorrectFormat) + } + + for _, mutableProperty := range auxiliaryRequest.Mutables.GetMutablePropertyList().GetList() { + if property := classification.GetMutables().GetMutablePropertyList().GetProperty(mutableProperty.GetID()); property == nil { + return newAuxiliaryResponse(errorConstants.IncorrectFormat) + } + } + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeper{mapper: mapper} +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/classifications/auxiliaries/member/keeper_mock.go b/modules/classifications/auxiliaries/member/keeper_mock.go new file mode 100644 index 000000000..e828f034d --- /dev/null +++ b/modules/classifications/auxiliaries/member/keeper_mock.go @@ -0,0 +1,53 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package member + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/schema/data/constants" + "github.com/AssetMantle/modules/schema/documents" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeperMock)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + if auxiliaryRequest.Mutables.GetMutablePropertyList().GetProperty(baseIDs.NewPropertyID(baseIDs.NewStringID("memberError"), constants.IDDataID)) != nil { + classifications := auxiliaryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(auxiliaryRequest.ClassificationID)) + Mappable := classifications.Get(key.NewKey(auxiliaryRequest.ClassificationID)) + if Mappable == nil { + return newAuxiliaryResponse(errorConstants.EntityNotFound) + } + classification := Mappable.(documents.Classification) + if auxiliaryRequest.Mutables != nil { + if len(auxiliaryRequest.Mutables.GetMutablePropertyList().GetList()) > len(classification.GetMutables().GetMutablePropertyList().GetList()) { + return newAuxiliaryResponse(errorConstants.IncorrectFormat) + } + + for _, mutableProperty := range auxiliaryRequest.Mutables.GetMutablePropertyList().GetList() { + if property := classification.GetMutables().GetMutablePropertyList().GetProperty(mutableProperty.GetID()); property == nil { + return newAuxiliaryResponse(errorConstants.IncorrectFormat) + } + } + } + } + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} + +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/classifications/auxiliaries/member/keeper_test.go b/modules/classifications/auxiliaries/member/keeper_test.go new file mode 100644 index 000000000..3bc3fa155 --- /dev/null +++ b/modules/classifications/auxiliaries/member/keeper_test.go @@ -0,0 +1,161 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package member + +import ( + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/modules/classifications/internal/mappable" + "github.com/AssetMantle/modules/modules/classifications/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type TestKeepers struct { + MemberKeeper helpers.AuxiliaryKeeper +} + +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + keepers := TestKeepers{ + MemberKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.AuxiliaryKeeper), + } + + return context, keepers, Mapper, Parameters +} + +func Test_auxiliaryKeeper_Help(t *testing.T) { + context, keepers, Mapper, _ := createTestInput(t) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + immutables1 := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")), baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("ImmutableData")))) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + classificationID1 := baseIDs.NewClassificationID(immutables1, mutables) + keepers.MemberKeeper.(auxiliaryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(baseDocuments.NewClassification(immutables, mutables))) + type fields struct { + mapper helpers.Mapper + } + type args struct { + context sdkTypes.Context + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + fields fields + args args + want helpers.AuxiliaryResponse + }{ + {"+ve", fields{Mapper}, args{context, NewAuxiliaryRequest(classificationID, immutables, mutables)}, newAuxiliaryResponse(nil)}, + {"+ve Entity Not found", fields{Mapper}, args{context, NewAuxiliaryRequest(classificationID1, immutables, mutables)}, newAuxiliaryResponse(errorConstants.EntityNotFound)}, + {"+ve IncorrectFormat", fields{Mapper}, args{context, NewAuxiliaryRequest(classificationID, immutables1, mutables)}, newAuxiliaryResponse(errorConstants.IncorrectFormat)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryKeeper := auxiliaryKeeper{ + mapper: tt.fields.mapper, + } + if got := auxiliaryKeeper.Help(tt.args.context, tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Help() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_auxiliaryKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + in2 []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve with nil", fields{}, args{}, auxiliaryKeeper{}}, + {"+ve", fields{Mapper}, args{Mapper, Parameters, []interface{}{}}, auxiliaryKeeper{Mapper}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + au := auxiliaryKeeper{ + mapper: tt.fields.mapper, + } + if got := au.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.AuxiliaryKeeper + }{ + {"+ve", auxiliaryKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/classifications/auxiliaries/member/request.go b/modules/classifications/auxiliaries/member/request.go new file mode 100644 index 000000000..e96a1412b --- /dev/null +++ b/modules/classifications/auxiliaries/member/request.go @@ -0,0 +1,43 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package member + +import ( + "github.com/asaskevich/govalidator" + + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/qualified" +) + +type auxiliaryRequest struct { + ids.ClassificationID `json:"classificationID" valid:"required~required field classificationID missing"` + qualified.Immutables `json:"immutableProperties"` + qualified.Mutables `json:"mutableProperties"` +} + +var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) + +func (auxiliaryRequest auxiliaryRequest) Validate() error { + _, err := govalidator.ValidateStruct(auxiliaryRequest) + return err +} + +func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { + switch value := request.(type) { + case auxiliaryRequest: + return value + default: + panic(errorConstants.InvalidRequest) + } +} + +func NewAuxiliaryRequest(classificationID ids.ClassificationID, immutables qualified.Immutables, mutables qualified.Mutables) helpers.AuxiliaryRequest { + return auxiliaryRequest{ + ClassificationID: classificationID, + Immutables: immutables, + Mutables: mutables, + } +} diff --git a/modules/classifications/auxiliaries/member/response.go b/modules/classifications/auxiliaries/member/response.go new file mode 100644 index 000000000..4937df5fe --- /dev/null +++ b/modules/classifications/auxiliaries/member/response.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package member + +import "github.com/AssetMantle/modules/schema/helpers" + +type auxiliaryResponse struct { + Success bool `json:"success"` + Error error `json:"error"` +} + +var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) + +func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { + return auxiliaryResponse.Success +} +func (auxiliaryResponse auxiliaryResponse) GetError() error { + return auxiliaryResponse.Error +} +func newAuxiliaryResponse(error error) helpers.AuxiliaryResponse { + success := true + if error != nil { + success = false + } + + return auxiliaryResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/classifications/auxiliaries/member/response_test.go b/modules/classifications/auxiliaries/member/response_test.go new file mode 100644 index 000000000..de541c33d --- /dev/null +++ b/modules/classifications/auxiliaries/member/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package member + +import ( + "testing" + + "github.com/AssetMantle/modules/schema/errors/constants" + + "github.com/stretchr/testify/require" +) + +func Test_Conform_Response(t *testing.T) { + testAuxiliaryResponse := newAuxiliaryResponse(nil) + require.Equal(t, auxiliaryResponse{Success: true, Error: nil}, testAuxiliaryResponse) + require.Equal(t, true, testAuxiliaryResponse.IsSuccessful()) + require.Equal(t, nil, testAuxiliaryResponse.GetError()) + + testAuxiliaryResponse2 := newAuxiliaryResponse(constants.IncorrectFormat) + require.Equal(t, auxiliaryResponse{Success: false, Error: constants.IncorrectFormat}, testAuxiliaryResponse2) + require.Equal(t, false, testAuxiliaryResponse2.IsSuccessful()) + require.Equal(t, constants.IncorrectFormat, testAuxiliaryResponse2.GetError()) +} diff --git a/modules/classifications/auxiliaries/prototype.go b/modules/classifications/auxiliaries/prototype.go new file mode 100644 index 000000000..e5e979db4 --- /dev/null +++ b/modules/classifications/auxiliaries/prototype.go @@ -0,0 +1,20 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/define" + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/member" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Auxiliaries { + return baseHelpers.NewAuxiliaries( + conform.Auxiliary, + define.Auxiliary, + member.Auxiliary, + ) +} diff --git a/modules/classifications/auxiliaries/prototype_test.go b/modules/classifications/auxiliaries/prototype_test.go new file mode 100644 index 000000000..01155311d --- /dev/null +++ b/modules/classifications/auxiliaries/prototype_test.go @@ -0,0 +1,21 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/define" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, baseHelpers.NewAuxiliaries( + conform.Auxiliary, + define.Auxiliary, + ).Get(""), Prototype().Get("")) +} diff --git a/modules/classifications/doc.go b/modules/classifications/doc.go new file mode 100644 index 000000000..50dcc8a89 --- /dev/null +++ b/modules/classifications/doc.go @@ -0,0 +1,5 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +// Package classifications defines the classifications module. +package classifications diff --git a/modules/classifications/internal/block/block.go b/modules/classifications/internal/block/block.go new file mode 100644 index 000000000..2b406cdb0 --- /dev/null +++ b/modules/classifications/internal/block/block.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package block + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + abciTypes "github.com/tendermint/tendermint/abci/types" + + "github.com/AssetMantle/modules/schema/helpers" +) + +type block struct { + mapper helpers.Mapper + parameters helpers.Parameters +} + +var _ helpers.Block = (*block)(nil) + +func (block block) Begin(_ sdkTypes.Context, _ abciTypes.RequestBeginBlock) { + +} + +func (block block) End(_ sdkTypes.Context, _ abciTypes.RequestEndBlock) { + +} + +func Prototype() helpers.Block { + return block{} +} + +func (block block) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, _ ...interface{}) helpers.Block { + block.mapper, block.parameters = mapper, parameters + return block +} diff --git a/modules/classifications/internal/block/block_test.go b/modules/classifications/internal/block/block_test.go new file mode 100644 index 000000000..8f94af36c --- /dev/null +++ b/modules/classifications/internal/block/block_test.go @@ -0,0 +1,57 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package block + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/classifications/internal/mapper" + "github.com/AssetMantle/modules/modules/classifications/internal/parameters" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" +) + +func CreateTestInput(t *testing.T) sdkTypes.Context { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + return context +} + +func Test_Block_Methods(t *testing.T) { + block := Prototype() + block.Initialize(mapper.Prototype(), parameters.Prototype(), []helpers.Auxiliary{}) + context := CreateTestInput(t) + block.Begin(context, abciTypes.RequestBeginBlock{}) + block.End(context, abciTypes.RequestEndBlock{}) +} diff --git a/modules/classifications/internal/common/codec.go b/modules/classifications/internal/common/codec.go new file mode 100644 index 000000000..f352ea531 --- /dev/null +++ b/modules/classifications/internal/common/codec.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package common + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/modules/classifications/internal/mappable" + "github.com/AssetMantle/modules/utilities/module" +) + +var Codec *codec.Codec + +func init() { + Codec = module.RegisterCodec(key.Prototype, mappable.Prototype) +} diff --git a/modules/classifications/internal/genesis/genesis.go b/modules/classifications/internal/genesis/genesis.go deleted file mode 100644 index caaab72cf..000000000 --- a/modules/classifications/internal/genesis/genesis.go +++ /dev/null @@ -1,188 +0,0 @@ -package genesis - -import ( - "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ helpers.Genesis = (*Genesis)(nil) - -func (genesis Genesis) Default() helpers.Genesis { - return genesis.Initialize(genesis.GetMappableList(), genesis.GetParameterList()) -} - -func (genesis Genesis) Validate() error { - if len(genesis.ParameterList) != len(genesis.DefaultParameterList) { - return errors.InvalidParameter - } - - for _, parameter := range genesis.ParameterList { - var isPresent bool - for _, defaultParameter := range genesis.DefaultParameterList { - isPresent = false - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - isPresent = true - break - } - } - - if !isPresent { - return errors.InvalidParameter - } - - if Error := parameter.Validate(); Error != nil { - return Error - } - } - - _, Error := govalidator.ValidateStruct(genesis) - - return Error -} - -func (genesis Genesis) Import(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) { - for _, mappableValue := range genesis.MappableList { - mapper.Create(context, &mappableValue) - } - - for _, parameter := range genesis.ParameterList { - parameters.Mutate(context, ¶meter) - } -} - -func (genesis Genesis) Export(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) helpers.Genesis { - var mappableList []helpers.Mappable - - appendMappableList := func(mappable helpers.Mappable) bool { - mappableList = append(mappableList, mappable) - return false - } - mapper.Iterate(context, key.Prototype(), appendMappableList) - - for _, defaultParameter := range genesis.DefaultParameterList { - parameters = parameters.Fetch(context, defaultParameter.GetID()) - } - - return genesis.Initialize(mappableList, parameters.GetList()) -} - -func (genesis Genesis) LegacyAminoEncode() []byte { - legacyAminoCodec := codec.NewLegacyAmino() - bytes, Error := legacyAminoCodec.MarshalJSON(genesis) - if Error != nil { - panic(Error) - } - - return bytes -} -func (genesis Genesis) LegacyAminoDecode(byte []byte) helpers.Genesis { - var newGenesis Genesis - legacyAminoCodec := codec.NewLegacyAmino() - if Error := legacyAminoCodec.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(genesis.DefaultMappableList, genesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Encode(cdc codec.JSONMarshaler) []byte { - bytes, Error := cdc.MarshalJSON(&genesis) - if Error != nil { - panic(Error) - } - - return bytes -} - -func (genesis Genesis) Decode(cdc codec.JSONMarshaler, byte []byte) helpers.Genesis { - var newGenesis Genesis - if Error := cdc.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(newGenesis.DefaultMappableList, newGenesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Initialize(mappableList []helpers.Mappable, parameterList []types.Parameter) helpers.Genesis { - newParametersList := make([]dummy.DummyParameter, len(parameterList)) - for i, _ := range parameterList { - newParametersList[i] = *dummy.NewParameter(parameterList[i].GetID(), parameterList[i].GetData()) - } - newMappableList := make([]mappable.Classification, len(mappableList)) - for i, _ := range mappableList { - newMappableList[i] = *mappableList[i].(*mappable.Classification) - } - newParameter := dummy.Parameter.Mutate(dummy.Parameter.GetData()) - genesis.DefaultParameterList = []dummy.DummyParameter{*dummy.NewParameter(newParameter.GetID(), newParameter.GetData())} - if len(newMappableList) == 0 { - genesis.MappableList = genesis.DefaultMappableList - } else { - genesis.MappableList = newMappableList - } - - if len(newParametersList) == 0 { - genesis.ParameterList = genesis.DefaultParameterList - } else { - for _, defaultParameter := range genesis.DefaultParameterList { - for i, parameter := range newParametersList { - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - newParametersList[i] = *dummy.NewParameter(defaultParameter.Mutate(parameter.GetData()).GetID(), defaultParameter.Mutate(parameter.GetData()).GetData()) - } - } - } - genesis.ParameterList = newParametersList - } - - if Error := genesis.Validate(); Error != nil { - panic(Error) - } - - return &genesis -} - -func (genesis Genesis) GetParameterList() []types.Parameter { - newParameterList := make([]types.Parameter, len(genesis.ParameterList)) - for i, _ := range genesis.ParameterList { - newParameterList[i] = &genesis.ParameterList[i] - } - return newParameterList -} -func (genesis Genesis) GetMappableList() []helpers.Mappable { - newMappableList := make([]helpers.Mappable, len(genesis.MappableList)) - for i, _ := range genesis.MappableList { - newMappableList[i] = &genesis.MappableList[i] - } - return newMappableList -} - -func (genesis Genesis) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*helpers.Key)(nil), - &key.ClassificationID{}, - ) - registry.RegisterImplementations((*helpers.Mappable)(nil), - &mappable.Classification{}, - ) - registry.RegisterImplementations((*types.Parameter)(nil), - &dummy.DummyParameter{}, - ) - registry.RegisterImplementations((*helpers.Genesis)(nil), - &Genesis{}, - ) -} - -func NewGenesis(defaultMappableList []mappable.Classification, defaultParameterList []dummy.DummyParameter) *Genesis { - return &Genesis{ - DefaultMappableList: defaultMappableList, - DefaultParameterList: defaultParameterList, - MappableList: []mappable.Classification{}, - ParameterList: []dummy.DummyParameter{}, - } -} diff --git a/modules/classifications/internal/genesis/genesis.pb.go b/modules/classifications/internal/genesis/genesis.pb.go deleted file mode 100644 index 0113b80c9..000000000 --- a/modules/classifications/internal/genesis/genesis.pb.go +++ /dev/null @@ -1,500 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/classifications/internal/genesis/genesis.proto - -package genesis - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - mappable "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/mappable" - dummy "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/parameters/dummy" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Genesis struct { - DefaultMappableList []mappable.Classification `protobuf:"bytes,1,rep,name=defaultMappableList,proto3" json:"defaultMappableList"` - DefaultParameterList []dummy.DummyParameter `protobuf:"bytes,2,rep,name=defaultParameterList,proto3" json:"defaultParameterList"` - MappableList []mappable.Classification `protobuf:"bytes,3,rep,name=MappableList,proto3" json:"MappableList"` - ParameterList []dummy.DummyParameter `protobuf:"bytes,4,rep,name=ParameterList,proto3" json:"ParameterList"` -} - -func (m *Genesis) Reset() { *m = Genesis{} } -func (m *Genesis) String() string { return proto.CompactTextString(m) } -func (*Genesis) ProtoMessage() {} -func (*Genesis) Descriptor() ([]byte, []int) { - return fileDescriptor_482e9ef79a2f0a3d, []int{0} -} -func (m *Genesis) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Genesis) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Genesis.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Genesis) XXX_Merge(src proto.Message) { - xxx_messageInfo_Genesis.Merge(m, src) -} -func (m *Genesis) XXX_Size() int { - return m.Size() -} -func (m *Genesis) XXX_DiscardUnknown() { - xxx_messageInfo_Genesis.DiscardUnknown(m) -} - -var xxx_messageInfo_Genesis proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Genesis)(nil), "persistence_sdk.modules.classifications.internal.genesis.Genesis") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/classifications/internal/genesis/genesis.proto", fileDescriptor_482e9ef79a2f0a3d) -} - -var fileDescriptor_482e9ef79a2f0a3d = []byte{ - // 341 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x72, 0x2b, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0x4f, 0xce, 0x49, 0x2c, 0x2e, 0xce, 0x4c, 0xcb, 0x4c, 0x4e, 0x2c, 0xc9, - 0xcc, 0xcf, 0x2b, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, 0xca, 0x4b, 0xcc, 0xd1, 0x4f, 0x4f, 0xcd, - 0x4b, 0x2d, 0xce, 0x2c, 0x86, 0xd1, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x16, 0x68, 0xe6, - 0xe8, 0x41, 0xcd, 0xd1, 0x43, 0x33, 0x47, 0x0f, 0x66, 0x8e, 0x1e, 0x54, 0xbf, 0x94, 0x48, 0x7a, - 0x7e, 0x7a, 0x3e, 0xd8, 0x10, 0x7d, 0x10, 0x0b, 0x62, 0x9e, 0x94, 0x1f, 0xc9, 0xee, 0xca, 0x4d, - 0x2c, 0x28, 0x48, 0x4c, 0xca, 0x49, 0x45, 0x53, 0x01, 0x35, 0x2f, 0x90, 0x64, 0xf3, 0x0a, 0x12, - 0x8b, 0x12, 0x73, 0x53, 0x4b, 0x52, 0x8b, 0x8a, 0xf5, 0x53, 0x4a, 0x73, 0x73, 0x2b, 0x11, 0x02, - 0x10, 0x23, 0x95, 0xa6, 0xb2, 0x70, 0xb1, 0xbb, 0x43, 0x3c, 0x21, 0xd4, 0xc8, 0xc8, 0x25, 0x9c, - 0x92, 0x9a, 0x96, 0x58, 0x9a, 0x53, 0xe2, 0x0b, 0x75, 0x87, 0x4f, 0x66, 0x71, 0x89, 0x04, 0xa3, - 0x02, 0xb3, 0x06, 0xb7, 0x91, 0xa7, 0x1e, 0xc9, 0xa1, 0x03, 0xf3, 0x8d, 0x9e, 0x33, 0x8a, 0x0a, - 0x27, 0x96, 0x13, 0xf7, 0xe4, 0x19, 0x82, 0xb0, 0xd9, 0x25, 0xd4, 0xcd, 0xc8, 0x25, 0x02, 0x15, - 0x0f, 0x80, 0x39, 0x15, 0xec, 0x08, 0x26, 0xb0, 0x23, 0x02, 0x49, 0x77, 0x04, 0x22, 0x08, 0xf4, - 0xc0, 0x41, 0xa0, 0xe7, 0x02, 0x22, 0xe1, 0x86, 0x43, 0x1d, 0x83, 0xd5, 0x52, 0xa1, 0x62, 0x2e, - 0x1e, 0x94, 0x90, 0x60, 0xa6, 0x4d, 0x48, 0xa0, 0x58, 0x22, 0x54, 0xcb, 0xc5, 0x8b, 0xea, 0x75, - 0x16, 0xda, 0x7a, 0x1d, 0xd5, 0x36, 0x2b, 0x96, 0x8e, 0x05, 0xf2, 0x0c, 0x4e, 0xd9, 0x27, 0x1e, - 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, - 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0x10, 0x15, 0x98, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, - 0x97, 0x9c, 0x9f, 0xab, 0x8f, 0xe4, 0x22, 0xff, 0xbc, 0x54, 0x64, 0x6e, 0xb0, 0x8b, 0x37, 0xd1, - 0xb9, 0x30, 0x89, 0x0d, 0x9c, 0x16, 0x8d, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x1c, 0x9a, 0x5a, - 0x57, 0xc8, 0x03, 0x00, 0x00, -} - -func (m *Genesis) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Genesis) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Genesis) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ParameterList) > 0 { - for iNdEx := len(m.ParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.MappableList) > 0 { - for iNdEx := len(m.MappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.DefaultParameterList) > 0 { - for iNdEx := len(m.DefaultParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.DefaultMappableList) > 0 { - for iNdEx := len(m.DefaultMappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultMappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Genesis) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.DefaultMappableList) > 0 { - for _, e := range m.DefaultMappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.DefaultParameterList) > 0 { - for _, e := range m.DefaultParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.MappableList) > 0 { - for _, e := range m.MappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ParameterList) > 0 { - for _, e := range m.ParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Genesis) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Genesis: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Genesis: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultMappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultMappableList = append(m.DefaultMappableList, mappable.Classification{}) - if err := m.DefaultMappableList[len(m.DefaultMappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultParameterList = append(m.DefaultParameterList, dummy.DummyParameter{}) - if err := m.DefaultParameterList[len(m.DefaultParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MappableList = append(m.MappableList, mappable.Classification{}) - if err := m.MappableList[len(m.MappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ParameterList = append(m.ParameterList, dummy.DummyParameter{}) - if err := m.ParameterList[len(m.ParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/classifications/internal/genesis/prototype.go b/modules/classifications/internal/genesis/prototype.go index 2e4245737..54a0c8ff7 100644 --- a/modules/classifications/internal/genesis/prototype.go +++ b/modules/classifications/internal/genesis/prototype.go @@ -1,16 +1,18 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package genesis import ( - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/modules/classifications/internal/mappable" + "github.com/AssetMantle/modules/modules/classifications/internal/parameters" + "github.com/AssetMantle/modules/schema/documents/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" ) +// TODO ***** add default classes NUB,maintainer, self class func Prototype() helpers.Genesis { - return NewGenesis([]mappable.Classification{}, []dummy.DummyParameter{}) + return baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{mappable.NewMappable(constants.NubClassification), mappable.NewMappable(constants.MaintainerClassification)}, parameters.Prototype().GetList()) } diff --git a/modules/classifications/internal/genesis/prototype_test.go b/modules/classifications/internal/genesis/prototype_test.go index 2c33446f6..c30674629 100644 --- a/modules/classifications/internal/genesis/prototype_test.go +++ b/modules/classifications/internal/genesis/prototype_test.go @@ -1,14 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + package genesis import ( - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/stretchr/testify/require" "testing" + + "github.com/AssetMantle/modules/schema/documents/constants" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/modules/classifications/internal/mappable" + "github.com/AssetMantle/modules/modules/classifications/internal/parameters" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" ) func TestPrototype(t *testing.T) { require.Panics(t, func() { - require.Equal(t, Prototype(), NewGenesis([]helpers.Mappable{}, parameters.Prototype().GetList())) + require.Equal(t, Prototype(), baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{mappable.NewMappable(constants.NubClassification), mappable.NewMappable(constants.MaintainerClassification)}, parameters.Prototype().GetList())) }) } diff --git a/modules/classifications/internal/key/classifictionID.pb.go b/modules/classifications/internal/key/classifictionID.pb.go deleted file mode 100644 index 2cf2f3f7e..000000000 --- a/modules/classifications/internal/key/classifictionID.pb.go +++ /dev/null @@ -1,367 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/classifications/internal/key/classifictionID.proto - -package key - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - github_com_persistenceOne_persistenceSDK_schema_types "github.com/persistenceOne/persistenceSDK/schema/types" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type ClassificationID struct { - ChainID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,1,opt,name=chain_i_d,json=chainID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"chain_i_d"` - HashID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,2,opt,name=hash_i_d,json=hashID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"hash_i_d"` -} - -func (m *ClassificationID) Reset() { *m = ClassificationID{} } -func (*ClassificationID) ProtoMessage() {} -func (*ClassificationID) Descriptor() ([]byte, []int) { - return fileDescriptor_3bfd5ee2cc87a76a, []int{0} -} -func (m *ClassificationID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ClassificationID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ClassificationID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *ClassificationID) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClassificationID.Merge(m, src) -} -func (m *ClassificationID) XXX_Size() int { - return m.Size() -} -func (m *ClassificationID) XXX_DiscardUnknown() { - xxx_messageInfo_ClassificationID.DiscardUnknown(m) -} - -var xxx_messageInfo_ClassificationID proto.InternalMessageInfo - -func init() { - proto.RegisterType((*ClassificationID)(nil), "persistence_sdk.modules.classifications.internal.key.ClassificationID") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/classifications/internal/key/classifictionID.proto", fileDescriptor_3bfd5ee2cc87a76a) -} - -var fileDescriptor_3bfd5ee2cc87a76a = []byte{ - // 269 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xf2, 0x2a, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0x4f, 0xce, 0x49, 0x2c, 0x2e, 0xce, 0x4c, 0xcb, 0x4c, 0x4e, 0x2c, 0xc9, - 0xcc, 0xcf, 0x2b, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, 0xca, 0x4b, 0xcc, 0xd1, 0xcf, 0x4e, 0xad, - 0x44, 0x48, 0x82, 0xe4, 0x3c, 0x5d, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x4c, 0xd0, 0xcc, - 0xd2, 0x83, 0x9a, 0xa5, 0x87, 0x66, 0x96, 0x1e, 0xcc, 0x2c, 0xbd, 0xec, 0xd4, 0x4a, 0x29, 0x91, - 0xf4, 0xfc, 0xf4, 0x7c, 0xb0, 0x01, 0xfa, 0x20, 0x16, 0xc4, 0x2c, 0xa5, 0x4b, 0x8c, 0x5c, 0x02, - 0xce, 0x28, 0xda, 0x3c, 0x5d, 0x84, 0x62, 0xb8, 0x38, 0x93, 0x33, 0x12, 0x33, 0xf3, 0xe2, 0x33, - 0xe3, 0x53, 0x24, 0x18, 0x15, 0x18, 0x35, 0x38, 0x9d, 0x1c, 0x4e, 0xdc, 0x93, 0x67, 0xb8, 0x75, - 0x4f, 0xde, 0x22, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0x1f, 0xc9, 0x19, - 0xfe, 0x79, 0xa9, 0xc8, 0xdc, 0x60, 0x17, 0x6f, 0xfd, 0xe2, 0xe4, 0x8c, 0xd4, 0xdc, 0x44, 0xfd, - 0x92, 0xca, 0x82, 0xd4, 0x62, 0x3d, 0x4f, 0x97, 0x20, 0x76, 0xb0, 0x91, 0x9e, 0x2e, 0x42, 0x51, - 0x5c, 0x1c, 0x19, 0x89, 0xc5, 0x19, 0x60, 0xc3, 0x99, 0xa8, 0x64, 0x38, 0x1b, 0xc8, 0x44, 0x4f, - 0x17, 0x2b, 0x96, 0x19, 0x0b, 0xe4, 0x19, 0x9c, 0xd2, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, - 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, - 0x58, 0x8e, 0x21, 0xca, 0x97, 0x68, 0x1b, 0x88, 0x89, 0x9f, 0x24, 0x36, 0x70, 0x20, 0x1a, 0x03, - 0x02, 0x00, 0x00, 0xff, 0xff, 0xd7, 0xdf, 0xd3, 0x3f, 0xde, 0x01, 0x00, 0x00, -} - -func (m *ClassificationID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ClassificationID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ClassificationID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.HashID.Size() - i -= size - if _, err := m.HashID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintClassifictionID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.ChainID.Size() - i -= size - if _, err := m.ChainID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintClassifictionID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintClassifictionID(dAtA []byte, offset int, v uint64) int { - offset -= sovClassifictionID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *ClassificationID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ChainID.Size() - n += 1 + l + sovClassifictionID(uint64(l)) - l = m.HashID.Size() - n += 1 + l + sovClassifictionID(uint64(l)) - return n -} - -func sovClassifictionID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozClassifictionID(x uint64) (n int) { - return sovClassifictionID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *ClassificationID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClassifictionID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ClassificationID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ClassificationID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ChainID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClassifictionID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthClassifictionID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthClassifictionID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ChainID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HashID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClassifictionID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthClassifictionID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthClassifictionID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HashID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClassifictionID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClassifictionID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipClassifictionID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowClassifictionID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowClassifictionID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowClassifictionID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthClassifictionID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupClassifictionID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthClassifictionID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthClassifictionID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowClassifictionID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupClassifictionID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/classifications/internal/key/key.go b/modules/classifications/internal/key/key.go new file mode 100644 index 000000000..cdaf5226c --- /dev/null +++ b/modules/classifications/internal/key/key.go @@ -0,0 +1,55 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package key + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/classifications/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +type key struct { + ids.ClassificationID +} + +var _ helpers.Key = (*key)(nil) + +func (key key) GenerateStoreKeyBytes() []byte { + return module.StoreKeyPrefix.GenerateStoreKey(key.Bytes()) +} +func (key) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, key{}) +} +func (key key) IsPartial() bool { + return len(key.ClassificationID.Bytes()) == 0 +} +func (key key) Equals(compareKey helpers.Key) bool { + if CompareKey, err := keyFromInterface(compareKey); err != nil { + return false + } else { + return key.ClassificationID.Compare(CompareKey.ClassificationID) == 0 + } +} +func keyFromInterface(i interface{}) (key, error) { + switch value := i.(type) { + case key: + return value, nil + default: + return key{}, errorConstants.MetaDataError + } +} + +func NewKey(classificationID ids.ClassificationID) helpers.Key { + return key{ + ClassificationID: classificationID, + } +} + +func Prototype() helpers.Key { + return key{} +} diff --git a/modules/classifications/internal/key/key_test.go b/modules/classifications/internal/key/key_test.go new file mode 100644 index 000000000..5039bd73f --- /dev/null +++ b/modules/classifications/internal/key/key_test.go @@ -0,0 +1,190 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package key + +import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/classifications/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseHelpers "github.com/AssetMantle/modules/utilities/test/schema/helpers/base" +) + +func createTestInput() ids.ClassificationID { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + return classificationID +} + +func TestNewKey(t *testing.T) { + type args struct { + classificationID ids.ClassificationID + } + tests := []struct { + name string + args args + want helpers.Key + }{ + {"+ve", args{createTestInput()}, key{createTestInput()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewKey(tt.args.classificationID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewKey() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Key + }{ + {"+ve", key{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_keyFromInterface(t *testing.T) { + type args struct { + i interface{} + } + tests := []struct { + name string + args args + want key + wantErr bool + }{ + {"+ve", args{NewKey(createTestInput())}, key{createTestInput()}, false}, + {"+ve MetaDataError", args{}, key{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := keyFromInterface(tt.args.i) + if (err != nil) != tt.wantErr { + t.Errorf("keyFromInterface() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("keyFromInterface() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_Equals(t *testing.T) { + type fields struct { + ClassificationID ids.ClassificationID + } + type args struct { + compareKey helpers.Key + } + tests := []struct { + name string + fields fields + args args + want bool + }{ + {"+ve", fields{createTestInput()}, args{key{createTestInput()}}, true}, + {"+ve", fields{createTestInput()}, args{baseHelpers.KeyPrototype()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key := key{ + ClassificationID: tt.fields.ClassificationID, + } + if got := key.Equals(tt.args.compareKey); got != tt.want { + t.Errorf("Equals() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_GenerateStoreKeyBytes(t *testing.T) { + type fields struct { + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{createTestInput()}, module.StoreKeyPrefix.GenerateStoreKey(key{createTestInput()}.Bytes())}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key := key{ + ClassificationID: tt.fields.ClassificationID, + } + if got := key.GenerateStoreKeyBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GenerateStoreKeyBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_IsPartial(t *testing.T) { + type fields struct { + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want bool + }{ + {"+ve", fields{createTestInput()}, false}, + {"-ve", fields{baseIDs.PrototypeClassificationID()}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key := key{ + ClassificationID: tt.fields.ClassificationID, + } + if got := key.IsPartial(); got != tt.want { + t.Errorf("IsPartial() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_RegisterCodec(t *testing.T) { + type fields struct { + ClassificationID ids.ClassificationID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{createTestInput()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ke := key{ + ClassificationID: tt.fields.ClassificationID, + } + ke.RegisterCodec(tt.args.codec) + }) + } +} diff --git a/modules/classifications/internal/key/utilities.go b/modules/classifications/internal/key/utilities.go deleted file mode 100644 index 8c22eb558..000000000 --- a/modules/classifications/internal/key/utilities.go +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - "strings" - - "github.com/persistenceOne/persistenceSDK/schema/helpers" - - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -func readClassificationID(classificationIDString string) ClassificationID { - idList := strings.Split(classificationIDString, constants.IDSeparator) - if len(idList) == 2 { - return ClassificationID{ - ChainID: base.NewID(idList[0]), - HashID: base.NewID(idList[1]), - } - } - - return ClassificationID{ChainID: base.NewID(""), HashID: base.NewID("")} -} -func classificationIDFromInterface(i interface{}) ClassificationID { - switch value := i.(type) { - case ClassificationID: - return value - case types.ID: - return classificationIDFromInterface(readClassificationID(value.String())) - default: - panic(i) - } -} - -func FromID(id types.ID) helpers.Key { - return classificationIDFromInterface(id) -} diff --git a/modules/classifications/internal/mappable/classification.pb.go b/modules/classifications/internal/mappable/classification.pb.go deleted file mode 100644 index 0f057ee5d..000000000 --- a/modules/classifications/internal/mappable/classification.pb.go +++ /dev/null @@ -1,418 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/classifications/internal/mappable/classification.proto - -package mappable - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base1 "github.com/persistenceOne/persistenceSDK/schema/traits/base" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Classification struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - HasImmutables base1.HasImmutables `protobuf:"bytes,2,opt,name=has_immutables,json=hasImmutables,proto3" json:"has_immutables"` - HasMutables base1.HasMutables `protobuf:"bytes,3,opt,name=has_mutables,json=hasMutables,proto3" json:"has_mutables"` -} - -func (m *Classification) Reset() { *m = Classification{} } -func (m *Classification) String() string { return proto.CompactTextString(m) } -func (*Classification) ProtoMessage() {} -func (*Classification) Descriptor() ([]byte, []int) { - return fileDescriptor_4e506b3bc47e585e, []int{0} -} -func (m *Classification) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Classification) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Classification.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Classification) XXX_Merge(src proto.Message) { - xxx_messageInfo_Classification.Merge(m, src) -} -func (m *Classification) XXX_Size() int { - return m.Size() -} -func (m *Classification) XXX_DiscardUnknown() { - xxx_messageInfo_Classification.DiscardUnknown(m) -} - -var xxx_messageInfo_Classification proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Classification)(nil), "persistence_sdk.modules.classifications.internal.mappable.Classification") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/classifications/internal/mappable/classification.proto", fileDescriptor_4e506b3bc47e585e) -} - -var fileDescriptor_4e506b3bc47e585e = []byte{ - // 343 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0xd2, 0x3f, 0x4b, 0xfb, 0x40, - 0x18, 0x07, 0xf0, 0xa4, 0x2d, 0xbf, 0x21, 0xfd, 0xd9, 0x21, 0x38, 0x94, 0x0e, 0x57, 0x11, 0x04, - 0x71, 0xb8, 0xc3, 0x3f, 0x08, 0x8a, 0x53, 0xed, 0x60, 0x91, 0x2a, 0xd4, 0x45, 0x1c, 0x2c, 0x97, - 0xe4, 0x6c, 0x0e, 0x73, 0xb9, 0x90, 0xe7, 0x3a, 0xf8, 0x0e, 0x9c, 0xc4, 0x97, 0xe0, 0xcb, 0xe9, - 0xd8, 0xd1, 0x49, 0xa4, 0x79, 0x23, 0x92, 0x4b, 0x5a, 0x92, 0x40, 0x21, 0x5b, 0x02, 0xcf, 0xf7, - 0x93, 0x3c, 0xdf, 0x3b, 0xeb, 0x2e, 0x62, 0x31, 0x70, 0x50, 0x2c, 0x74, 0xd9, 0x14, 0xbc, 0x57, - 0x22, 0xa4, 0x37, 0x0f, 0x18, 0x10, 0x37, 0xa0, 0x00, 0xfc, 0x85, 0xbb, 0x54, 0x71, 0x19, 0x02, - 0xe1, 0xa1, 0x62, 0x71, 0x48, 0x03, 0x22, 0x68, 0x14, 0x51, 0x27, 0x60, 0x95, 0x09, 0x1c, 0xc5, - 0x52, 0x49, 0xfb, 0xa2, 0xe2, 0xe1, 0xdc, 0xc3, 0x15, 0x0f, 0xaf, 0x3d, 0xbc, 0xf6, 0x7a, 0xbb, - 0x33, 0x39, 0x93, 0x5a, 0x21, 0xe9, 0x53, 0x06, 0xf6, 0xce, 0xab, 0x3f, 0x08, 0xae, 0xcf, 0x04, - 0x25, 0x2a, 0xa6, 0x5c, 0x01, 0x71, 0x28, 0x30, 0xe2, 0x53, 0x18, 0x09, 0x31, 0x57, 0x29, 0x03, - 0x79, 0xee, 0xac, 0x5e, 0x6e, 0x5c, 0x4e, 0x1d, 0x6d, 0x4b, 0xbd, 0x45, 0x2c, 0x0f, 0x71, 0x2f, - 0x9b, 0xdd, 0xff, 0x68, 0x58, 0x9d, 0xeb, 0xd2, 0x56, 0xf6, 0x95, 0xd5, 0xe4, 0x53, 0xaf, 0x6b, - 0xee, 0x99, 0x87, 0xed, 0x93, 0x03, 0x5c, 0xed, 0x22, 0xc3, 0xb0, 0xc6, 0x70, 0x8a, 0xe1, 0xd1, - 0x70, 0xd0, 0x5a, 0xfc, 0xf4, 0x8d, 0x49, 0x83, 0x0f, 0xed, 0x67, 0xab, 0xe3, 0x53, 0x98, 0xf2, - 0xcd, 0x2a, 0xdd, 0x86, 0x86, 0x8e, 0xb7, 0x42, 0x7a, 0x97, 0x4c, 0xba, 0x29, 0x76, 0x90, 0xa3, - 0x3b, 0xa5, 0x62, 0xec, 0x47, 0xeb, 0x7f, 0xea, 0x6f, 0xf4, 0xa6, 0xd6, 0x49, 0x4d, 0x7d, 0x5c, - 0xb6, 0xdb, 0x85, 0xf2, 0x2e, 0x5b, 0xef, 0x5f, 0x7d, 0x63, 0x10, 0x2c, 0x56, 0xc8, 0x5c, 0xae, - 0x90, 0xf9, 0xbb, 0x42, 0xe6, 0x67, 0x82, 0x8c, 0x65, 0x82, 0x8c, 0xef, 0x04, 0x19, 0x4f, 0x93, - 0x19, 0x57, 0xfe, 0xdc, 0xc1, 0xae, 0x14, 0xa4, 0xf0, 0xb5, 0xfb, 0x90, 0x15, 0x5f, 0x1f, 0x86, - 0xb7, 0xf5, 0xaf, 0x9f, 0xf3, 0x4f, 0x9f, 0xc2, 0xe9, 0x5f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x89, - 0xa8, 0xda, 0x41, 0xc2, 0x02, 0x00, 0x00, -} - -func (m *Classification) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Classification) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Classification) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.HasMutables.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClassification(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.HasImmutables.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClassification(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClassification(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintClassification(dAtA []byte, offset int, v uint64) int { - offset -= sovClassification(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Classification) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovClassification(uint64(l)) - l = m.HasImmutables.Size() - n += 1 + l + sovClassification(uint64(l)) - l = m.HasMutables.Size() - n += 1 + l + sovClassification(uint64(l)) - return n -} - -func sovClassification(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozClassification(x uint64) (n int) { - return sovClassification(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Classification) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClassification - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Classification: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Classification: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClassification - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClassification - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClassification - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HasImmutables", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClassification - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClassification - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClassification - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HasImmutables.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HasMutables", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClassification - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClassification - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClassification - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HasMutables.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClassification(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClassification - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipClassification(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowClassification - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowClassification - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowClassification - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthClassification - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupClassification - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthClassification - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthClassification = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowClassification = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupClassification = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/classifications/internal/mappable/mappable.go b/modules/classifications/internal/mappable/mappable.go new file mode 100644 index 000000000..3af83aabc --- /dev/null +++ b/modules/classifications/internal/mappable/mappable.go @@ -0,0 +1,36 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mappable + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/helpers" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +type mappable struct { + documents.Classification +} + +var _ helpers.Mappable = (*mappable)(nil) + +func (mappable mappable) GetKey() helpers.Key { + return key.NewKey(mappable.GetClassificationID()) +} +func (mappable) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, mappable{}) +} + +func NewMappable(classification documents.Classification) helpers.Mappable { + return mappable{ + Classification: classification, + } +} + +func Prototype() helpers.Mappable { + return mappable{} +} diff --git a/modules/classifications/internal/mappable/mappable_test.go b/modules/classifications/internal/mappable/mappable_test.go new file mode 100644 index 000000000..ce9363de1 --- /dev/null +++ b/modules/classifications/internal/mappable/mappable_test.go @@ -0,0 +1,125 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mappable + +import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/classifications/internal/key" + baseData "github.com/AssetMantle/modules/schema/data/base" + documentsSchema "github.com/AssetMantle/modules/schema/documents" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/qualified" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +func createTestInput() (ids.ClassificationID, qualified.Immutables, qualified.Mutables, mappable) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + testMappable := mappable{Classification: baseDocuments.NewDocument(classificationID, immutables, mutables)} + return classificationID, immutables, mutables, testMappable +} + +func TestNewMappable(t *testing.T) { + classificationID, immutables, mutables, testMappable := createTestInput() + type args struct { + Asset documentsSchema.Document + } + tests := []struct { + name string + args args + want documentsSchema.Document + }{ + {"+ve", args{baseDocuments.NewDocument(classificationID, immutables, mutables)}, testMappable}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewMappable(tt.args.Asset); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewDocument() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Mappable + }{ + {"+ve", mappable{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_mappable_RegisterCodec(t *testing.T) { + _, _, _, testMappable := createTestInput() + type fields struct { + Document mappable + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testMappable}, args{codec: codec.New()}}, + {"+ve nil", fields{mappable{nil}}, args{codec: codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + as := mappable{ + Classification: tt.fields.Document, + } + as.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_mappable_GetKey(t *testing.T) { + _, _, _, testMappable := createTestInput() + type fields struct { + Document mappable + } + tests := []struct { + name string + fields fields + want helpers.Key + wantPanic bool + }{ + {"+ve", fields{testMappable}, key.NewKey(baseIDs.NewClassificationID(testMappable.GetImmutables(), testMappable.GetMutables())), false}, + {"panic case nil", fields{mappable{nil}}, nil, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + asset := mappable{ + Classification: tt.fields.Document, + } + if tt.wantPanic { + require.Panics(t, func() { + asset.GetKey() + }) + } else if got := asset.GetKey(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetKey() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/classifications/internal/mappable/prototype.go b/modules/classifications/internal/mappable/prototype.go deleted file mode 100644 index 33b2c2c27..000000000 --- a/modules/classifications/internal/mappable/prototype.go +++ /dev/null @@ -1,12 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import "github.com/persistenceOne/persistenceSDK/schema/helpers" - -func Prototype() helpers.Mappable { - return &Classification{} -} diff --git a/modules/classifications/internal/mapper/prototype.go b/modules/classifications/internal/mapper/prototype.go new file mode 100644 index 000000000..9889b2af0 --- /dev/null +++ b/modules/classifications/internal/mapper/prototype.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mapper + +import ( + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/modules/classifications/internal/mappable" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Mapper { + return baseHelpers.NewMapper(key.Prototype, mappable.Prototype) +} diff --git a/modules/classifications/internal/module/constants.go b/modules/classifications/internal/module/constants.go new file mode 100644 index 000000000..32843c13a --- /dev/null +++ b/modules/classifications/internal/module/constants.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package module + +import ( + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +const Name = "classifications" + +var StoreKeyPrefix = constants.ClassificationsStoreKeyPrefix + +// MaxPropertyCount TODO convert it to module param +const MaxPropertyCount = 22 diff --git a/modules/metas/module/parameters/dummy/constants.go b/modules/classifications/internal/parameters/dummy/constants.go similarity index 100% rename from modules/metas/module/parameters/dummy/constants.go rename to modules/classifications/internal/parameters/dummy/constants.go diff --git a/modules/classifications/internal/parameters/dummy/parameter.go b/modules/classifications/internal/parameters/dummy/parameter.go index e78fdc8d0..5ffc0eaf5 100644 --- a/modules/classifications/internal/parameters/dummy/parameter.go +++ b/modules/classifications/internal/parameters/dummy/parameter.go @@ -1,59 +1,10 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "encoding/json" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" ) -var _ types.Parameter = (*DummyParameter)(nil) - -func (dummyParameter DummyParameter) String() string { - bytes, Error := json.Marshal(dummyParameter) - if Error != nil { - return Error.Error() - } - return string(bytes) -} - -func (dummyParameter DummyParameter) Equal(compareParameter types.Parameter) bool { - if compareParameter == nil { - return false - } - return dummyParameter.Data.Compare(compareParameter.GetData()) == 0 -} - -func (dummyParameter DummyParameter) Validate() error { - return validator(dummyParameter) -} - -func (dummyParameter DummyParameter) GetID() types.ID { - return &dummyParameter.ID -} - -func (dummyParameter DummyParameter) GetData() types.Data { - return &dummyParameter.Data -} - -func (dummyParameter DummyParameter) GetValidator() func(interface{}) error { - return validator -} - -func (dummyParameter DummyParameter) Mutate(data types.Data) types.Parameter { - decData, _ := data.AsDec() - dummyParameter.Data = *base.NewDummyDecData(decData) - return &dummyParameter -} - -func NewParameter(id types.ID, data types.Data) *DummyParameter { - decData, _ := data.AsDec() - return &DummyParameter{ - ID: *base.NewID(id.String()), - Data: *base.NewDummyDecData(decData), - } -} +var Parameter = baseTypes.NewParameter(ID, DefaultData, validator) diff --git a/modules/classifications/internal/parameters/dummy/parameter.pb.go b/modules/classifications/internal/parameters/dummy/parameter.pb.go deleted file mode 100644 index e7c5f7e25..000000000 --- a/modules/classifications/internal/parameters/dummy/parameter.pb.go +++ /dev/null @@ -1,368 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/classifications/internal/parameters/dummy/parameter.proto - -package dummy - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type DummyParameter struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - Data base.DecData `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` -} - -func (m *DummyParameter) Reset() { *m = DummyParameter{} } -func (*DummyParameter) ProtoMessage() {} -func (*DummyParameter) Descriptor() ([]byte, []int) { - return fileDescriptor_9fa6cc99a8174b09, []int{0} -} -func (m *DummyParameter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DummyParameter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DummyParameter.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DummyParameter) XXX_Merge(src proto.Message) { - xxx_messageInfo_DummyParameter.Merge(m, src) -} -func (m *DummyParameter) XXX_Size() int { - return m.Size() -} -func (m *DummyParameter) XXX_DiscardUnknown() { - xxx_messageInfo_DummyParameter.DiscardUnknown(m) -} - -var xxx_messageInfo_DummyParameter proto.InternalMessageInfo - -func init() { - proto.RegisterType((*DummyParameter)(nil), "persistence_sdk.modules.classifications.internal.parameters.dummy.DummyParameter") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/classifications/internal/parameters/dummy/parameter.proto", fileDescriptor_9fa6cc99a8174b09) -} - -var fileDescriptor_9fa6cc99a8174b09 = []byte{ - // 311 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0xd1, 0x3f, 0x4b, 0x3b, 0x31, - 0x18, 0x07, 0xf0, 0xa4, 0xbf, 0xf2, 0x43, 0x4e, 0x70, 0x28, 0x0e, 0xa5, 0x43, 0x2a, 0x82, 0x20, - 0x1d, 0x12, 0xd0, 0x4d, 0x5c, 0x2c, 0x59, 0xc4, 0xc1, 0x7f, 0x5b, 0x97, 0x92, 0x26, 0x8f, 0x6d, - 0xb0, 0xb9, 0x1c, 0x97, 0xdc, 0xd0, 0x77, 0xe0, 0xe8, 0xe8, 0x24, 0x7d, 0x39, 0x1d, 0x3b, 0x3a, - 0x89, 0xdc, 0xbd, 0x11, 0xb9, 0xdc, 0x95, 0x96, 0x5b, 0xd4, 0x2d, 0x09, 0xcf, 0xf7, 0x93, 0xe7, - 0x49, 0xa2, 0xfb, 0x04, 0x52, 0xa7, 0x9d, 0x87, 0x58, 0xc2, 0xd8, 0xa9, 0x67, 0x66, 0xac, 0xca, - 0xe6, 0xe0, 0x98, 0x9c, 0x0b, 0xe7, 0xf4, 0x93, 0x96, 0xc2, 0x6b, 0x1b, 0x3b, 0xa6, 0x63, 0x0f, - 0x69, 0x2c, 0xe6, 0x2c, 0x11, 0xa9, 0x30, 0xe0, 0x21, 0x75, 0x4c, 0x65, 0xc6, 0x2c, 0xb6, 0x07, - 0x34, 0x49, 0xad, 0xb7, 0x9d, 0xab, 0x06, 0x49, 0x6b, 0x92, 0x36, 0x48, 0xba, 0x21, 0xe9, 0x96, - 0xa4, 0x81, 0xec, 0x1d, 0x4e, 0xed, 0xd4, 0x06, 0x8d, 0x95, 0xab, 0x0a, 0xee, 0x0d, 0x9a, 0xbd, - 0x3a, 0x39, 0x03, 0x23, 0x98, 0x5f, 0x24, 0xe0, 0xd8, 0x44, 0x38, 0x60, 0x5a, 0xd5, 0xb5, 0xec, - 0xe7, 0x5a, 0x05, 0x92, 0x0b, 0x2f, 0xaa, 0xc0, 0xf1, 0x3b, 0x8e, 0x0e, 0x78, 0x79, 0xf9, 0xdd, - 0xa6, 0x99, 0xce, 0x65, 0xf4, 0x4f, 0x8f, 0x55, 0x17, 0x1f, 0xe1, 0xd3, 0xfd, 0xb3, 0x13, 0xda, - 0x1c, 0xab, 0x12, 0x69, 0x10, 0x69, 0x29, 0xd2, 0x6b, 0x3e, 0x6c, 0xaf, 0x3e, 0xfb, 0xe8, 0xa1, - 0xa5, 0x79, 0x87, 0x47, 0x6d, 0x25, 0xbc, 0xe8, 0xb6, 0x42, 0x7c, 0xf0, 0x8b, 0x38, 0xaf, 0x1a, - 0xaa, 0x8d, 0x90, 0xbe, 0xd8, 0x7b, 0x59, 0xf6, 0xd1, 0xdb, 0xb2, 0x8f, 0x86, 0x7e, 0x95, 0x13, - 0xbc, 0xce, 0x09, 0xfe, 0xca, 0x09, 0x7e, 0x2d, 0x08, 0x5a, 0x17, 0x04, 0x7d, 0x14, 0x04, 0x8d, - 0x46, 0x53, 0xed, 0x67, 0xd9, 0x84, 0x4a, 0x6b, 0x76, 0xc7, 0xbe, 0x8d, 0x61, 0x77, 0xfb, 0xc8, - 0x6f, 0xfe, 0xfe, 0xb9, 0x93, 0xff, 0xe1, 0x75, 0xce, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0xe0, - 0xa3, 0x2c, 0x15, 0x28, 0x02, 0x00, 0x00, -} - -func (m *DummyParameter) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DummyParameter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DummyParameter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Data.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintParameter(dAtA []byte, offset int, v uint64) int { - offset -= sovParameter(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *DummyParameter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovParameter(uint64(l)) - l = m.Data.Size() - n += 1 + l + sovParameter(uint64(l)) - return n -} - -func sovParameter(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParameter(x uint64) (n int) { - return sovParameter(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *DummyParameter) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DummyParameter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DummyParameter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParameter(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParameter - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParameter(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParameter - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParameter - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParameter - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParameter = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParameter = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParameter = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/classifications/internal/parameters/dummy/prototype.go b/modules/classifications/internal/parameters/dummy/prototype.go deleted file mode 100644 index b390a673e..000000000 --- a/modules/classifications/internal/parameters/dummy/prototype.go +++ /dev/null @@ -1,3 +0,0 @@ -package dummy - -var Parameter = NewParameter(ID, DefaultData) diff --git a/modules/classifications/internal/parameters/dummy/validator.go b/modules/classifications/internal/parameters/dummy/validator.go index cc0d80a52..2bb100018 100644 --- a/modules/classifications/internal/parameters/dummy/validator.go +++ b/modules/classifications/internal/parameters/dummy/validator.go @@ -1,32 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/parameters" ) func validator(i interface{}) error { switch value := i.(type) { - case DummyParameter: - data, Error := value.GetData().AsDec() - if Error != nil || value.GetID().Compare(ID) != 0 || data.IsNegative() { - return errors.InvalidParameter + case parameters.Parameter: + if value.GetID().Compare(ID) != 0 || value.GetData().(data.DecData).Get().IsNegative() { + return constants.InvalidParameter } return nil - case types.Data: - data, Error := value.AsDec() - if Error != nil || data.IsNegative() { - return errors.InvalidParameter + case data.DecData: + if value.Get().IsNegative() { + return constants.InvalidParameter } return nil default: - return errors.IncorrectFormat + return constants.IncorrectFormat } } diff --git a/modules/classifications/internal/parameters/dummy/validator_test.go b/modules/classifications/internal/parameters/dummy/validator_test.go new file mode 100644 index 000000000..6915a0b78 --- /dev/null +++ b/modules/classifications/internal/parameters/dummy/validator_test.go @@ -0,0 +1,21 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package dummy + +import ( + "testing" + + "github.com/stretchr/testify/require" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/errors/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" +) + +func Test_Validator(t *testing.T) { + require.Equal(t, constants.IncorrectFormat, validator(baseIDs.NewStringID(""))) + require.Equal(t, nil, validator(Parameter)) + require.Equal(t, constants.InvalidParameter, validator(baseTypes.NewParameter(baseIDs.NewStringID(""), baseData.NewStringData(""), validator))) +} diff --git a/modules/classifications/internal/parameters/prototype.go b/modules/classifications/internal/parameters/prototype.go new file mode 100644 index 000000000..7012ceda7 --- /dev/null +++ b/modules/classifications/internal/parameters/prototype.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package parameters + +import ( + "github.com/AssetMantle/modules/modules/classifications/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Parameters { + return baseHelpers.NewParameters(dummy.Parameter) +} diff --git a/modules/classifications/internal/queries/classification/grpc_query.go b/modules/classifications/internal/queries/classification/grpc_query.go deleted file mode 100644 index c07bcb513..000000000 --- a/modules/classifications/internal/queries/classification/grpc_query.go +++ /dev/null @@ -1,29 +0,0 @@ -package classification - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/key" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type queryServer struct { - queryKeeper -} - -var _ QueryServer = queryServer{} - -func (queryServer queryServer) Enquire(ctx context.Context, queryRequest *QueryRequest) (*QueryResponse, error) { - cntx := sdkTypes.UnwrapSDKContext(ctx) - - keyr := key.FromID(base.NewID(queryRequest.ClassificationID.String())) - - collection := queryServer.queryKeeper.mapper.NewCollection(cntx) - response := newQueryResponse(collection.Fetch(keyr), nil) - return &response, response.GetError() - -} - -func NewQueryServerImpl(keeper queryKeeper) QueryServer { - return &queryServer{keeper} -} diff --git a/modules/classifications/internal/queries/classification/keeper.go b/modules/classifications/internal/queries/classification/keeper.go new file mode 100644 index 000000000..5481c1868 --- /dev/null +++ b/modules/classifications/internal/queries/classification/keeper.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package classification + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/schema/helpers" +) + +type queryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.QueryKeeper = (*queryKeeper)(nil) + +func (queryKeeper queryKeeper) Enquire(context sdkTypes.Context, queryRequest helpers.QueryRequest) helpers.QueryResponse { + return newQueryResponse(queryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(queryRequestFromInterface(queryRequest).ClassificationID)), nil) +} + +func (queryKeeper queryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + queryKeeper.mapper = mapper + return queryKeeper +} + +func keeperPrototype() helpers.QueryKeeper { + return queryKeeper{} +} diff --git a/modules/classifications/internal/queries/classification/keeper_test.go b/modules/classifications/internal/queries/classification/keeper_test.go new file mode 100644 index 000000000..75e8d926f --- /dev/null +++ b/modules/classifications/internal/queries/classification/keeper_test.go @@ -0,0 +1,81 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package classification + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/modules/classifications/internal/mappable" + "github.com/AssetMantle/modules/modules/classifications/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +func CreateTestInput2(t *testing.T) (sdkTypes.Context, helpers.Keeper) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + testQueryKeeper := keeperPrototype().Initialize(mapper, Parameters, []interface{}{}) + + return context, testQueryKeeper +} + +func Test_Query_Keeper_Classification(t *testing.T) { + context, keepers := CreateTestInput2(t) + immutableProperties, err := utilities.ReadMetaPropertyList("defaultImmutable1:S|defaultImmutable1") + require.Equal(t, nil, err) + mutableProperties, Error2 := utilities.ReadMetaPropertyList("burn:S|100") + require.Equal(t, nil, Error2) + + classificationID := baseIDs.NewClassificationID(baseQualified.NewImmutables(immutableProperties), baseQualified.NewMutables(mutableProperties)) + keepers.(queryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(baseDocuments.NewClassification(baseQualified.NewImmutables(immutableProperties), baseQualified.NewMutables(mutableProperties)))) + + testQueryRequest := newQueryRequest(classificationID) + require.Equal(t, queryResponse{Success: true, Error: nil, List: keepers.(queryKeeper).mapper.NewCollection(context).Fetch(key.NewKey(classificationID)).GetList()}, keepers.(queryKeeper).Enquire(context, testQueryRequest)) + +} diff --git a/modules/classifications/internal/queries/classification/query.go b/modules/classifications/internal/queries/classification/query.go index 14261efd7..05cfa7cf5 100644 --- a/modules/classifications/internal/queries/classification/query.go +++ b/modules/classifications/internal/queries/classification/query.go @@ -1,25 +1,24 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package classification import ( - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers/base" + "github.com/AssetMantle/modules/modules/classifications/internal/module" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" ) -var Query = base.NewQuery( +var Query = baseHelpers.NewQuery( "classifications", "", "", module.Name, + requestPrototype, responsePrototype, keeperPrototype, - flags.ClassificationID, + constants.ClassificationID, ) diff --git a/modules/classifications/internal/queries/classification/query.pb.go b/modules/classifications/internal/queries/classification/query.pb.go deleted file mode 100644 index 054d12b84..000000000 --- a/modules/classifications/internal/queries/classification/query.pb.go +++ /dev/null @@ -1,674 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/classifications/internal/queries/classification/query.proto - -package classification - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - github_com_persistenceOne_persistenceSDK_schema_helpers "github.com/persistenceOne/persistenceSDK/schema/helpers" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type QueryRequest struct { - ClassificationID base.ID `protobuf:"bytes,1,opt,name=classification_i_d,json=classificationID,proto3" json:"classification_i_d" valid:"required~required ClassificationID missing"` -} - -func (m *QueryRequest) Reset() { *m = QueryRequest{} } -func (m *QueryRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRequest) ProtoMessage() {} -func (*QueryRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_ddac3d6de870e613, []int{0} -} -func (m *QueryRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRequest.Merge(m, src) -} -func (m *QueryRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRequest proto.InternalMessageInfo - -type QueryResponse struct { - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` - List []github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable `protobuf:"bytes,3,rep,name=list,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable" json:"list"` -} - -func (m *QueryResponse) Reset() { *m = QueryResponse{} } -func (m *QueryResponse) String() string { return proto.CompactTextString(m) } -func (*QueryResponse) ProtoMessage() {} -func (*QueryResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ddac3d6de870e613, []int{1} -} -func (m *QueryResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryResponse.Merge(m, src) -} -func (m *QueryResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryRequest)(nil), "persistence_sdk.modules.classifications.internal.queries.classification.QueryRequest") - proto.RegisterType((*QueryResponse)(nil), "persistence_sdk.modules.classifications.internal.queries.classification.QueryResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/classifications/internal/queries/classification/query.proto", fileDescriptor_ddac3d6de870e613) -} - -var fileDescriptor_ddac3d6de870e613 = []byte{ - // 475 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x93, 0xc1, 0x8b, 0xd3, 0x40, - 0x14, 0xc6, 0x33, 0xbb, 0xae, 0xbb, 0x1b, 0x15, 0x24, 0xec, 0xa1, 0x14, 0x49, 0x42, 0x40, 0x28, - 0x8a, 0x33, 0xd0, 0xbd, 0xf5, 0x24, 0xb5, 0xa2, 0x8b, 0x88, 0x98, 0x45, 0x0f, 0x22, 0xd4, 0x69, - 0xf2, 0x4c, 0x07, 0xd3, 0x99, 0x74, 0xde, 0x44, 0x58, 0x0f, 0x1e, 0x3c, 0x79, 0x53, 0xf0, 0x1f, - 0xd8, 0x9b, 0xe0, 0x5f, 0xb2, 0xc7, 0x05, 0x2f, 0xe2, 0xa1, 0x48, 0xeb, 0xc1, 0x8b, 0x17, 0x2f, - 0x5e, 0x25, 0x49, 0x8b, 0x6d, 0xf6, 0x22, 0xd2, 0xdb, 0xbc, 0xbc, 0xc7, 0x2f, 0xdf, 0xf7, 0xcd, - 0x3c, 0xfb, 0x30, 0x03, 0x8d, 0x02, 0x0d, 0xc8, 0x08, 0xfa, 0x18, 0xbf, 0x60, 0x23, 0x15, 0xe7, - 0x29, 0x20, 0x8b, 0x52, 0x8e, 0x28, 0x9e, 0x8b, 0x88, 0x1b, 0xa1, 0x24, 0x32, 0x21, 0x0d, 0x68, - 0xc9, 0x53, 0x36, 0xce, 0x41, 0x8b, 0x33, 0x03, 0xe5, 0xe7, 0x23, 0x9a, 0x69, 0x65, 0x94, 0x73, - 0xa7, 0x06, 0xa5, 0x73, 0x28, 0xad, 0x41, 0xe9, 0x02, 0x4a, 0xe7, 0xd0, 0xda, 0x40, 0x73, 0x2f, - 0x51, 0x89, 0x2a, 0x99, 0xac, 0x38, 0x55, 0xf8, 0xe6, 0x95, 0x44, 0xa9, 0x24, 0x05, 0xc6, 0x33, - 0xc1, 0xb8, 0x94, 0xca, 0xcc, 0x69, 0x55, 0xf7, 0x5a, 0xdd, 0x11, 0x46, 0x43, 0x18, 0x71, 0x66, - 0x8e, 0x32, 0x40, 0x36, 0xe0, 0x08, 0x4c, 0xc4, 0xd5, 0x6c, 0xf0, 0x89, 0xd8, 0x17, 0x1f, 0x16, - 0xc2, 0x43, 0x18, 0xe7, 0x80, 0xc6, 0x79, 0x47, 0x6c, 0x67, 0x55, 0x43, 0x5f, 0xf4, 0xe3, 0x06, - 0xf1, 0x49, 0xeb, 0x42, 0xfb, 0x2a, 0xad, 0xfb, 0xaa, 0xd0, 0xb4, 0x44, 0xd3, 0x02, 0x4d, 0x0f, - 0x7a, 0xdd, 0xce, 0xc9, 0xc4, 0xb3, 0x7e, 0x4d, 0xbc, 0xf6, 0x4b, 0x9e, 0x8a, 0xb8, 0x13, 0x68, - 0x18, 0xe7, 0x42, 0x43, 0xfc, 0x7a, 0x71, 0xf0, 0x6f, 0xad, 0xfc, 0xe1, 0xa0, 0xe7, 0x8f, 0x04, - 0xa2, 0x90, 0x49, 0x10, 0x5e, 0x8e, 0x6a, 0xad, 0xce, 0xce, 0xdb, 0x63, 0xcf, 0xfa, 0x71, 0xec, - 0x59, 0xc1, 0x47, 0x62, 0x5f, 0x9a, 0x8b, 0xc5, 0x4c, 0x49, 0x04, 0xa7, 0x61, 0x6f, 0x63, 0x1e, - 0x45, 0x80, 0x58, 0x2a, 0xdc, 0x09, 0x17, 0xa5, 0xb3, 0x67, 0x6f, 0x81, 0xd6, 0x4a, 0x37, 0x36, - 0x7c, 0xd2, 0xda, 0x0d, 0xab, 0xc2, 0x79, 0x6a, 0x9f, 0x4b, 0x05, 0x9a, 0xc6, 0xa6, 0xbf, 0xd9, - 0xda, 0xed, 0xde, 0x2d, 0x74, 0x7e, 0x9d, 0x78, 0x37, 0x13, 0x61, 0x86, 0xf9, 0x80, 0x46, 0x6a, - 0xc4, 0x96, 0x0c, 0x3e, 0x90, 0xb0, 0x5c, 0x1e, 0xf6, 0xee, 0x2d, 0x92, 0x1c, 0x42, 0x5a, 0x34, - 0xe8, 0x7d, 0x9e, 0x65, 0x7c, 0x90, 0x42, 0x58, 0x52, 0xff, 0x2a, 0x6d, 0xff, 0x26, 0xf6, 0x56, - 0xa9, 0xd4, 0xf9, 0x49, 0xec, 0xed, 0xdb, 0xb2, 0xb4, 0xed, 0x3c, 0xa2, 0x6b, 0x7a, 0x16, 0x74, - 0xf9, 0xca, 0x9a, 0x8f, 0xd7, 0x8d, 0xad, 0xc2, 0x0d, 0xf6, 0xdf, 0x7c, 0xfe, 0xfe, 0x61, 0xe3, - 0x86, 0x73, 0x7d, 0x39, 0x85, 0x33, 0x6b, 0xb1, 0x5a, 0x77, 0x5f, 0x9d, 0x4c, 0x5d, 0x72, 0x3a, - 0x75, 0xc9, 0xb7, 0xa9, 0x4b, 0xde, 0xcf, 0x5c, 0xeb, 0x74, 0xe6, 0x5a, 0x5f, 0x66, 0xae, 0xf5, - 0xe4, 0xd9, 0x3f, 0xa7, 0xfc, 0x9f, 0x1b, 0x38, 0x38, 0x5f, 0xbe, 0xe9, 0xfd, 0x3f, 0x01, 0x00, - 0x00, 0xff, 0xff, 0x04, 0xe0, 0x8e, 0x24, 0xd3, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) { - out := new(QueryResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.classifications.internal.queries.classification.Query/Enquire", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - Enquire(context.Context, *QueryRequest) (*QueryResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Enquire(ctx context.Context, req *QueryRequest) (*QueryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Enquire not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Enquire_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Enquire(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.classifications.internal.queries.classification.Query/Enquire", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Enquire(ctx, req.(*QueryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.classifications.internal.queries.classification.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Enquire", - Handler: _Query_Enquire_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/classifications/internal/queries/classification/query.proto", -} - -func (m *QueryRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.ClassificationID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.List) > 0 { - for iNdEx := len(m.List) - 1; iNdEx >= 0; iNdEx-- { - { - size := m.List[iNdEx].Size() - i -= size - if _, err := m.List[iNdEx].MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Error) > 0 { - i -= len(m.Error) - copy(dAtA[i:], m.Error) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Error))) - i-- - dAtA[i] = 0x12 - } - if m.Success { - i-- - if m.Success { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ClassificationID.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Success { - n += 2 - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.List) > 0 { - for _, e := range m.List { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Success = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field List", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var v github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable - m.List = append(m.List, v) - if err := m.List[len(m.List)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/classifications/internal/queries/classification/query.pb.gw.go b/modules/classifications/internal/queries/classification/query.pb.gw.go deleted file mode 100644 index 642d5b56d..000000000 --- a/modules/classifications/internal/queries/classification/query.pb.gw.go +++ /dev/null @@ -1,166 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: persistence_sdk/modules/classifications/internal/queries/classification/query.proto - -/* -Package classification is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package classification - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage - -var ( - filter_Query_Enquire_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Enquire(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Enquire(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features (such as grpc.SendHeader, etc) to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Enquire_0(rctx, inboundMarshaler, server, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Enquire_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Enquire_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"persistence", "classifications", "classification"}, "", runtime.AssumeColonVerbOpt(true))) -) - -var ( - forward_Query_Enquire_0 = runtime.ForwardResponseMessage -) diff --git a/modules/classifications/internal/queries/classification/request.go b/modules/classifications/internal/queries/classification/request.go index a4746f858..9b48b7a33 100644 --- a/modules/classifications/internal/queries/classification/request.go +++ b/modules/classifications/internal/queries/classification/request.go @@ -1,79 +1,74 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package classification import ( "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/cosmos/cosmos-sdk/client/context" + + "github.com/AssetMantle/modules/modules/classifications/internal/common" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" ) -var _ helpers.QueryRequest = (*QueryRequest)(nil) +type queryRequest struct { + ids.ClassificationID `json:"classificationID" valid:"required~required field classificationID missing"` +} + +var _ helpers.QueryRequest = (*queryRequest)(nil) -// QueryRequest godoc -// @Summary Query classification using classification id -// @Descrption Able to query the asset +// Validate godoc +// @Summary Search for an identity by identity ID +// @Description Able to query the asset // @Accept json // @Produce json // @Tags Classifications -// @Param classificationID path string true "classification ID" -// @Success 200 {object} queryResponse "Sucessful query response" -// @Failure default {object} queryResponse "An unexpected error response." +// @Param classificationID path string true "Unique identifier of an asset classification." +// @Success 200 {object} queryResponse "Message for a successful search response." +// @Failure default {object} queryResponse "Message for an unexpected error response." // @Router /classifications/classifications/{classificationID} [get] -func (queryRequest QueryRequest) Validate() error { - _, Error := govalidator.ValidateStruct(queryRequest) - return Error -} -func (queryRequest QueryRequest) FromCLI(cliCommand helpers.CLICommand, _ client.Context) helpers.QueryRequest { - return newQueryRequest(base.NewID(cliCommand.ReadString(flags.ClassificationID))) +func (queryRequest queryRequest) Validate() error { + _, err := govalidator.ValidateStruct(queryRequest) + return err } - -func (queryRequest QueryRequest) FromMap(vars map[string]string) helpers.QueryRequest { - return newQueryRequest(base.NewID(vars[Query.GetName()])) -} -func (queryRequest QueryRequest) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryRequest) +func (queryRequest) FromCLI(cliCommand helpers.CLICommand, _ context.CLIContext) (helpers.QueryRequest, error) { + if classificationID, err := baseIDs.ReadClassificationID(cliCommand.ReadString(constants.ClassificationID)); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(classificationID), nil + } } - -func (queryRequest QueryRequest) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryRequest, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest) FromMap(vars map[string]string) (helpers.QueryRequest, error) { + if classificationID, err := baseIDs.ReadClassificationID(vars[Query.GetName()]); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(classificationID), nil } - - return queryRequest, nil } -func (queryRequest QueryRequest) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryRequest) +func (queryRequest queryRequest) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryRequest) } - -func (queryRequest QueryRequest) LegacyAminoDecode(bytes []byte) (helpers.QueryRequest, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest queryRequest) Decode(bytes []byte) (helpers.QueryRequest, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryRequest); err != nil { + return nil, err } return queryRequest, nil } func requestPrototype() helpers.QueryRequest { - return QueryRequest{} + return queryRequest{} } - -func queryRequestFromInterface(request helpers.QueryRequest) QueryRequest { +func queryRequestFromInterface(request helpers.QueryRequest) queryRequest { switch value := request.(type) { - case QueryRequest: + case queryRequest: return value default: - return QueryRequest{} + return queryRequest{} } } - -func newQueryRequest(classificationID types.ID) helpers.QueryRequest { - return QueryRequest{ClassificationID: *base.NewID(classificationID.String())} +func newQueryRequest(classificationID ids.ClassificationID) helpers.QueryRequest { + return queryRequest{ClassificationID: classificationID} } diff --git a/modules/classifications/internal/queries/classification/request_test.go b/modules/classifications/internal/queries/classification/request_test.go index 7fefa495a..e10222c7e 100644 --- a/modules/classifications/internal/queries/classification/request_test.go +++ b/modules/classifications/internal/queries/classification/request_test.go @@ -1,59 +1,256 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package classification import ( - "github.com/cosmos/cosmos-sdk/client" + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/common" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" - "testing" + + "github.com/AssetMantle/modules/modules/classifications/internal/common" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" ) -func Test_Classification_Request(t *testing.T) { +func createTestInput() ids.ClassificationID { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIDs.NewClassificationID(immutables, mutables) + return classificationID +} + +func Test_newQueryRequest(t *testing.T) { + type args struct { + classificationID ids.ClassificationID + } + tests := []struct { + name string + args args + want helpers.QueryRequest + }{ + {"+ve", args{createTestInput()}, queryRequest{createTestInput()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newQueryRequest(tt.args.classificationID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newQueryRequest() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequestFromInterface(t *testing.T) { + type args struct { + request helpers.QueryRequest + } + tests := []struct { + name string + args args + want queryRequest + }{ + {"+ve", args{newQueryRequest(createTestInput())}, queryRequest{createTestInput()}}, + {"+ve", args{newQueryRequest(baseIDs.PrototypeClassificationID())}, queryRequest{baseIDs.PrototypeClassificationID()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := queryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("queryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() +func Test_queryRequest_Decode(t *testing.T) { + encodedQueryResponse, err := queryRequest{createTestInput()}.Encode() + require.NoError(t, err) + encodedQueryResponse1, err := queryRequest{baseIDs.PrototypeClassificationID()}.Encode() + require.NoError(t, err) + type fields struct { + ClassificationID ids.ClassificationID + } + type args struct { + bytes []byte + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{baseIDs.PrototypeClassificationID()}, args{encodedQueryResponse}, queryRequest{createTestInput()}, false}, + {"+ve", fields{baseIDs.PrototypeClassificationID()}, args{encodedQueryResponse1}, queryRequest{baseIDs.PrototypeClassificationID()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + ClassificationID: tt.fields.ClassificationID, + } + got, err := queryRequest.Decode(tt.args.bytes) + if (err != nil) != tt.wantErr { + t.Errorf("Decode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Decode() got = %v, want %v", got, tt.want) + } + }) + } +} - testClassificationID := base.NewID("ClassificationID") - testQueryRequest := newQueryRequest(testClassificationID) - require.Equal(t, nil, testQueryRequest.Validate()) - require.Equal(t, queryRequest{}, requestPrototype()) +func Test_queryRequest_Encode(t *testing.T) { + encodedQuery, err := common.Codec.MarshalJSON(queryRequest{baseIDs.PrototypeClassificationID()}) + require.NoError(t, err) + encodedQuery1, err := common.Codec.MarshalJSON(queryRequest{createTestInput()}) + require.NoError(t, err) + type fields struct { + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want []byte + wantErr bool + }{ + {"+ve with nil", fields{baseIDs.PrototypeClassificationID()}, encodedQuery, false}, + {"+ve with nil", fields{createTestInput()}, encodedQuery1, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + ClassificationID: tt.fields.ClassificationID, + } + got, err := queryRequest.Encode() + if (err != nil) != tt.wantErr { + t.Errorf("Encode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Encode() got = %v, want %v", got, tt.want) + } + }) + } +} - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.ClassificationID}) - cliContext := context.NewCLIContext().WithCodec(Codec) - require.Equal(t, newQueryRequest(base.NewID("")), queryRequest{}.FromCLI(cliCommand, cliContext)) +func Test_queryRequest_FromCLI(t *testing.T) { + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.ClassificationID}) + cliContext := context.NewCLIContext().WithCodec(codec.New()) + type fields struct { + ClassificationID ids.ClassificationID + } + type args struct { + cliCommand helpers.CLICommand + in1 context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want string + wantErr bool + }{ + {"+ve", fields{}, args{cliCommand, cliContext}, "", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + ClassificationID: tt.fields.ClassificationID, + } + got, err := qu.FromCLI(tt.args.cliCommand, tt.args.in1) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} +func Test_queryRequest_FromMap(t *testing.T) { vars := make(map[string]string) - vars["classifications"] = "randomString" - require.Equal(t, newQueryRequest(base.NewID("randomString")), queryRequest{}.FromMap(vars)) - - encodedRequest, Error := testQueryRequest.LegacyAminoEncode() - encodedResult, _ := common.LegacyAminoCodec.MarshalJSON(testQueryRequest) - require.Equal(t, encodedResult, encodedRequest) - require.Nil(t, Error) - - decodedRequest, Error := queryRequest{}.LegacyAminoDecode(encodedRequest) - require.Equal(t, testQueryRequest, decodedRequest) - require.Equal(t, nil, Error) - - randomDecode, _ := queryRequest{}.LegacyAminoDecode(base.NewID("").Bytes()) - require.Equal(t, nil, randomDecode) - require.Equal(t, testQueryRequest, queryRequestFromInterface(testQueryRequest)) - require.Equal(t, queryRequest{}, queryRequestFromInterface(nil)) + vars[Query.GetName()] = "GBYwV5EFZY35encqWghm_e6EL5Uy6QnYfKyVIzew24A=" + type fields struct { + ClassificationID ids.ClassificationID + } + type args struct { + vars map[string]string + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{createTestInput()}, args{vars}, newQueryRequest(createTestInput()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + ClassificationID: tt.fields.ClassificationID, + } + got, err := qu.FromMap(tt.args.vars) + if (err != nil) != tt.wantErr { + t.Errorf("FromMap() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromMap() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequest_Validate(t *testing.T) { + type fields struct { + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{createTestInput()}, false}, + {"+ve", fields{baseIDs.PrototypeClassificationID()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + ClassificationID: tt.fields.ClassificationID, + } + if err := queryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryRequest + }{ + {"+ve", queryRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/classifications/internal/queries/classification/response.go b/modules/classifications/internal/queries/classification/response.go index 548858b48..60365ec7e 100644 --- a/modules/classifications/internal/queries/classification/response.go +++ b/modules/classifications/internal/queries/classification/response.go @@ -1,64 +1,49 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package classification import ( - "errors" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/classifications/internal/common" + "github.com/AssetMantle/modules/schema/helpers" ) -var _ helpers.QueryResponse = (*QueryResponse)(nil) +type queryResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` + List []helpers.Mappable `json:"list"` +} + +var _ helpers.QueryResponse = (*queryResponse)(nil) -func (queryResponse QueryResponse) IsSuccessful() bool { +func (queryResponse queryResponse) IsSuccessful() bool { return queryResponse.Success } -func (queryResponse QueryResponse) GetError() error { - return errors.New(queryResponse.Error) +func (queryResponse queryResponse) GetError() error { + return queryResponse.Error } -func (queryResponse QueryResponse) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryResponse) +func (queryResponse queryResponse) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryResponse) } -func (queryResponse QueryResponse) LegacyAminoDecode(bytes []byte) (helpers.QueryResponse, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error +func (queryResponse queryResponse) Decode(bytes []byte) (helpers.QueryResponse, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryResponse); err != nil { + return nil, err } - return &queryResponse, nil -} -func (queryResponse QueryResponse) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryResponse) -} - -func (queryResponse QueryResponse) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryResponse, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error - } - return &queryResponse, nil + return queryResponse, nil } - func responsePrototype() helpers.QueryResponse { - return &QueryResponse{} + return queryResponse{} } - -func newQueryResponse(collection helpers.Collection, error error) QueryResponse { +func newQueryResponse(collection helpers.Collection, error error) helpers.QueryResponse { success := true if error != nil { success = false - return QueryResponse{ - Success: success, - Error: "yes", - List: collection.GetList(), - } } - return QueryResponse{ + + return queryResponse{ Success: success, - Error: "no", + Error: error, List: collection.GetList(), } - } diff --git a/modules/classifications/internal/queries/classification/response_test.go b/modules/classifications/internal/queries/classification/response_test.go index 786ddd9c4..d03badb13 100644 --- a/modules/classifications/internal/queries/classification/response_test.go +++ b/modules/classifications/internal/queries/classification/response_test.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package classification @@ -17,17 +15,17 @@ import ( "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/mapper" - "github.com/persistenceOne/persistenceSDK/schema" + "github.com/AssetMantle/modules/modules/classifications/internal/common" + "github.com/AssetMantle/modules/modules/classifications/internal/mapper" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/errors/constants" ) func CreateTestInput(t *testing.T) sdkTypes.Context { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() @@ -56,21 +54,21 @@ func Test_Classification_Response(t *testing.T) { collection := mapper.Prototype().NewCollection(context) testQueryResponse := newQueryResponse(collection, nil) - testQueryResponseWithError := newQueryResponse(collection, errors.IncorrectFormat) + testQueryResponseWithError := newQueryResponse(collection, constants.IncorrectFormat) require.Equal(t, true, testQueryResponse.IsSuccessful()) require.Equal(t, false, testQueryResponseWithError.IsSuccessful()) require.Equal(t, nil, testQueryResponse.GetError()) - require.Equal(t, errors.IncorrectFormat, testQueryResponseWithError.GetError()) + require.Equal(t, constants.IncorrectFormat, testQueryResponseWithError.GetError()) - encodedResponse, _ := testQueryResponse.LegacyAminoEncode() - bytes, _ := common.LegacyAminoCodec.MarshalJSON(testQueryResponse) + encodedResponse, _ := testQueryResponse.Encode() + bytes, _ := common.Codec.MarshalJSON(testQueryResponse) require.Equal(t, bytes, encodedResponse) - decodedResponse, _ := queryResponse{}.LegacyAminoDecode(bytes) + decodedResponse, _ := queryResponse{}.Decode(bytes) require.Equal(t, testQueryResponse, decodedResponse) - decodedResponse2, _ := queryResponse{}.LegacyAminoDecode([]byte{}) + decodedResponse2, _ := queryResponse{}.Decode([]byte{}) require.Equal(t, nil, decodedResponse2) require.Equal(t, queryResponse{}, responsePrototype()) diff --git a/modules/classifications/internal/queries/prototype.go b/modules/classifications/internal/queries/prototype.go new file mode 100644 index 000000000..c5e3d196b --- /dev/null +++ b/modules/classifications/internal/queries/prototype.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queries + +import ( + "github.com/AssetMantle/modules/modules/classifications/internal/queries/classification" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Queries { + return baseHelpers.NewQueries( + classification.Query, + ) +} diff --git a/modules/classifications/internal/queries/prototype_test.go b/modules/classifications/internal/queries/prototype_test.go new file mode 100644 index 000000000..48faa81a8 --- /dev/null +++ b/modules/classifications/internal/queries/prototype_test.go @@ -0,0 +1,21 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queries + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/classifications/internal/queries/classification" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Panics(t, func() { + require.Equal(t, Prototype().Get("classification").GetName(), baseHelpers.NewQueries( + classification.Query, + ).Get("classification").GetName()) + }) +} diff --git a/modules/classifications/internal/simulator/constants.go b/modules/classifications/internal/simulator/constants.go new file mode 100644 index 000000000..0e23f0a61 --- /dev/null +++ b/modules/classifications/internal/simulator/constants.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +const OpWeightSubmitTextProposal = "op_weight_submit_text_proposal" +const DefaultWeightTextProposal = 1 + +const OpWeightMsg = "OpWeightMsg" +const DefaultWeightMsg = 1 diff --git a/modules/classifications/internal/simulator/genesis.go b/modules/classifications/internal/simulator/genesis.go new file mode 100644 index 000000000..9ddc938e6 --- /dev/null +++ b/modules/classifications/internal/simulator/genesis.go @@ -0,0 +1,50 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "math/rand" + + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + + "github.com/AssetMantle/modules/modules/classifications/internal/common" + "github.com/AssetMantle/modules/modules/classifications/internal/key" + "github.com/AssetMantle/modules/modules/classifications/internal/mappable" + classificationsModule "github.com/AssetMantle/modules/modules/classifications/internal/module" + "github.com/AssetMantle/modules/modules/classifications/internal/parameters" + "github.com/AssetMantle/modules/modules/classifications/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/data" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + parameters2 "github.com/AssetMantle/modules/schema/parameters" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseSimulation "github.com/AssetMantle/modules/simulation/schema/types/base" +) + +func (simulator) RandomizedGenesisState(simulationState *module.SimulationState) { + var Data data.Data + + simulationState.AppParams.GetOrGenerate( + simulationState.Cdc, + dummy.ID.String(), + &Data, + simulationState.Rand, + func(rand *rand.Rand) { Data = baseData.NewDecData(sdkTypes.NewDecWithPrec(int64(rand.Intn(99)), 2)) }, + ) + + mappableList := make([]helpers.Mappable, simulationState.Rand.Intn(99)) + + for i := range mappableList { + immutables := baseQualified.NewImmutables(baseSimulation.GenerateRandomPropertyList(simulationState.Rand)) + mutables := baseQualified.NewMutables(baseSimulation.GenerateRandomPropertyList(simulationState.Rand)) + mappableList[i] = mappable.NewMappable(base.NewClassification(immutables, mutables)) + } + + genesisState := baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, nil, parameters.Prototype().GetList()).Initialize(mappableList, []parameters2.Parameter{dummy.Parameter.Mutate(Data)}) + + simulationState.GenState[classificationsModule.Name] = common.Codec.MustMarshalJSON(genesisState) +} diff --git a/modules/classifications/internal/simulator/operations.go b/modules/classifications/internal/simulator/operations.go index d5dfcf59e..3c3884187 100644 --- a/modules/classifications/internal/simulator/operations.go +++ b/modules/classifications/internal/simulator/operations.go @@ -1,21 +1,18 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( - sdkModuleSimulation "github.com/cosmos/cosmos-sdk/x/simulation" "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" ) -func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec.JSONMarshaler) simulation.WeightedOperation { +func (simulator) WeightedOperations(appParams simulation.AppParams, codec *codec.Codec) simulation.WeightedOperations { var weightMsg int appParams.GetOrGenerate(codec, OpWeightMsg, &weightMsg, nil, @@ -24,10 +21,12 @@ func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec. }, ) - return sdkModuleSimulation.NewWeightedOperation( - weightMsg, - simulateMsg(), - ) + return simulation.WeightedOperations{ + simulation.NewWeightedOperation( + weightMsg, + simulateMsg(), + ), + } } func simulateMsg() simulation.Operation { diff --git a/modules/classifications/internal/simulator/params.go b/modules/classifications/internal/simulator/params.go index 6dbdf27d0..eafc1d157 100644 --- a/modules/classifications/internal/simulator/params.go +++ b/modules/classifications/internal/simulator/params.go @@ -1,31 +1,30 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( "math/rand" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/common" + "github.com/AssetMantle/modules/modules/classifications/internal/common" + "github.com/AssetMantle/modules/schema/data/base" + + sdk "github.com/cosmos/cosmos-sdk/types" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - simTypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + + "github.com/AssetMantle/modules/modules/classifications/internal/module" + "github.com/AssetMantle/modules/modules/classifications/internal/parameters/dummy" ) -func (simulator) ParamChangeList(_ *rand.Rand) []simTypes.ParamChange { - return []simTypes.ParamChange{ +func (simulator) ParamChangeList(_ *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange(module.Name, dummy.ID.String(), func(r *rand.Rand) string { - bytes, Error := common.LegacyAminoCodec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdkTypes.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) - if Error != nil { - panic(Error) + bytes, err := common.Codec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdk.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) + if err != nil { + panic(err) } return string(bytes) }), diff --git a/modules/classifications/internal/simulator/proposals.go b/modules/classifications/internal/simulator/proposals.go index c85fdfbd1..ce4efd54f 100644 --- a/modules/classifications/internal/simulator/proposals.go +++ b/modules/classifications/internal/simulator/proposals.go @@ -1,34 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( - simulation2 "github.com/cosmos/cosmos-sdk/x/simulation" "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/simulation" ) func (simulator) WeightedProposalContentList() []simulation.WeightedProposalContent { return []simulation.WeightedProposalContent{ - simulation2.NewWeightedProposalContent( - OpWeightSubmitTextProposal, - DefaultWeightTextProposal, - contentSimulatorFunc(), - ), + { + AppParamsKey: OpWeightSubmitTextProposal, + DefaultWeight: DefaultWeightTextProposal, + ContentSimulatorFn: simulateTextProposalContent, + }, } } -func contentSimulatorFunc() simulation.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) simulation.Content { - return types.NewTextProposal( - simulation.RandStringOfLength(r, 140), - simulation.RandStringOfLength(r, 5000), - ) - } +func simulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Account) types.Content { + return types.NewTextProposal( + simulation.RandStringOfLength(r, 140), + simulation.RandStringOfLength(r, 5000), + ) } diff --git a/modules/classifications/internal/simulator/prototype.go b/modules/classifications/internal/simulator/prototype.go new file mode 100644 index 000000000..3da39d69f --- /dev/null +++ b/modules/classifications/internal/simulator/prototype.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +func Prototype() helpers.Simulator { + return newSimulator() +} diff --git a/modules/classifications/internal/simulator/prototype_test.go b/modules/classifications/internal/simulator/prototype_test.go new file mode 100644 index 000000000..4352a8d45 --- /dev/null +++ b/modules/classifications/internal/simulator/prototype_test.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype(), newSimulator()) +} diff --git a/modules/classifications/internal/simulator/simulator.go b/modules/classifications/internal/simulator/simulator.go new file mode 100644 index 000000000..d963561c2 --- /dev/null +++ b/modules/classifications/internal/simulator/simulator.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +type simulator struct{} + +var _ helpers.Simulator = (*simulator)(nil) + +func newSimulator() helpers.Simulator { + return simulator{} +} diff --git a/modules/classifications/internal/simulator/simulator_test.go b/modules/classifications/internal/simulator/simulator_test.go new file mode 100644 index 000000000..1a738209a --- /dev/null +++ b/modules/classifications/internal/simulator/simulator_test.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func Test_newSimulator(t *testing.T) { + require.Equal(t, newSimulator(), simulator{}) +} diff --git a/modules/classifications/internal/transactions/prototype.go b/modules/classifications/internal/transactions/prototype.go new file mode 100644 index 000000000..576f90402 --- /dev/null +++ b/modules/classifications/internal/transactions/prototype.go @@ -0,0 +1,13 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transactions + +import ( + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Transactions { + return baseHelpers.NewTransactions() +} diff --git a/modules/classifications/internal/transactions/prototype_test.go b/modules/classifications/internal/transactions/prototype_test.go new file mode 100644 index 000000000..87a575a9c --- /dev/null +++ b/modules/classifications/internal/transactions/prototype_test.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transactions + +import ( + "testing" + + "github.com/stretchr/testify/require" + + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype(), baseHelpers.NewTransactions()) +} diff --git a/modules/classifications/prototype.go b/modules/classifications/prototype.go new file mode 100644 index 000000000..014da5c14 --- /dev/null +++ b/modules/classifications/prototype.go @@ -0,0 +1,32 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package classifications + +import ( + "github.com/AssetMantle/modules/modules/classifications/auxiliaries" + "github.com/AssetMantle/modules/modules/classifications/internal/block" + "github.com/AssetMantle/modules/modules/classifications/internal/genesis" + "github.com/AssetMantle/modules/modules/classifications/internal/mapper" + "github.com/AssetMantle/modules/modules/classifications/internal/module" + "github.com/AssetMantle/modules/modules/classifications/internal/parameters" + "github.com/AssetMantle/modules/modules/classifications/internal/queries" + "github.com/AssetMantle/modules/modules/classifications/internal/simulator" + "github.com/AssetMantle/modules/modules/classifications/internal/transactions" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Module { + return baseHelpers.NewModule( + module.Name, + auxiliaries.Prototype, + genesis.Prototype, + mapper.Prototype, + parameters.Prototype, + queries.Prototype, + simulator.Prototype, + transactions.Prototype, + block.Prototype, + ) +} diff --git a/modules/classifications/prototype_test.go b/modules/classifications/prototype_test.go new file mode 100644 index 000000000..251d4a34c --- /dev/null +++ b/modules/classifications/prototype_test.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package classifications + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries" + "github.com/AssetMantle/modules/modules/classifications/internal/block" + "github.com/AssetMantle/modules/modules/classifications/internal/genesis" + "github.com/AssetMantle/modules/modules/classifications/internal/mapper" + "github.com/AssetMantle/modules/modules/classifications/internal/module" + "github.com/AssetMantle/modules/modules/classifications/internal/parameters" + "github.com/AssetMantle/modules/modules/classifications/internal/queries" + "github.com/AssetMantle/modules/modules/classifications/internal/simulator" + "github.com/AssetMantle/modules/modules/classifications/internal/transactions" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Name(), baseHelpers.NewModule( + module.Name, + auxiliaries.Prototype, + genesis.Prototype, + mapper.Prototype, + parameters.Prototype, + queries.Prototype, + simulator.Prototype, + transactions.Prototype, + block.Prototype, + ).Name()) +} diff --git a/modules/identities/auxiliaries/authenticate/auxiliary.go b/modules/identities/auxiliaries/authenticate/auxiliary.go new file mode 100644 index 000000000..40542978a --- /dev/null +++ b/modules/identities/auxiliaries/authenticate/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package authenticate + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "authenticate", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "authenticate", + keeperPrototypeMock, +) diff --git a/modules/identities/auxiliaries/authenticate/keeper.go b/modules/identities/auxiliaries/authenticate/keeper.go new file mode 100644 index 000000000..31e93bee0 --- /dev/null +++ b/modules/identities/auxiliaries/authenticate/keeper.go @@ -0,0 +1,63 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package authenticate + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/schema/documents" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplementAuxiliary helpers.Auxiliary +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + + Mappable := auxiliaryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(auxiliaryRequest.IdentityID)).Get(key.NewKey(auxiliaryRequest.IdentityID)) + if Mappable == nil { + return newAuxiliaryResponse(errorConstants.EntityNotFound) + } + + identity := Mappable.(documents.Identity) + + if !identity.IsProvisioned(auxiliaryRequest.Address) { + return newAuxiliaryResponse(errorConstants.NotAuthorized) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeper auxiliaryKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + auxiliaryKeeper.mapper, auxiliaryKeeper.parameters = mapper, parameters + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case supplement.Auxiliary.GetName(): + auxiliaryKeeper.supplementAuxiliary = value + default: + break + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return auxiliaryKeeper +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/identities/auxiliaries/authenticate/keeper_mock.go b/modules/identities/auxiliaries/authenticate/keeper_mock.go new file mode 100644 index 000000000..8bbf33b61 --- /dev/null +++ b/modules/identities/auxiliaries/authenticate/keeper_mock.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package authenticate + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeperMock)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(_ sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + if auxiliaryRequest.Address.Equals(sdkTypes.AccAddress("verifyError")) { + return newAuxiliaryResponse(constants.MockError) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/identities/auxiliaries/authenticate/keeper_test.go b/modules/identities/auxiliaries/authenticate/keeper_test.go new file mode 100644 index 000000000..d1c89c0cb --- /dev/null +++ b/modules/identities/auxiliaries/authenticate/keeper_test.go @@ -0,0 +1,177 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package authenticate + +import ( + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/modules/identities/internal/parameters" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +var ( + supplementAuxiliary helpers.Auxiliary +) + +type TestKeepers struct { + AuthenticateKeeper helpers.AuxiliaryKeeper +} + +func CreateTestInput(t *testing.T) (types.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := types.NewKVStoreKey("test") + paramsStoreKey := types.NewKVStoreKey("testParams") + paramsTransientStoreKeys := types.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, types.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + supplementAuxiliary = supplement.AuxiliaryMock.Initialize(Mapper, Parameters) + context := types.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + keepers := TestKeepers{ + AuthenticateKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{supplementAuxiliary}).(helpers.AuxiliaryKeeper), + } + + return context, keepers, Mapper, Parameters +} + +func Test_auxiliaryKeeper_Help(t *testing.T) { + context, keepers, Mapper, Parameters := CreateTestInput(t) + mutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + immutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + immutables := baseQualified.NewImmutables(immutableProperties) + mutables := baseQualified.NewMutables(mutableProperties) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + testIdentity := baseDocuments.NewIdentity(testClassificationID, immutables, mutables) + testIdentity.ProvisionAddress([]types.AccAddress{fromAccAddress}...) + keepers.AuthenticateKeeper.(auxiliaryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testIdentity)) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplementAuxiliary helpers.Auxiliary + } + type args struct { + context types.Context + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + fields fields + args args + want helpers.AuxiliaryResponse + }{ + {"+ve", fields{Mapper, Parameters, supplementAuxiliary}, args{context, NewAuxiliaryRequest(fromAccAddress, testFromID)}, newAuxiliaryResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryKeeper := auxiliaryKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + supplementAuxiliary: tt.fields.supplementAuxiliary, + } + if got := auxiliaryKeeper.Help(tt.args.context, tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Help() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_auxiliaryKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := CreateTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplementAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper, Parameters, supplementAuxiliary}, args{Mapper, Parameters, []interface{}{}}, auxiliaryKeeper{Mapper, Parameters, supplementAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryKeeper := auxiliaryKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + supplementAuxiliary: tt.fields.supplementAuxiliary, + } + if got := auxiliaryKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.AuxiliaryKeeper + }{ + {"+ve", auxiliaryKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/identities/auxiliaries/authenticate/request.go b/modules/identities/auxiliaries/authenticate/request.go new file mode 100644 index 000000000..56774dbc0 --- /dev/null +++ b/modules/identities/auxiliaries/authenticate/request.go @@ -0,0 +1,40 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package authenticate + +import ( + "github.com/asaskevich/govalidator" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" +) + +type auxiliaryRequest struct { + Address sdkTypes.AccAddress `json:"address" valid:"required~required field address missing, matches(^[a-z0-9]*$)~field address is invalid"` + ids.IdentityID `json:"identityID" valid:"required~required field identityID missing"` +} + +var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) + +func (auxiliaryRequest auxiliaryRequest) Validate() error { + _, err := govalidator.ValidateStruct(auxiliaryRequest) + return err +} + +func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { + switch value := request.(type) { + case auxiliaryRequest: + return value + default: + return auxiliaryRequest{} + } +} + +func NewAuxiliaryRequest(address sdkTypes.AccAddress, identityID ids.IdentityID) helpers.AuxiliaryRequest { + return auxiliaryRequest{ + Address: address, + IdentityID: identityID, + } +} diff --git a/modules/identities/auxiliaries/authenticate/request_test.go b/modules/identities/auxiliaries/authenticate/request_test.go new file mode 100644 index 000000000..4c400acf2 --- /dev/null +++ b/modules/identities/auxiliaries/authenticate/request_test.go @@ -0,0 +1,99 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package authenticate + +import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +var ( + mutableProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + immutableProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + toMutateMetaProperties = baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList(baseData.NewStringData("Test"))))) + immutables = baseQualified.NewImmutables(immutableProperties) + mutables = baseQualified.NewMutables(mutableProperties) + testClassificationID = baseIDs.NewClassificationID(immutables, mutables) + testFromID = baseIDs.NewIdentityID(testClassificationID, immutables) + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = types.AccAddressFromBech32(fromAddress) +) + +func TestNewAuxiliaryRequest(t *testing.T) { + type args struct { + address types.AccAddress + identityID ids.IdentityID + } + tests := []struct { + name string + args args + want helpers.AuxiliaryRequest + }{ + {"+ve", args{fromAccAddress, testFromID}, auxiliaryRequest{fromAccAddress, testFromID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewAuxiliaryRequest(tt.args.address, tt.args.identityID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewAuxiliaryRequest() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_auxiliaryRequestFromInterface(t *testing.T) { + type args struct { + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + args args + want auxiliaryRequest + }{ + {"+ve with nil", args{}, auxiliaryRequest{}}, + {"+ve", args{auxiliaryRequest{fromAccAddress, testFromID}}, auxiliaryRequest{fromAccAddress, testFromID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := auxiliaryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("auxiliaryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_auxiliaryRequest_Validate(t *testing.T) { + type fields struct { + Address types.AccAddress + IdentityID ids.IdentityID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve with nil", fields{}, true}, + {"+ve", fields{fromAccAddress, testFromID}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryRequest := auxiliaryRequest{ + Address: tt.fields.Address, + IdentityID: tt.fields.IdentityID, + } + if err := auxiliaryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/modules/identities/auxiliaries/authenticate/response.go b/modules/identities/auxiliaries/authenticate/response.go new file mode 100644 index 000000000..eb37128c4 --- /dev/null +++ b/modules/identities/auxiliaries/authenticate/response.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package authenticate + +import "github.com/AssetMantle/modules/schema/helpers" + +type auxiliaryResponse struct { + Success bool `json:"success"` + Error error `json:"error"` +} + +var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) + +func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { + return auxiliaryResponse.Success +} +func (auxiliaryResponse auxiliaryResponse) GetError() error { + return auxiliaryResponse.Error +} +func newAuxiliaryResponse(error error) helpers.AuxiliaryResponse { + success := true + if error != nil { + success = false + } + + return auxiliaryResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/identities/auxiliaries/authenticate/response_test.go b/modules/identities/auxiliaries/authenticate/response_test.go new file mode 100644 index 000000000..8289f7c8b --- /dev/null +++ b/modules/identities/auxiliaries/authenticate/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package authenticate + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Verify_Response(t *testing.T) { + testAuxiliaryResponse := newAuxiliaryResponse(nil) + require.Equal(t, auxiliaryResponse{Success: true, Error: nil}, testAuxiliaryResponse) + require.Equal(t, true, testAuxiliaryResponse.IsSuccessful()) + require.Equal(t, nil, testAuxiliaryResponse.GetError()) + + testAuxiliaryResponse2 := newAuxiliaryResponse(constants.IncorrectFormat) + require.Equal(t, auxiliaryResponse{Success: false, Error: constants.IncorrectFormat}, testAuxiliaryResponse2) + require.Equal(t, false, testAuxiliaryResponse2.IsSuccessful()) + require.Equal(t, constants.IncorrectFormat, testAuxiliaryResponse2.GetError()) +} diff --git a/modules/identities/auxiliaries/prototype.go b/modules/identities/auxiliaries/prototype.go new file mode 100644 index 000000000..0af45e176 --- /dev/null +++ b/modules/identities/auxiliaries/prototype.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Auxiliaries { + return baseHelpers.NewAuxiliaries( + authenticate.Auxiliary, + ) +} diff --git a/modules/identities/auxiliaries/prototype_test.go b/modules/identities/auxiliaries/prototype_test.go new file mode 100644 index 000000000..f65da0bc7 --- /dev/null +++ b/modules/identities/auxiliaries/prototype_test.go @@ -0,0 +1,29 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "reflect" + "testing" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want string + }{ + + {"+ve", baseHelpers.NewAuxiliaries(authenticate.Auxiliary).Get("authenticate").GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype().Get("authenticate").GetName(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/identities/doc.go b/modules/identities/doc.go new file mode 100644 index 000000000..e868f9696 --- /dev/null +++ b/modules/identities/doc.go @@ -0,0 +1,5 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +// Package identities defines the identities' module. +package identities diff --git a/modules/identities/internal/block/block.go b/modules/identities/internal/block/block.go new file mode 100644 index 000000000..2b406cdb0 --- /dev/null +++ b/modules/identities/internal/block/block.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package block + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + abciTypes "github.com/tendermint/tendermint/abci/types" + + "github.com/AssetMantle/modules/schema/helpers" +) + +type block struct { + mapper helpers.Mapper + parameters helpers.Parameters +} + +var _ helpers.Block = (*block)(nil) + +func (block block) Begin(_ sdkTypes.Context, _ abciTypes.RequestBeginBlock) { + +} + +func (block block) End(_ sdkTypes.Context, _ abciTypes.RequestEndBlock) { + +} + +func Prototype() helpers.Block { + return block{} +} + +func (block block) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, _ ...interface{}) helpers.Block { + block.mapper, block.parameters = mapper, parameters + return block +} diff --git a/modules/identities/internal/block/block_test.go b/modules/identities/internal/block/block_test.go new file mode 100644 index 000000000..f84f2e8da --- /dev/null +++ b/modules/identities/internal/block/block_test.go @@ -0,0 +1,111 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package block + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/identities/internal/mapper" + "github.com/AssetMantle/modules/modules/identities/internal/parameters" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" +) + +func CreateTestInput(t *testing.T) sdkTypes.Context { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + return context +} + +func Test_block_Begin(t *testing.T) { + context := CreateTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + } + type args struct { + in0 sdkTypes.Context + in1 abciTypes.RequestBeginBlock + } + tests := []struct { + name string + fields fields + args args + }{ + + {"+ve", fields{mapper: mapper.Prototype(), parameters: parameters.Prototype()}, args{in0: context, in1: abciTypes.RequestBeginBlock{}}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + block := block{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + } + block.Begin(tt.args.in0, tt.args.in1) + }) + } +} + +func Test_block_End(t *testing.T) { + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + } + type args struct { + in0 sdkTypes.Context + in1 abciTypes.RequestEndBlock + } + tests := []struct { + name string + fields fields + args args + }{ + + {"+ve", fields{mapper.Prototype(), parameters.Prototype()}, args{CreateTestInput(t), abciTypes.RequestEndBlock{}}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + block := block{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + } + block.End(tt.args.in0, tt.args.in1) + }) + } +} + +func Test_block_Initialize(t *testing.T) { + block := Prototype() + block.Initialize(mapper.Prototype(), parameters.Prototype(), []helpers.Auxiliary{}) +} diff --git a/modules/identities/internal/common/codec.go b/modules/identities/internal/common/codec.go new file mode 100644 index 000000000..3a71cac93 --- /dev/null +++ b/modules/identities/internal/common/codec.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package common + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/utilities/module" +) + +var Codec *codec.Codec + +func init() { + Codec = module.RegisterCodec(key.Prototype, mappable.Prototype) +} diff --git a/modules/identities/internal/genesis/genesis.go b/modules/identities/internal/genesis/genesis.go deleted file mode 100644 index 62ad1f908..000000000 --- a/modules/identities/internal/genesis/genesis.go +++ /dev/null @@ -1,189 +0,0 @@ -package genesis - -import ( - "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ helpers.Genesis = (*Genesis)(nil) - -func (genesis Genesis) Default() helpers.Genesis { - return genesis.Initialize(genesis.GetMappableList(), genesis.GetParameterList()) -} - -func (genesis Genesis) Validate() error { - if len(genesis.ParameterList) != len(genesis.DefaultParameterList) { - return errors.InvalidParameter - } - - for _, parameter := range genesis.ParameterList { - var isPresent bool - for _, defaultParameter := range genesis.DefaultParameterList { - isPresent = false - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - isPresent = true - break - } - } - - if !isPresent { - return errors.InvalidParameter - } - - if Error := parameter.Validate(); Error != nil { - return Error - } - } - - _, Error := govalidator.ValidateStruct(genesis) - - return Error -} - -func (genesis Genesis) Import(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) { - for _, mappableValue := range genesis.MappableList { - mapper.Create(context, &mappableValue) - } - - for _, parameter := range genesis.ParameterList { - parameters.Mutate(context, ¶meter) - } -} - -func (genesis Genesis) Export(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) helpers.Genesis { - var mappableList []helpers.Mappable - - appendMappableList := func(mappable helpers.Mappable) bool { - mappableList = append(mappableList, mappable) - return false - } - mapper.Iterate(context, key.Prototype(), appendMappableList) - - for _, defaultParameter := range genesis.DefaultParameterList { - parameters = parameters.Fetch(context, defaultParameter.GetID()) - } - - return genesis.Initialize(mappableList, parameters.GetList()) -} - -func (genesis Genesis) LegacyAminoEncode() []byte { - legacyAminoCodec := codec.NewLegacyAmino() - bytes, Error := legacyAminoCodec.MarshalJSON(genesis) - if Error != nil { - panic(Error) - } - - return bytes -} -func (genesis Genesis) LegacyAminoDecode(byte []byte) helpers.Genesis { - var newGenesis Genesis - legacyAminoCodec := codec.NewLegacyAmino() - if Error := legacyAminoCodec.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(genesis.DefaultMappableList, genesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Encode(cdc codec.JSONMarshaler) []byte { - - bytes, Error := cdc.MarshalJSON(&genesis) - if Error != nil { - panic(Error) - } - - return bytes -} - -func (genesis Genesis) Decode(cdc codec.JSONMarshaler, byte []byte) helpers.Genesis { - var newGenesis Genesis - if Error := cdc.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(genesis.DefaultMappableList, genesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Initialize(mappableList []helpers.Mappable, parameterList []types.Parameter) helpers.Genesis { - newParametersList := make([]dummy.DummyParameter, len(parameterList)) - for i, _ := range parameterList { - newParametersList[i] = *dummy.NewParameter(parameterList[i].GetID(), parameterList[i].GetData()) - } - newMappableList := make([]mappable.Identity, len(mappableList)) - for i, _ := range mappableList { - newMappableList[i] = *mappableList[i].(*mappable.Identity) - } - newParameter := dummy.Parameter.Mutate(dummy.Parameter.GetData()) - genesis.DefaultParameterList = []dummy.DummyParameter{*dummy.NewParameter(newParameter.GetID(), newParameter.GetData())} - if len(newMappableList) == 0 { - genesis.MappableList = genesis.DefaultMappableList - } else { - genesis.MappableList = newMappableList - } - - if len(newParametersList) == 0 { - genesis.ParameterList = genesis.DefaultParameterList - } else { - for _, defaultParameter := range genesis.DefaultParameterList { - for i, parameter := range newParametersList { - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - newParametersList[i] = *dummy.NewParameter(defaultParameter.Mutate(parameter.GetData()).GetID(), defaultParameter.Mutate(parameter.GetData()).GetData()) - } - } - } - genesis.ParameterList = newParametersList - } - - if Error := genesis.Validate(); Error != nil { - panic(Error) - } - - return &genesis -} - -func (genesis Genesis) GetParameterList() []types.Parameter { - newParameterList := make([]types.Parameter, len(genesis.ParameterList)) - for i, _ := range genesis.ParameterList { - newParameterList[i] = &genesis.ParameterList[i] - } - return newParameterList -} -func (genesis Genesis) GetMappableList() []helpers.Mappable { - newMappableList := make([]helpers.Mappable, len(genesis.MappableList)) - for i, _ := range genesis.MappableList { - newMappableList[i] = &genesis.MappableList[i] - } - return newMappableList -} - -func (genesis Genesis) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*helpers.Key)(nil), - &key.IdentityID{}, - ) - registry.RegisterImplementations((*helpers.Mappable)(nil), - &mappable.Identity{}, - ) - registry.RegisterImplementations((*types.Parameter)(nil), - &dummy.DummyParameter{}, - ) - registry.RegisterImplementations((*helpers.Genesis)(nil), - &Genesis{}, - ) -} - -func NewGenesis(defaultMappableList []mappable.Identity, defaultParameterList []dummy.DummyParameter) *Genesis { - return &Genesis{ - DefaultMappableList: defaultMappableList, - DefaultParameterList: defaultParameterList, - MappableList: []mappable.Identity{}, - ParameterList: []dummy.DummyParameter{}, - } -} diff --git a/modules/identities/internal/genesis/genesis.pb.go b/modules/identities/internal/genesis/genesis.pb.go deleted file mode 100644 index 3e5199325..000000000 --- a/modules/identities/internal/genesis/genesis.pb.go +++ /dev/null @@ -1,499 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/genesis/genesis.proto - -package genesis - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - mappable "github.com/persistenceOne/persistenceSDK/modules/identities/internal/mappable" - dummy "github.com/persistenceOne/persistenceSDK/modules/identities/internal/parameters/dummy" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Genesis struct { - DefaultMappableList []mappable.Identity `protobuf:"bytes,1,rep,name=defaultMappableList,proto3" json:"defaultMappableList"` - DefaultParameterList []dummy.DummyParameter `protobuf:"bytes,2,rep,name=defaultParameterList,proto3" json:"defaultParameterList"` - MappableList []mappable.Identity `protobuf:"bytes,3,rep,name=MappableList,proto3" json:"MappableList"` - ParameterList []dummy.DummyParameter `protobuf:"bytes,4,rep,name=ParameterList,proto3" json:"ParameterList"` -} - -func (m *Genesis) Reset() { *m = Genesis{} } -func (m *Genesis) String() string { return proto.CompactTextString(m) } -func (*Genesis) ProtoMessage() {} -func (*Genesis) Descriptor() ([]byte, []int) { - return fileDescriptor_d750e73d0638d9f3, []int{0} -} -func (m *Genesis) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Genesis) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Genesis.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Genesis) XXX_Merge(src proto.Message) { - xxx_messageInfo_Genesis.Merge(m, src) -} -func (m *Genesis) XXX_Size() int { - return m.Size() -} -func (m *Genesis) XXX_DiscardUnknown() { - xxx_messageInfo_Genesis.DiscardUnknown(m) -} - -var xxx_messageInfo_Genesis proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Genesis)(nil), "persistence_sdk.modules.identities.internal.genesis.Genesis") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/genesis/genesis.proto", fileDescriptor_d750e73d0638d9f3) -} - -var fileDescriptor_d750e73d0638d9f3 = []byte{ - // 331 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x72, 0x2c, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4c, 0x49, 0xcd, 0x2b, 0xc9, 0x2c, 0xc9, 0x04, 0x31, 0xf3, 0x4a, - 0x52, 0x8b, 0xf2, 0x12, 0x73, 0xf4, 0xd3, 0x53, 0xf3, 0x52, 0x8b, 0x33, 0x8b, 0x61, 0xb4, 0x5e, - 0x41, 0x51, 0x7e, 0x49, 0xbe, 0x90, 0x31, 0x9a, 0x11, 0x7a, 0x50, 0x23, 0xf4, 0x10, 0x46, 0xe8, - 0xc1, 0x8c, 0xd0, 0x83, 0x6a, 0x95, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0xeb, 0xd7, 0x07, 0xb1, - 0x20, 0x46, 0x49, 0xf9, 0x90, 0xe2, 0x9a, 0x82, 0xc4, 0xa2, 0xc4, 0xdc, 0xd4, 0x92, 0xd4, 0xa2, - 0x62, 0xfd, 0x94, 0xd2, 0xdc, 0xdc, 0x4a, 0x84, 0x00, 0xd4, 0x34, 0x67, 0x52, 0x4c, 0xcb, 0x4d, - 0x2c, 0x28, 0x48, 0x4c, 0xca, 0x49, 0x85, 0x49, 0x56, 0x42, 0x0c, 0x51, 0x7a, 0xc8, 0xcc, 0xc5, - 0xee, 0x0e, 0x71, 0xb4, 0x50, 0x19, 0x97, 0x70, 0x4a, 0x6a, 0x5a, 0x62, 0x69, 0x4e, 0x89, 0x2f, - 0x54, 0xb5, 0x4f, 0x66, 0x71, 0x89, 0x04, 0xa3, 0x02, 0xb3, 0x06, 0xb7, 0x91, 0x9d, 0x1e, 0x29, - 0xe1, 0x00, 0xb3, 0x4e, 0xcf, 0x13, 0x6a, 0x9d, 0x13, 0xcb, 0x89, 0x7b, 0xf2, 0x0c, 0x41, 0xd8, - 0x2c, 0x10, 0xaa, 0xe5, 0x12, 0x81, 0x0a, 0x07, 0xc0, 0xbc, 0x08, 0xb6, 0x98, 0x09, 0x6c, 0xb1, - 0x33, 0x31, 0x16, 0x23, 0x02, 0x4b, 0x0f, 0x1c, 0x58, 0x7a, 0x2e, 0x20, 0x12, 0x6e, 0x1c, 0xd4, - 0x76, 0xac, 0xd6, 0x08, 0x65, 0x70, 0xf1, 0xa0, 0xf8, 0x97, 0x99, 0x8a, 0xfe, 0x45, 0x31, 0x59, - 0x28, 0x9f, 0x8b, 0x17, 0xd5, 0x87, 0x2c, 0xd4, 0xf6, 0x21, 0xaa, 0xf9, 0x56, 0x2c, 0x1d, 0x0b, - 0xe4, 0x19, 0x9c, 0xd2, 0x4e, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, - 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0xca, 0x27, - 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0x1f, 0xc9, 0x0d, 0xfe, 0x79, 0xa9, - 0xc8, 0xdc, 0x60, 0x17, 0x6f, 0x62, 0xf2, 0x4d, 0x12, 0x1b, 0x38, 0x49, 0x19, 0x03, 0x02, 0x00, - 0x00, 0xff, 0xff, 0x2e, 0xc9, 0x41, 0x85, 0x75, 0x03, 0x00, 0x00, -} - -func (m *Genesis) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Genesis) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Genesis) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ParameterList) > 0 { - for iNdEx := len(m.ParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.MappableList) > 0 { - for iNdEx := len(m.MappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.DefaultParameterList) > 0 { - for iNdEx := len(m.DefaultParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.DefaultMappableList) > 0 { - for iNdEx := len(m.DefaultMappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultMappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Genesis) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.DefaultMappableList) > 0 { - for _, e := range m.DefaultMappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.DefaultParameterList) > 0 { - for _, e := range m.DefaultParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.MappableList) > 0 { - for _, e := range m.MappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ParameterList) > 0 { - for _, e := range m.ParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Genesis) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Genesis: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Genesis: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultMappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultMappableList = append(m.DefaultMappableList, mappable.Identity{}) - if err := m.DefaultMappableList[len(m.DefaultMappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultParameterList = append(m.DefaultParameterList, dummy.DummyParameter{}) - if err := m.DefaultParameterList[len(m.DefaultParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MappableList = append(m.MappableList, mappable.Identity{}) - if err := m.MappableList[len(m.MappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ParameterList = append(m.ParameterList, dummy.DummyParameter{}) - if err := m.ParameterList[len(m.ParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/genesis/prototype.go b/modules/identities/internal/genesis/prototype.go index d8548bb7e..5a8c75e41 100644 --- a/modules/identities/internal/genesis/prototype.go +++ b/modules/identities/internal/genesis/prototype.go @@ -1,16 +1,17 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package genesis import ( - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/modules/identities/internal/parameters" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" ) +// TODO ***** add module nub IDs func Prototype() helpers.Genesis { - return NewGenesis([]mappable.Identity{}, []dummy.DummyParameter{}) + return baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{}, parameters.Prototype().GetList()) } diff --git a/modules/identities/internal/genesis/prototype_test.go b/modules/identities/internal/genesis/prototype_test.go new file mode 100644 index 000000000..473202656 --- /dev/null +++ b/modules/identities/internal/genesis/prototype_test.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package genesis + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/modules/identities/internal/parameters" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Panics(t, func() { + require.Equal(t, Prototype(), baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{}, parameters.Prototype().GetList())) + }) +} diff --git a/modules/identities/internal/key/identityID.pb.go b/modules/identities/internal/key/identityID.pb.go deleted file mode 100644 index fa41f42be..000000000 --- a/modules/identities/internal/key/identityID.pb.go +++ /dev/null @@ -1,367 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/key/identityID.proto - -package key - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - github_com_persistenceOne_persistenceSDK_schema_types "github.com/persistenceOne/persistenceSDK/schema/types" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type IdentityID struct { - ClassificationID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,1,opt,name=classification_i_d,json=classificationID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"classification_i_d"` - HashID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,2,opt,name=hash_i_d,json=hashID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"hash_i_d"` -} - -func (m *IdentityID) Reset() { *m = IdentityID{} } -func (*IdentityID) ProtoMessage() {} -func (*IdentityID) Descriptor() ([]byte, []int) { - return fileDescriptor_ff03090ecd6bb0d3, []int{0} -} -func (m *IdentityID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *IdentityID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_IdentityID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *IdentityID) XXX_Merge(src proto.Message) { - xxx_messageInfo_IdentityID.Merge(m, src) -} -func (m *IdentityID) XXX_Size() int { - return m.Size() -} -func (m *IdentityID) XXX_DiscardUnknown() { - xxx_messageInfo_IdentityID.DiscardUnknown(m) -} - -var xxx_messageInfo_IdentityID proto.InternalMessageInfo - -func init() { - proto.RegisterType((*IdentityID)(nil), "persistence_sdk.modules.identities.internal.key.IdentityID") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/key/identityID.proto", fileDescriptor_ff03090ecd6bb0d3) -} - -var fileDescriptor_ff03090ecd6bb0d3 = []byte{ - // 267 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x72, 0x28, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4c, 0x49, 0xcd, 0x2b, 0xc9, 0x2c, 0xc9, 0x04, 0x31, 0xf3, 0x4a, - 0x52, 0x8b, 0xf2, 0x12, 0x73, 0xf4, 0xb3, 0x53, 0x2b, 0x61, 0xe2, 0x95, 0x9e, 0x2e, 0x7a, 0x05, - 0x45, 0xf9, 0x25, 0xf9, 0x42, 0xfa, 0x68, 0x26, 0xe8, 0x41, 0x4d, 0xd0, 0x43, 0x98, 0xa0, 0x07, - 0x33, 0x41, 0x2f, 0x3b, 0xb5, 0x52, 0x4a, 0x24, 0x3d, 0x3f, 0x3d, 0x1f, 0xac, 0x57, 0x1f, 0xc4, - 0x82, 0x18, 0xa3, 0x74, 0x8f, 0x91, 0x8b, 0xcb, 0x13, 0x6e, 0xb6, 0x50, 0x1e, 0x97, 0x50, 0x72, - 0x4e, 0x62, 0x71, 0x71, 0x66, 0x5a, 0x66, 0x72, 0x62, 0x49, 0x66, 0x7e, 0x5e, 0x7c, 0x66, 0x7c, - 0x8a, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xa7, 0x93, 0xc3, 0x89, 0x7b, 0xf2, 0x0c, 0xb7, 0xee, 0xc9, - 0x5b, 0xa4, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0x22, 0x3b, 0xc2, 0x3f, 0x2f, - 0x15, 0x99, 0x1b, 0xec, 0xe2, 0xad, 0x5f, 0x9c, 0x9c, 0x91, 0x9a, 0x9b, 0xa8, 0x5f, 0x52, 0x59, - 0x90, 0x5a, 0xac, 0xe7, 0xe9, 0x12, 0x24, 0x80, 0x6a, 0xb6, 0xa7, 0x8b, 0x50, 0x14, 0x17, 0x47, - 0x46, 0x62, 0x71, 0x06, 0xd8, 0x16, 0x26, 0x2a, 0xd9, 0xc2, 0x06, 0x32, 0xd1, 0xd3, 0xc5, 0x8a, - 0x65, 0xc6, 0x02, 0x79, 0x06, 0xa7, 0xa4, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, - 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, - 0x88, 0xf2, 0x20, 0xda, 0x06, 0x02, 0x91, 0x93, 0xc4, 0x06, 0x0e, 0x4b, 0x63, 0x40, 0x00, 0x00, - 0x00, 0xff, 0xff, 0x33, 0x17, 0x69, 0x8c, 0xd6, 0x01, 0x00, 0x00, -} - -func (m *IdentityID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *IdentityID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *IdentityID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.HashID.Size() - i -= size - if _, err := m.HashID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintIdentityID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.ClassificationID.Size() - i -= size - if _, err := m.ClassificationID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintIdentityID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintIdentityID(dAtA []byte, offset int, v uint64) int { - offset -= sovIdentityID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *IdentityID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ClassificationID.Size() - n += 1 + l + sovIdentityID(uint64(l)) - l = m.HashID.Size() - n += 1 + l + sovIdentityID(uint64(l)) - return n -} - -func sovIdentityID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozIdentityID(x uint64) (n int) { - return sovIdentityID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *IdentityID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIdentityID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: IdentityID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: IdentityID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIdentityID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthIdentityID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthIdentityID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HashID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIdentityID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthIdentityID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthIdentityID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HashID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipIdentityID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthIdentityID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipIdentityID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdentityID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdentityID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdentityID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthIdentityID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupIdentityID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthIdentityID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthIdentityID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowIdentityID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupIdentityID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/key/key.go b/modules/identities/internal/key/key.go new file mode 100644 index 000000000..1328aa2a6 --- /dev/null +++ b/modules/identities/internal/key/key.go @@ -0,0 +1,54 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package key + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/identities/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +type key struct { + ids.IdentityID +} + +var _ helpers.Key = (*key)(nil) + +func (key key) GenerateStoreKeyBytes() []byte { + return module.StoreKeyPrefix.GenerateStoreKey(key.Bytes()) +} +func (key) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, key{}) +} +func (key key) IsPartial() bool { + return len(key.IdentityID.GetHashID().Bytes()) == 0 +} +func (key key) Equals(compareKey helpers.Key) bool { + if CompareKey, err := keyFromInterface(compareKey); err != nil { + return false + } else { + // TODO test nil IdentityID case + return key.IdentityID.Compare(CompareKey.IdentityID) == 0 + } +} +func keyFromInterface(i interface{}) (key, error) { + switch value := i.(type) { + case key: + return value, nil + default: + return key{}, errorConstants.MetaDataError + } +} + +func NewKey(identityID ids.IdentityID) helpers.Key { + return key{IdentityID: identityID} +} + +func Prototype() helpers.Key { + return key{} +} diff --git a/modules/identities/internal/key/utilities.go b/modules/identities/internal/key/utilities.go index 030cdc599..35ff7df5a 100644 --- a/modules/identities/internal/key/utilities.go +++ b/modules/identities/internal/key/utilities.go @@ -1,47 +1,4 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package key - -import ( - "strings" - - "github.com/persistenceOne/persistenceSDK/schema/helpers" - - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -func readIdentityID(identityIDString string) IdentityID { - idList := strings.Split(identityIDString, constants.FirstOrderCompositeIDSeparator) - if len(idList) == 2 { - return IdentityID{ - ClassificationID: base.NewID(idList[0]), - HashID: base.NewID(idList[1]), - } - } - - return IdentityID{ClassificationID: base.NewID(""), HashID: base.NewID("")} -} - -func identityIDFromInterface(i interface{}) IdentityID { - switch value := i.(type) { - case IdentityID: - return value - case types.ID: - return identityIDFromInterface(readIdentityID(value.String())) - default: - panic(i) - } -} - -func FromID(id types.ID) helpers.Key { - return identityIDFromInterface(id) -} - -func ReadClassificationID(identityID types.ID) types.ID { - return base.NewID(identityIDFromInterface(identityID).ClassificationID.String()) -} diff --git a/modules/identities/internal/mappable/identity.pb.go b/modules/identities/internal/mappable/identity.pb.go deleted file mode 100644 index acabd45c7..000000000 --- a/modules/identities/internal/mappable/identity.pb.go +++ /dev/null @@ -1,417 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/mappable/identity.proto - -package mappable - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base1 "github.com/persistenceOne/persistenceSDK/schema/traits/base" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Identity struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - HasImmutables base1.HasImmutables `protobuf:"bytes,2,opt,name=has_immutables,json=hasImmutables,proto3" json:"has_immutables"` - HasMutables base1.HasMutables `protobuf:"bytes,3,opt,name=has_mutables,json=hasMutables,proto3" json:"has_mutables"` -} - -func (m *Identity) Reset() { *m = Identity{} } -func (m *Identity) String() string { return proto.CompactTextString(m) } -func (*Identity) ProtoMessage() {} -func (*Identity) Descriptor() ([]byte, []int) { - return fileDescriptor_0c7982e5d5467bfd, []int{0} -} -func (m *Identity) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Identity) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Identity.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Identity) XXX_Merge(src proto.Message) { - xxx_messageInfo_Identity.Merge(m, src) -} -func (m *Identity) XXX_Size() int { - return m.Size() -} -func (m *Identity) XXX_DiscardUnknown() { - xxx_messageInfo_Identity.DiscardUnknown(m) -} - -var xxx_messageInfo_Identity proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Identity)(nil), "persistence_sdk.modules.identities.internal.mappable.Identity") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/mappable/identity.proto", fileDescriptor_0c7982e5d5467bfd) -} - -var fileDescriptor_0c7982e5d5467bfd = []byte{ - // 334 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0xd2, 0xb1, 0x4a, 0xc3, 0x40, - 0x00, 0x06, 0xe0, 0xa4, 0x2d, 0x22, 0xa9, 0x3a, 0x04, 0x87, 0xd2, 0xe1, 0x2a, 0x82, 0x20, 0x0e, - 0x77, 0xa8, 0xc5, 0x41, 0x9c, 0x6a, 0x07, 0x8b, 0x14, 0x41, 0x17, 0x71, 0xb0, 0x5c, 0x92, 0x23, - 0x39, 0xcc, 0xe5, 0x42, 0xee, 0x32, 0xf4, 0x0d, 0x3a, 0xfa, 0x08, 0x3e, 0x4e, 0xc7, 0x8e, 0x4e, - 0x22, 0xc9, 0x8b, 0x48, 0x2e, 0x49, 0x4d, 0x02, 0x85, 0x6c, 0x17, 0x92, 0xff, 0x4b, 0xfe, 0x9f, - 0x18, 0xf7, 0x21, 0x89, 0x04, 0x15, 0x92, 0x04, 0x36, 0x59, 0x08, 0xe7, 0x03, 0x31, 0xee, 0xc4, - 0x3e, 0x11, 0x88, 0x3a, 0x24, 0x90, 0x54, 0xd2, 0xec, 0x18, 0x48, 0x12, 0x05, 0xd8, 0x47, 0x0c, - 0x87, 0x21, 0xb6, 0x7c, 0x52, 0xde, 0x5c, 0xc2, 0x30, 0xe2, 0x92, 0x9b, 0xe3, 0x06, 0x02, 0x0b, - 0x04, 0xfe, 0x23, 0xb0, 0x44, 0x60, 0x89, 0x0c, 0x8f, 0x5d, 0xee, 0x72, 0x05, 0xa0, 0xec, 0x94, - 0x5b, 0xc3, 0x9b, 0xe6, 0x07, 0x09, 0xdb, 0x23, 0x0c, 0x23, 0x19, 0x61, 0x2a, 0x05, 0xb2, 0xb0, - 0x20, 0xc8, 0xc3, 0x62, 0xc6, 0x58, 0x2c, 0x33, 0x46, 0x14, 0xb9, 0x71, 0xbb, 0xdc, 0xbc, 0x9e, - 0xba, 0xd8, 0x95, 0x5a, 0x86, 0xa4, 0x08, 0x51, 0x27, 0x7f, 0xf6, 0x74, 0xd5, 0x31, 0xf6, 0x67, - 0x45, 0x71, 0xf3, 0xce, 0xe8, 0xd2, 0x85, 0x33, 0xd0, 0x4f, 0xf4, 0xf3, 0xfe, 0xd5, 0x19, 0x6c, - 0x0e, 0x90, 0x33, 0x50, 0x31, 0x30, 0x63, 0xe0, 0x6c, 0x3a, 0xe9, 0xad, 0x7f, 0x46, 0xda, 0x73, - 0x87, 0x4e, 0xcd, 0x77, 0xe3, 0xc8, 0xc3, 0x62, 0x41, 0xb7, 0x25, 0x06, 0x1d, 0x05, 0x5d, 0xee, - 0x84, 0x54, 0x8b, 0x5c, 0x7a, 0xa8, 0xb6, 0x2f, 0xd0, 0xc3, 0xda, 0x24, 0xe6, 0xab, 0x71, 0x90, - 0xf9, 0x5b, 0xbd, 0xab, 0x74, 0xd4, 0x52, 0x9f, 0xd7, 0xed, 0x7e, 0x65, 0xb6, 0xdb, 0xde, 0xea, - 0x6b, 0xa4, 0x4d, 0xdc, 0x75, 0x02, 0xf4, 0x4d, 0x02, 0xf4, 0xdf, 0x04, 0xe8, 0x9f, 0x29, 0xd0, - 0x36, 0x29, 0xd0, 0xbe, 0x53, 0xa0, 0xbd, 0xcd, 0x5d, 0x2a, 0xbd, 0xd8, 0x82, 0x36, 0x67, 0xa8, - 0xf2, 0xb6, 0xa7, 0x80, 0x54, 0x2f, 0x5f, 0xa6, 0x8f, 0xad, 0x7e, 0x34, 0x6b, 0x4f, 0x4d, 0x7f, - 0xfd, 0x17, 0x00, 0x00, 0xff, 0xff, 0x35, 0x49, 0x77, 0x4f, 0xa7, 0x02, 0x00, 0x00, -} - -func (m *Identity) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Identity) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Identity) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.HasMutables.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintIdentity(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.HasImmutables.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintIdentity(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintIdentity(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintIdentity(dAtA []byte, offset int, v uint64) int { - offset -= sovIdentity(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Identity) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovIdentity(uint64(l)) - l = m.HasImmutables.Size() - n += 1 + l + sovIdentity(uint64(l)) - l = m.HasMutables.Size() - n += 1 + l + sovIdentity(uint64(l)) - return n -} - -func sovIdentity(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozIdentity(x uint64) (n int) { - return sovIdentity(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Identity) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIdentity - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Identity: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Identity: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIdentity - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthIdentity - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthIdentity - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HasImmutables", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIdentity - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthIdentity - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthIdentity - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HasImmutables.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HasMutables", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIdentity - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthIdentity - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthIdentity - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HasMutables.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipIdentity(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthIdentity - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipIdentity(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdentity - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdentity - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdentity - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthIdentity - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupIdentity - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthIdentity - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthIdentity = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowIdentity = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupIdentity = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/mappable/mappable.go b/modules/identities/internal/mappable/mappable.go new file mode 100644 index 000000000..6822e9b93 --- /dev/null +++ b/modules/identities/internal/mappable/mappable.go @@ -0,0 +1,37 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mappable + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +type mappable struct { + documents.Identity +} + +var _ documents.Identity = (*mappable)(nil) + +func (identity mappable) GetKey() helpers.Key { + return key.NewKey(baseIDs.NewIdentityID(identity.GetClassificationID(), identity.GetImmutables())) +} +func (mappable) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, mappable{}) +} + +func NewMappable(identity documents.Identity) helpers.Mappable { + return mappable{ + Identity: identity, + } +} + +func Prototype() helpers.Mappable { + return mappable{} +} diff --git a/modules/identities/internal/mappable/mappable_test.go b/modules/identities/internal/mappable/mappable_test.go new file mode 100644 index 000000000..d8f160108 --- /dev/null +++ b/modules/identities/internal/mappable/mappable_test.go @@ -0,0 +1,131 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mappable + +import ( + "reflect" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/identities/internal/key" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/qualified" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +func createTestInput() (documents.Identity, ids.ClassificationID, qualified.Immutables, qualified.Mutables) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testIdentity := baseDocuments.NewIdentity(classificationID, immutables, mutables) + + return testIdentity, classificationID, immutables, mutables +} + +func TestNewMappable(t *testing.T) { + _, classificationID, immutables, mutables := createTestInput() + type args struct { + classificationID ids.ClassificationID + immutables qualified.Immutables + mutables qualified.Mutables + } + tests := []struct { + name string + args args + want mappable + }{ + {"+ve", args{classificationID, immutables, mutables}, mappable{Identity: baseDocuments.NewIdentity(classificationID, immutables, mutables)}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewMappable(baseDocuments.NewIdentity(tt.args.classificationID, tt.args.immutables, tt.args.mutables)); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewIdentity() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Mappable + }{ + {"+ve", mappable{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_identity_GetKey(t *testing.T) { + testIdentity, _, _, _ := createTestInput() + + type fields struct { + Document documents.Identity + } + tests := []struct { + name string + fields fields + want helpers.Key + wantPanic bool + }{ + {"+ve", fields{testIdentity}, key.NewKey(baseIds.NewIdentityID(testIdentity.GetClassificationID(), testIdentity.GetImmutables())), false}, + {"panic case nil", fields{nil}, nil, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + identity := mappable{ + Identity: tt.fields.Document, + } + if tt.wantPanic { + require.Panics(t, func() { + identity.GetKey() + }) + } else if got := identity.GetKey(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetKey() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_identity_RegisterCodec(t *testing.T) { + testIdentity, _, _, _ := createTestInput() + + type fields struct { + Document documents.Identity + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testIdentity}, args{codec.New()}}, + {"+ve nil", fields{nil}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + id := mappable{ + Identity: tt.fields.Document, + } + id.RegisterCodec(tt.args.codec) + }) + } +} diff --git a/modules/identities/internal/mappable/prototype.go b/modules/identities/internal/mappable/prototype.go deleted file mode 100644 index 389f5f8c7..000000000 --- a/modules/identities/internal/mappable/prototype.go +++ /dev/null @@ -1,12 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import "github.com/persistenceOne/persistenceSDK/schema/helpers" - -func Prototype() helpers.Mappable { - return &Identity{} -} diff --git a/modules/identities/internal/mapper/prototype.go b/modules/identities/internal/mapper/prototype.go new file mode 100644 index 000000000..cb7cdb003 --- /dev/null +++ b/modules/identities/internal/mapper/prototype.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mapper + +import ( + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Mapper { + return baseHelpers.NewMapper(key.Prototype, mappable.Prototype) +} diff --git a/modules/identities/internal/mapper/prototype_test.go b/modules/identities/internal/mapper/prototype_test.go new file mode 100644 index 000000000..46e203b91 --- /dev/null +++ b/modules/identities/internal/mapper/prototype_test.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mapper + +import ( + "reflect" + "testing" + + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Mapper + }{ + // TODO: Same data and type but fails to equate + {"+ve", baseHelpers.NewMapper(key.Prototype, mappable.Prototype)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/identities/internal/module/constants.go b/modules/identities/internal/module/constants.go new file mode 100644 index 000000000..def19dfef --- /dev/null +++ b/modules/identities/internal/module/constants.go @@ -0,0 +1,12 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package module + +import ( + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +const Name = "identities" + +var StoreKeyPrefix = constants.IdentitiesStoreKeyPrefix diff --git a/modules/identities/internal/parameters/dummy/constants.go b/modules/identities/internal/parameters/dummy/constants.go new file mode 100644 index 000000000..770f437dc --- /dev/null +++ b/modules/identities/internal/parameters/dummy/constants.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package dummy + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +var ID = baseIDs.NewStringID("dummy") + +var DefaultData = baseData.NewDecData(sdkTypes.SmallestDec()) diff --git a/modules/identities/internal/parameters/dummy/parameter.go b/modules/identities/internal/parameters/dummy/parameter.go index e78fdc8d0..5ffc0eaf5 100644 --- a/modules/identities/internal/parameters/dummy/parameter.go +++ b/modules/identities/internal/parameters/dummy/parameter.go @@ -1,59 +1,10 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "encoding/json" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" ) -var _ types.Parameter = (*DummyParameter)(nil) - -func (dummyParameter DummyParameter) String() string { - bytes, Error := json.Marshal(dummyParameter) - if Error != nil { - return Error.Error() - } - return string(bytes) -} - -func (dummyParameter DummyParameter) Equal(compareParameter types.Parameter) bool { - if compareParameter == nil { - return false - } - return dummyParameter.Data.Compare(compareParameter.GetData()) == 0 -} - -func (dummyParameter DummyParameter) Validate() error { - return validator(dummyParameter) -} - -func (dummyParameter DummyParameter) GetID() types.ID { - return &dummyParameter.ID -} - -func (dummyParameter DummyParameter) GetData() types.Data { - return &dummyParameter.Data -} - -func (dummyParameter DummyParameter) GetValidator() func(interface{}) error { - return validator -} - -func (dummyParameter DummyParameter) Mutate(data types.Data) types.Parameter { - decData, _ := data.AsDec() - dummyParameter.Data = *base.NewDummyDecData(decData) - return &dummyParameter -} - -func NewParameter(id types.ID, data types.Data) *DummyParameter { - decData, _ := data.AsDec() - return &DummyParameter{ - ID: *base.NewID(id.String()), - Data: *base.NewDummyDecData(decData), - } -} +var Parameter = baseTypes.NewParameter(ID, DefaultData, validator) diff --git a/modules/identities/internal/parameters/dummy/parameter.pb.go b/modules/identities/internal/parameters/dummy/parameter.pb.go deleted file mode 100644 index 6aaa83d6b..000000000 --- a/modules/identities/internal/parameters/dummy/parameter.pb.go +++ /dev/null @@ -1,367 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/parameters/dummy/parameter.proto - -package dummy - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type DummyParameter struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - Data base.DecData `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` -} - -func (m *DummyParameter) Reset() { *m = DummyParameter{} } -func (*DummyParameter) ProtoMessage() {} -func (*DummyParameter) Descriptor() ([]byte, []int) { - return fileDescriptor_bbcbfdb5c78cb7a4, []int{0} -} -func (m *DummyParameter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DummyParameter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DummyParameter.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DummyParameter) XXX_Merge(src proto.Message) { - xxx_messageInfo_DummyParameter.Merge(m, src) -} -func (m *DummyParameter) XXX_Size() int { - return m.Size() -} -func (m *DummyParameter) XXX_DiscardUnknown() { - xxx_messageInfo_DummyParameter.DiscardUnknown(m) -} - -var xxx_messageInfo_DummyParameter proto.InternalMessageInfo - -func init() { - proto.RegisterType((*DummyParameter)(nil), "persistence_sdk.modules.identities.parameters.dummy.DummyParameter") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/parameters/dummy/parameter.proto", fileDescriptor_bbcbfdb5c78cb7a4) -} - -var fileDescriptor_bbcbfdb5c78cb7a4 = []byte{ - // 303 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xf2, 0x29, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4c, 0x49, 0xcd, 0x2b, 0xc9, 0x2c, 0xc9, 0x04, 0x31, 0xf3, 0x4a, - 0x52, 0x8b, 0xf2, 0x12, 0x73, 0xf4, 0x0b, 0x12, 0x8b, 0x12, 0x73, 0x53, 0x4b, 0x52, 0x8b, 0x8a, - 0xf5, 0x53, 0x4a, 0x73, 0x73, 0x2b, 0x11, 0x02, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0xc6, - 0x68, 0xa6, 0xe9, 0x41, 0x4d, 0xd3, 0x43, 0x98, 0xa6, 0x87, 0x30, 0x44, 0x0f, 0x6c, 0x88, 0x94, - 0x48, 0x7a, 0x7e, 0x7a, 0x3e, 0x58, 0xbf, 0x3e, 0x88, 0x05, 0x31, 0x4a, 0x4a, 0x1f, 0xdd, 0x61, - 0xc5, 0xc9, 0x19, 0xa9, 0xb9, 0x89, 0xfa, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0xfa, 0x49, 0x89, 0xc5, - 0xa9, 0xfa, 0x29, 0xa9, 0xc9, 0x2e, 0x89, 0x25, 0x89, 0x50, 0x0d, 0x5a, 0x84, 0x35, 0x64, 0xa6, - 0x40, 0xd4, 0x2a, 0xcd, 0x63, 0xe4, 0xe2, 0x73, 0x01, 0x59, 0x1e, 0x00, 0x73, 0x8c, 0x90, 0x0d, - 0x17, 0x73, 0x66, 0x7c, 0x8a, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0xaa, 0x1e, 0xba, 0x47, - 0x20, 0x86, 0xe9, 0x81, 0x0d, 0xd3, 0x03, 0x19, 0xa6, 0xe7, 0xe9, 0xe2, 0xc4, 0x72, 0xe2, 0x9e, - 0x3c, 0x43, 0x10, 0x53, 0xa6, 0x8b, 0x90, 0x0b, 0x17, 0x4b, 0x4a, 0x62, 0x49, 0xa2, 0x04, 0x13, - 0x58, 0xbb, 0x16, 0x11, 0xda, 0x5d, 0x20, 0x8e, 0x87, 0x9a, 0x01, 0xd6, 0x6d, 0xc5, 0xd1, 0xb1, - 0x40, 0x9e, 0x61, 0xc6, 0x02, 0x79, 0x06, 0xa7, 0xfc, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, - 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, - 0x96, 0x63, 0x88, 0x0a, 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0x45, 0x0e, - 0x22, 0xff, 0xbc, 0x54, 0x64, 0x6e, 0xb0, 0x8b, 0x37, 0x49, 0x31, 0x99, 0xc4, 0x06, 0x0e, 0x18, - 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xba, 0xed, 0x5d, 0xac, 0x10, 0x02, 0x00, 0x00, -} - -func (m *DummyParameter) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DummyParameter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DummyParameter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Data.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintParameter(dAtA []byte, offset int, v uint64) int { - offset -= sovParameter(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *DummyParameter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovParameter(uint64(l)) - l = m.Data.Size() - n += 1 + l + sovParameter(uint64(l)) - return n -} - -func sovParameter(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParameter(x uint64) (n int) { - return sovParameter(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *DummyParameter) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DummyParameter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DummyParameter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParameter(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParameter - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParameter(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParameter - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParameter - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParameter - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParameter = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParameter = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParameter = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/parameters/dummy/prototype.go b/modules/identities/internal/parameters/dummy/prototype.go deleted file mode 100644 index b390a673e..000000000 --- a/modules/identities/internal/parameters/dummy/prototype.go +++ /dev/null @@ -1,3 +0,0 @@ -package dummy - -var Parameter = NewParameter(ID, DefaultData) diff --git a/modules/identities/internal/parameters/dummy/validator.go b/modules/identities/internal/parameters/dummy/validator.go index cc0d80a52..2bb100018 100644 --- a/modules/identities/internal/parameters/dummy/validator.go +++ b/modules/identities/internal/parameters/dummy/validator.go @@ -1,32 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/parameters" ) func validator(i interface{}) error { switch value := i.(type) { - case DummyParameter: - data, Error := value.GetData().AsDec() - if Error != nil || value.GetID().Compare(ID) != 0 || data.IsNegative() { - return errors.InvalidParameter + case parameters.Parameter: + if value.GetID().Compare(ID) != 0 || value.GetData().(data.DecData).Get().IsNegative() { + return constants.InvalidParameter } return nil - case types.Data: - data, Error := value.AsDec() - if Error != nil || data.IsNegative() { - return errors.InvalidParameter + case data.DecData: + if value.Get().IsNegative() { + return constants.InvalidParameter } return nil default: - return errors.IncorrectFormat + return constants.IncorrectFormat } } diff --git a/modules/identities/internal/parameters/dummy/validator_test.go b/modules/identities/internal/parameters/dummy/validator_test.go new file mode 100644 index 000000000..63d260ffb --- /dev/null +++ b/modules/identities/internal/parameters/dummy/validator_test.go @@ -0,0 +1,38 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package dummy + +import ( + "testing" + + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" +) + +func Test_validator(t *testing.T) { + type args struct { + i interface{} + } + tests := []struct { + name string + args args + wantErr bool + }{ + + {"+ve with nil", args{Parameter}, false}, + {"-ve wrong parameter Type", args{baseTypes.NewParameter(baseIDs.NewStringID("newID"), baseData.NewDecData(sdkTypes.NewDec(-1)), validator)}, true}, + {"-ve wrong parameter Type", args{baseTypes.NewParameter(baseIDs.NewStringID("newID"), baseData.NewStringData("newStringData"), validator)}, true}, + {"+ve empty string", args{baseIDs.NewStringID("")}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := validator(tt.args.i); (err != nil) != tt.wantErr { + t.Errorf("validator() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/modules/identities/internal/parameters/prototype.go b/modules/identities/internal/parameters/prototype.go new file mode 100644 index 000000000..30b43f1f3 --- /dev/null +++ b/modules/identities/internal/parameters/prototype.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package parameters + +import ( + "github.com/AssetMantle/modules/modules/identities/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Parameters { + return baseHelpers.NewParameters(dummy.Parameter) +} diff --git a/modules/identities/internal/parameters/prototype_test.go b/modules/identities/internal/parameters/prototype_test.go new file mode 100644 index 000000000..a311265b7 --- /dev/null +++ b/modules/identities/internal/parameters/prototype_test.go @@ -0,0 +1,29 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package parameters + +import ( + "reflect" + "testing" + + "github.com/AssetMantle/modules/modules/identities/internal/parameters/dummy" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want string + }{ + + {"+ve", baseHelpers.NewParameters(dummy.Parameter).String()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype().String(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/identities/internal/queries/identity/grpc_query.go b/modules/identities/internal/queries/identity/grpc_query.go deleted file mode 100644 index 5d23d0fdc..000000000 --- a/modules/identities/internal/queries/identity/grpc_query.go +++ /dev/null @@ -1,29 +0,0 @@ -package identity - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/key" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type queryServer struct { - queryKeeper -} - -var _ QueryServer = queryServer{} - -func (queryServer queryServer) Enquire(ctx context.Context, queryRequest *QueryRequest) (*QueryResponse, error) { - cntx := sdkTypes.UnwrapSDKContext(ctx) - - keyr := key.FromID(base.NewID(queryRequest.IdentityID.String())) - - collection := queryServer.queryKeeper.mapper.NewCollection(cntx) - response := newQueryResponse(collection.Fetch(keyr), nil) - return &response, response.GetError() - -} - -func NewQueryServerImpl(keeper queryKeeper) QueryServer { - return &queryServer{keeper} -} diff --git a/modules/identities/internal/queries/identity/keeper.go b/modules/identities/internal/queries/identity/keeper.go new file mode 100644 index 000000000..9832285e3 --- /dev/null +++ b/modules/identities/internal/queries/identity/keeper.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package identity + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/schema/helpers" +) + +type queryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.QueryKeeper = (*queryKeeper)(nil) + +func (queryKeeper queryKeeper) Enquire(context sdkTypes.Context, queryRequest helpers.QueryRequest) helpers.QueryResponse { + return newQueryResponse(queryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(queryRequestFromInterface(queryRequest).IdentityID)), nil) +} + +func (queryKeeper queryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + queryKeeper.mapper = mapper + return queryKeeper +} + +func keeperPrototype() helpers.QueryKeeper { + return queryKeeper{} +} diff --git a/modules/identities/internal/queries/identity/query.go b/modules/identities/internal/queries/identity/query.go new file mode 100644 index 000000000..8004579ab --- /dev/null +++ b/modules/identities/internal/queries/identity/query.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package identity + +import ( + "github.com/AssetMantle/modules/modules/identities/internal/module" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Query = baseHelpers.NewQuery( + "identities", + "", + "", + + module.Name, + + requestPrototype, + responsePrototype, + keeperPrototype, + + constants.IdentityID, +) diff --git a/modules/identities/internal/queries/identity/query.pb.go b/modules/identities/internal/queries/identity/query.pb.go deleted file mode 100644 index 581394f39..000000000 --- a/modules/identities/internal/queries/identity/query.pb.go +++ /dev/null @@ -1,674 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/queries/identity/query.proto - -package identity - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - github_com_persistenceOne_persistenceSDK_schema_helpers "github.com/persistenceOne/persistenceSDK/schema/helpers" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type QueryRequest struct { - IdentityID base.ID `protobuf:"bytes,1,opt,name=identity_i_d,json=identityID,proto3" json:"identity_i_d" valid:"required~required IdentityID missing"` -} - -func (m *QueryRequest) Reset() { *m = QueryRequest{} } -func (m *QueryRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRequest) ProtoMessage() {} -func (*QueryRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_3d54734af8667f22, []int{0} -} -func (m *QueryRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRequest.Merge(m, src) -} -func (m *QueryRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRequest proto.InternalMessageInfo - -type QueryResponse struct { - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` - List []github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable `protobuf:"bytes,3,rep,name=list,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable" json:"list"` -} - -func (m *QueryResponse) Reset() { *m = QueryResponse{} } -func (m *QueryResponse) String() string { return proto.CompactTextString(m) } -func (*QueryResponse) ProtoMessage() {} -func (*QueryResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3d54734af8667f22, []int{1} -} -func (m *QueryResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryResponse.Merge(m, src) -} -func (m *QueryResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryRequest)(nil), "persistence_sdk.modules.identities.internal.queries.identity.QueryRequest") - proto.RegisterType((*QueryResponse)(nil), "persistence_sdk.modules.identities.internal.queries.identity.QueryResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/queries/identity/query.proto", fileDescriptor_3d54734af8667f22) -} - -var fileDescriptor_3d54734af8667f22 = []byte{ - // 469 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x93, 0xbf, 0x8b, 0x13, 0x41, - 0x14, 0xc7, 0x77, 0xee, 0x3c, 0xef, 0x6e, 0x3c, 0x9b, 0xe5, 0x8a, 0x10, 0x64, 0x77, 0x59, 0x10, - 0x82, 0xc8, 0x0c, 0x9c, 0x56, 0x87, 0x85, 0x84, 0x08, 0x17, 0x0f, 0x11, 0x57, 0x6c, 0x44, 0x08, - 0x9b, 0xdd, 0xc7, 0x66, 0x70, 0x33, 0xb3, 0x99, 0x37, 0x2b, 0xa4, 0xd0, 0xc2, 0xca, 0x52, 0xb0, - 0xb0, 0xbd, 0xce, 0x7f, 0xe5, 0x0a, 0x8b, 0x80, 0x20, 0x62, 0x11, 0x24, 0xb1, 0xb0, 0xf6, 0x2f, - 0x90, 0xfd, 0x65, 0x62, 0x2a, 0xc5, 0xeb, 0xde, 0x9b, 0xef, 0xee, 0x67, 0xbf, 0xdf, 0x37, 0x6f, - 0xe9, 0x49, 0x06, 0x1a, 0x05, 0x1a, 0x90, 0x11, 0x0c, 0x30, 0x7e, 0xce, 0xc7, 0x2a, 0xce, 0x53, - 0x40, 0x2e, 0x62, 0x90, 0x46, 0x18, 0x51, 0x94, 0xd2, 0x80, 0x96, 0x61, 0xca, 0x27, 0x39, 0x68, - 0xb1, 0xd2, 0xa6, 0xe5, 0xc1, 0x94, 0x65, 0x5a, 0x19, 0x65, 0xdf, 0xd9, 0x20, 0xb1, 0x9a, 0xc4, - 0x56, 0x24, 0xd6, 0x90, 0x58, 0x4d, 0x6a, 0xb4, 0x69, 0xfb, 0x30, 0x51, 0x89, 0x2a, 0x41, 0xbc, - 0xa8, 0x2a, 0x66, 0xfb, 0x5a, 0xa2, 0x54, 0x92, 0x02, 0x0f, 0x33, 0xc1, 0x43, 0x29, 0x95, 0x09, - 0x8d, 0x50, 0x12, 0x6b, 0xf5, 0xc6, 0xa6, 0x77, 0x8c, 0x46, 0x30, 0x0e, 0xb9, 0x99, 0x66, 0x80, - 0x7c, 0x18, 0x22, 0x70, 0x11, 0x57, 0xcf, 0xfa, 0xef, 0x09, 0x3d, 0x78, 0x54, 0xb8, 0x0d, 0x60, - 0x92, 0x03, 0x1a, 0xfb, 0x25, 0x3d, 0x68, 0x3e, 0x3e, 0x10, 0x83, 0xb8, 0x45, 0x3c, 0xd2, 0xb9, - 0x72, 0x74, 0x9d, 0x6d, 0xa6, 0xa8, 0x98, 0xac, 0x64, 0xb2, 0x82, 0xc9, 0xfa, 0xbd, 0xee, 0xed, - 0xf3, 0xb9, 0x6b, 0xfd, 0x9c, 0xbb, 0x37, 0x5f, 0x84, 0xa9, 0x88, 0x8f, 0x7d, 0x0d, 0x93, 0x5c, - 0x68, 0x88, 0x5f, 0x35, 0x85, 0xd7, 0xaf, 0xd9, 0xfd, 0x9e, 0x37, 0x16, 0x88, 0x42, 0x26, 0x7e, - 0x40, 0xc5, 0xef, 0xc3, 0xe3, 0xbd, 0x37, 0x67, 0xae, 0xf5, 0xe3, 0xcc, 0xb5, 0xfc, 0x0f, 0x84, - 0x5e, 0xad, 0x9d, 0x61, 0xa6, 0x24, 0x82, 0xdd, 0xa2, 0xbb, 0x98, 0x47, 0x11, 0x20, 0x96, 0xae, - 0xf6, 0x82, 0xa6, 0xb5, 0x0f, 0xe9, 0x0e, 0x68, 0xad, 0x74, 0x6b, 0xcb, 0x23, 0x9d, 0xfd, 0xa0, - 0x6a, 0xec, 0x67, 0xf4, 0x52, 0x2a, 0xd0, 0xb4, 0xb6, 0xbd, 0xed, 0xce, 0x7e, 0xf7, 0xa4, 0xf0, - 0xf6, 0x75, 0xee, 0xde, 0x4d, 0x84, 0x19, 0xe5, 0x43, 0x16, 0xa9, 0x31, 0x5f, 0x0b, 0xf5, 0x50, - 0xc2, 0x7a, 0xfb, 0xb8, 0x77, 0xda, 0x8c, 0x6d, 0x04, 0x69, 0x21, 0xb0, 0x07, 0x61, 0x96, 0x85, - 0xc3, 0x14, 0x82, 0x92, 0xba, 0x72, 0x7a, 0xf4, 0x99, 0xd0, 0x9d, 0xd2, 0xa9, 0xfd, 0x91, 0xd0, - 0xdd, 0x7b, 0xb2, 0x8c, 0x6a, 0xdf, 0x67, 0xff, 0x73, 0xf1, 0x6c, 0xfd, 0x52, 0xda, 0xa7, 0x17, - 0xc2, 0xaa, 0xc6, 0xe8, 0x77, 0x5e, 0x7f, 0xfa, 0xfe, 0x6e, 0xcb, 0xb7, 0xbd, 0xf5, 0xbc, 0x7f, - 0xec, 0x75, 0xfd, 0x5e, 0x57, 0x9d, 0x2f, 0x1c, 0x32, 0x5b, 0x38, 0xe4, 0xdb, 0xc2, 0x21, 0x6f, - 0x97, 0x8e, 0x35, 0x5b, 0x3a, 0xd6, 0x97, 0xa5, 0x63, 0x3d, 0x7d, 0xf2, 0xd7, 0x43, 0xfc, 0x97, - 0xff, 0x66, 0x78, 0xb9, 0x5c, 0xca, 0x5b, 0xbf, 0x02, 0x00, 0x00, 0xff, 0xff, 0x57, 0x43, 0x0b, - 0x7c, 0x7e, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) { - out := new(QueryResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.identities.internal.queries.identity.Query/Enquire", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - Enquire(context.Context, *QueryRequest) (*QueryResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Enquire(ctx context.Context, req *QueryRequest) (*QueryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Enquire not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Enquire_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Enquire(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.identities.internal.queries.identity.Query/Enquire", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Enquire(ctx, req.(*QueryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.identities.internal.queries.identity.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Enquire", - Handler: _Query_Enquire_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/identities/internal/queries/identity/query.proto", -} - -func (m *QueryRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.IdentityID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.List) > 0 { - for iNdEx := len(m.List) - 1; iNdEx >= 0; iNdEx-- { - { - size := m.List[iNdEx].Size() - i -= size - if _, err := m.List[iNdEx].MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Error) > 0 { - i -= len(m.Error) - copy(dAtA[i:], m.Error) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Error))) - i-- - dAtA[i] = 0x12 - } - if m.Success { - i-- - if m.Success { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.IdentityID.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Success { - n += 2 - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.List) > 0 { - for _, e := range m.List { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IdentityID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IdentityID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Success = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field List", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var v github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable - m.List = append(m.List, v) - if err := m.List[len(m.List)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/queries/identity/query.pb.gw.go b/modules/identities/internal/queries/identity/query.pb.gw.go deleted file mode 100644 index 1859bc553..000000000 --- a/modules/identities/internal/queries/identity/query.pb.gw.go +++ /dev/null @@ -1,166 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/queries/identity/query.proto - -/* -Package identity is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package identity - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage - -var ( - filter_Query_Enquire_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Enquire(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Enquire(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features (such as grpc.SendHeader, etc) to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Enquire_0(rctx, inboundMarshaler, server, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Enquire_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Enquire_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"persistence", "identities", "identity"}, "", runtime.AssumeColonVerbOpt(true))) -) - -var ( - forward_Query_Enquire_0 = runtime.ForwardResponseMessage -) diff --git a/modules/identities/internal/queries/identity/request.go b/modules/identities/internal/queries/identity/request.go index 40a70a498..758de6439 100644 --- a/modules/identities/internal/queries/identity/request.go +++ b/modules/identities/internal/queries/identity/request.go @@ -1,80 +1,74 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package identity import ( "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/cosmos/cosmos-sdk/client/context" + + "github.com/AssetMantle/modules/modules/identities/internal/common" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" ) -var _ helpers.QueryRequest = (*QueryRequest)(nil) +type queryRequest struct { + ids.IdentityID `json:"identityID" valid:"required~required field identityID missing"` +} + +var _ helpers.QueryRequest = (*queryRequest)(nil) -// QueryRequest godoc -// @Summary Query identities using identity id -// @Descrption Able to query the asset +// Validate godoc +// @Summary Search for an identity by identity ID +// @Description Able to query the asset // @Accept json // @Produce json // @Tags Identities -// @Param identityID path string true "identity ID" -// @Success 200 {object} queryResponse "Sucessful query response" -// @Failure default {object} queryResponse "An unexpected error response." +// @Param identityID path string true "Query identity using identityID" +// @Success 200 {object} queryResponse "Message for a successful response." +// @Failure default {object} queryResponse "Message for an unexpected error response." // @Router /identities/identities/{identityID} [get] -func (queryRequest QueryRequest) Validate() error { - _, Error := govalidator.ValidateStruct(queryRequest) - return Error -} - -func (queryRequest QueryRequest) FromCLI(cliCommand helpers.CLICommand, _ client.Context) helpers.QueryRequest { - return newQueryRequest(base.NewID(cliCommand.ReadString(flags.IdentityID))) -} - -func (queryRequest QueryRequest) FromMap(vars map[string]string) helpers.QueryRequest { - return newQueryRequest(base.NewID(vars[Query.GetName()])) +func (queryRequest queryRequest) Validate() error { + _, err := govalidator.ValidateStruct(queryRequest) + return err } -func (queryRequest QueryRequest) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryRequest) +func (queryRequest) FromCLI(cliCommand helpers.CLICommand, _ context.CLIContext) (helpers.QueryRequest, error) { + if identityID, err := baseIDs.ReadIdentityID(cliCommand.ReadString(constants.IdentityID)); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(identityID), nil + } } - -func (queryRequest QueryRequest) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryRequest, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest) FromMap(vars map[string]string) (helpers.QueryRequest, error) { + if identityID, err := baseIDs.ReadIdentityID(vars[Query.GetName()]); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(identityID), nil } - - return queryRequest, nil } -func (queryRequest QueryRequest) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryRequest) +func (queryRequest queryRequest) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryRequest) } - -func (queryRequest QueryRequest) LegacyAminoDecode(bytes []byte) (helpers.QueryRequest, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest queryRequest) Decode(bytes []byte) (helpers.QueryRequest, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryRequest); err != nil { + return nil, err } return queryRequest, nil } func requestPrototype() helpers.QueryRequest { - return QueryRequest{} + return queryRequest{} } - -func queryRequestFromInterface(request helpers.QueryRequest) QueryRequest { +func queryRequestFromInterface(request helpers.QueryRequest) queryRequest { switch value := request.(type) { - case QueryRequest: + case queryRequest: return value default: - return QueryRequest{} + return queryRequest{} } } - -func newQueryRequest(identityID types.ID) helpers.QueryRequest { - return QueryRequest{IdentityID: *base.NewID(identityID.String())} +func newQueryRequest(identityID ids.IdentityID) helpers.QueryRequest { + return queryRequest{IdentityID: identityID} } diff --git a/modules/identities/internal/queries/identity/request_test.go b/modules/identities/internal/queries/identity/request_test.go index cb1c9dc91..ff28232b7 100644 --- a/modules/identities/internal/queries/identity/request_test.go +++ b/modules/identities/internal/queries/identity/request_test.go @@ -1,59 +1,303 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package identity import ( - "github.com/cosmos/cosmos-sdk/client" + "reflect" + "testing" + + "github.com/spf13/viper" + + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/common" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" - "testing" + + "github.com/AssetMantle/modules/modules/identities/internal/common" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" ) -func Test_Identity_Request(t *testing.T) { +func createTestInput() (ids.IdentityID, ids.IdentityID) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + emptyMutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID"), baseData.NewStringData("")))) + + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testIdentity := baseIDs.NewIdentityID(testClassificationID, immutables) + + emptyTestClassificationID := baseIDs.NewClassificationID(immutables, emptyMutables) + emptyTestIdentity := baseIDs.NewIdentityID(emptyTestClassificationID, immutables) - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + return testIdentity, emptyTestIdentity +} + +func Test_newQueryRequest(t *testing.T) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() + // vars := make(map[string]string) + // vars["identities"] = "randomString" + // cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.IdentityID}) + // cliContext := context.NewCLIContext().WithCodec(Codec) + testIdentity, emptyTestIdentity := createTestInput() + + type args struct { + identityID ids.IdentityID + } + tests := []struct { + name string + args args + want helpers.QueryRequest + }{ + + {"+ve", args{testIdentity}, queryRequest{testIdentity}}, + {"+ve with empty String", args{emptyTestIdentity}, queryRequest{emptyTestIdentity}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newQueryRequest(tt.args.identityID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newQueryRequest() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequestFromInterface(t *testing.T) { + testIdentity, emptyTestIdentity := createTestInput() + type args struct { + request helpers.QueryRequest + } + tests := []struct { + name string + args args + want queryRequest + }{ - testIdentityID := base.NewID("IdentityID") - testQueryRequest := newQueryRequest(testIdentityID) - require.Equal(t, nil, testQueryRequest.Validate()) - require.Equal(t, queryRequest{}, requestPrototype()) + {"+ve", args{newQueryRequest(testIdentity)}, queryRequest{testIdentity}}, + {"+ve with empty string", args{newQueryRequest(emptyTestIdentity)}, queryRequest{emptyTestIdentity}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := queryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("queryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.IdentityID}) - cliContext := context.NewCLIContext().WithCodec(Codec) - require.Equal(t, newQueryRequest(base.NewID("")), queryRequest{}.FromCLI(cliCommand, cliContext)) +func Test_queryRequest_Decode(t *testing.T) { + testIdentity, emptyTestIdentity := createTestInput() + testQueryRequest := newQueryRequest(testIdentity) + encodedRequest, err := testQueryRequest.Encode() + require.Nil(t, err) + randomDecode, _ := queryRequest{emptyTestIdentity}.Encode() + type fields struct { + IdentityID ids.IdentityID + } + type args struct { + bytes []byte + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testIdentity}, args{encodedRequest}, testQueryRequest, false}, + {"+ve", fields{emptyTestIdentity}, args{randomDecode}, queryRequest{emptyTestIdentity}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + IdentityID: tt.fields.IdentityID, + } + got, err := queryRequest.Decode(tt.args.bytes) + if (err != nil) != tt.wantErr { + t.Errorf("Decode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Decode() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequest_Encode(t *testing.T) { + testIdentity, emptyTestIdentity := createTestInput() + byteArr, _ := common.Codec.MarshalJSON(newQueryRequest(testIdentity)) + byteArr2, _ := common.Codec.MarshalJSON(newQueryRequest(emptyTestIdentity)) + + type fields struct { + IdentityID ids.IdentityID + } + tests := []struct { + name string + fields fields + want []byte + wantErr bool + }{ + + {"+ve", fields{testIdentity}, byteArr, false}, + {"+ve with empty String ID", fields{emptyTestIdentity}, byteArr2, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + IdentityID: tt.fields.IdentityID, + } + got, err := queryRequest.Encode() + if (err != nil) != tt.wantErr { + t.Errorf("Encode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Encode() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequest_FromCLI(t *testing.T) { + testIdentity, _ := createTestInput() + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.IdentityID}) + viper.Set(constants.IdentityID.GetName(), testIdentity.String()) + type fields struct { + IdentityID ids.IdentityID + } + type args struct { + cliCommand helpers.CLICommand + in1 context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testIdentity}, args{cliCommand, context.NewCLIContext()}, newQueryRequest(testIdentity), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + IdentityID: tt.fields.IdentityID, + } + if got, err := queryRequest.FromCLI(tt.args.cliCommand, tt.args.in1); !reflect.DeepEqual(got, tt.want) { + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + } + }) + } +} + +func Test_queryRequest_FromMap(t *testing.T) { vars := make(map[string]string) - vars["identities"] = "randomString" - require.Equal(t, newQueryRequest(base.NewID("randomString")), queryRequest{}.FromMap(vars)) - - encodedRequest, Error := testQueryRequest.LegacyAminoEncode() - encodedResult, _ := common.LegacyAminoCodec.MarshalJSON(testQueryRequest) - require.Equal(t, encodedResult, encodedRequest) - require.Nil(t, Error) - - decodedRequest, Error := queryRequest{}.LegacyAminoDecode(encodedRequest) - require.Equal(t, testQueryRequest, decodedRequest) - require.Equal(t, nil, Error) - - randomDecode, _ := queryRequest{}.LegacyAminoDecode(base.NewID("").Bytes()) - require.Equal(t, nil, randomDecode) - require.Equal(t, testQueryRequest, queryRequestFromInterface(testQueryRequest)) - require.Equal(t, queryRequest{}, queryRequestFromInterface(nil)) + vars["identities"] = "9UNIA3_tulK2vRE0nSmsHKNzhDxoCBHI4z8XXfLO1FM=" + vars2 := make(map[string]string) + vars2["identities"] = "qlFr8g0R-Qe6CxKcU5Ncdj7kAnSEp8Wq6sckkmznGiI=" + testIdentity, err := baseIDs.ReadIdentityID(vars["identities"]) + require.NoError(t, err) + emptyTestIdentity, err := baseIDs.ReadIdentityID(vars2["identities"]) + require.NoError(t, err) + type fields struct { + IdentityID ids.IdentityID + } + type args struct { + vars map[string]string + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + + {"+ve", fields{testIdentity}, args{vars: vars}, newQueryRequest(testIdentity), false}, + {"+ve with empty IdentityID", fields{emptyTestIdentity}, args{vars: vars2}, newQueryRequest(emptyTestIdentity), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + IdentityID: tt.fields.IdentityID, + } + if got, err := queryRequest.FromMap(tt.args.vars); !reflect.DeepEqual(got, tt.want) { + if (err != nil) != tt.wantErr { + t.Errorf("FromMap() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromMap() got = %v, want %v", got, tt.want) + } + + } + }) + } +} + +func Test_queryRequest_Validate(t *testing.T) { + testIdentity, emptyTestIdentity := createTestInput() + type fields struct { + IdentityID ids.IdentityID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + + {"+ve", fields{testIdentity}, false}, + {"+ve with empty IdentityID", fields{emptyTestIdentity}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + IdentityID: tt.fields.IdentityID, + } + if err := queryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryRequest + }{ + + {"+ve", queryRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/identities/internal/queries/identity/response.go b/modules/identities/internal/queries/identity/response.go index 51c3fdfbe..eae3717fa 100644 --- a/modules/identities/internal/queries/identity/response.go +++ b/modules/identities/internal/queries/identity/response.go @@ -1,64 +1,49 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package identity import ( - "errors" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/identities/internal/common" + "github.com/AssetMantle/modules/schema/helpers" ) -var _ helpers.QueryResponse = (*QueryResponse)(nil) +type queryResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` + List []helpers.Mappable `json:"list"` +} + +var _ helpers.QueryResponse = (*queryResponse)(nil) -func (queryResponse QueryResponse) IsSuccessful() bool { +func (queryResponse queryResponse) IsSuccessful() bool { return queryResponse.Success } -func (queryResponse QueryResponse) GetError() error { - return errors.New(queryResponse.Error) +func (queryResponse queryResponse) GetError() error { + return queryResponse.Error } -func (queryResponse QueryResponse) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryResponse) +func (queryResponse queryResponse) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryResponse) } -func (queryResponse QueryResponse) LegacyAminoDecode(bytes []byte) (helpers.QueryResponse, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error +func (queryResponse queryResponse) Decode(bytes []byte) (helpers.QueryResponse, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryResponse); err != nil { + return nil, err } - return &queryResponse, nil -} -func (queryResponse QueryResponse) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryResponse) -} - -func (queryResponse QueryResponse) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryResponse, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error - } - return &queryResponse, nil + return queryResponse, nil } - func responsePrototype() helpers.QueryResponse { - return &QueryResponse{} + return queryResponse{} } - -func newQueryResponse(collection helpers.Collection, error error) QueryResponse { +func newQueryResponse(collection helpers.Collection, error error) helpers.QueryResponse { success := true if error != nil { success = false - return QueryResponse{ - Success: success, - Error: "yes", - List: collection.GetList(), - } } - return QueryResponse{ + + return queryResponse{ Success: success, - Error: "no", + Error: error, List: collection.GetList(), } - } diff --git a/modules/identities/internal/queries/identity/response_test.go b/modules/identities/internal/queries/identity/response_test.go index 797b11aed..c524293fb 100644 --- a/modules/identities/internal/queries/identity/response_test.go +++ b/modules/identities/internal/queries/identity/response_test.go @@ -1,11 +1,10 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package identity import ( + "reflect" "testing" "github.com/cosmos/cosmos-sdk/codec" @@ -17,17 +16,18 @@ import ( "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/mapper" - "github.com/persistenceOne/persistenceSDK/schema" + "github.com/AssetMantle/modules/modules/identities/internal/common" + "github.com/AssetMantle/modules/modules/identities/internal/mapper" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" ) -func CreateTestInput(t *testing.T) sdkTypes.Context { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func CreateTestInputContext(t *testing.T) sdkTypes.Context { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() @@ -51,27 +51,184 @@ func CreateTestInput(t *testing.T) sdkTypes.Context { return context } -func Test_Identity_Response(t *testing.T) { - context := CreateTestInput(t) +func Test_newQueryResponse(t *testing.T) { + context := CreateTestInputContext(t) collection := mapper.Prototype().NewCollection(context) + type args struct { + collection helpers.Collection + error error + } + tests := []struct { + name string + args args + want helpers.QueryResponse + }{ + + {"+ve", args{collection: collection, error: nil}, queryResponse{Success: true, Error: nil}}, + {"-ve with error", args{collection: collection, error: constants.IncorrectFormat}, queryResponse{Success: false, Error: constants.IncorrectFormat}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newQueryResponse(tt.args.collection, tt.args.error); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newQueryResponse() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_queryResponse_Decode(t *testing.T) { + context := CreateTestInputContext(t) + collection := mapper.Prototype().NewCollection(context) testQueryResponse := newQueryResponse(collection, nil) - testQueryResponseWithError := newQueryResponse(collection, errors.IncorrectFormat) - - require.Equal(t, true, testQueryResponse.IsSuccessful()) - require.Equal(t, false, testQueryResponseWithError.IsSuccessful()) - require.Equal(t, nil, testQueryResponse.GetError()) - require.Equal(t, errors.IncorrectFormat, testQueryResponseWithError.GetError()) + encodedResponse, _ := testQueryResponse.Encode() + type fields struct { + Success bool + Error error + List []helpers.Mappable + } + type args struct { + bytes []byte + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryResponse + wantErr bool + }{ + + {"+ve", fields{Success: true, Error: nil}, args{bytes: encodedResponse}, testQueryResponse, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryResponse := queryResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + List: tt.fields.List, + } + got, err := queryResponse.Decode(tt.args.bytes) + if (err != nil) != tt.wantErr { + t.Errorf("Decode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Decode() got = %v, want %v", got, tt.want) + } + }) + } +} - encodedResponse, _ := testQueryResponse.LegacyAminoEncode() - bytes, _ := common.LegacyAminoCodec.MarshalJSON(testQueryResponse) - require.Equal(t, bytes, encodedResponse) +func Test_queryResponse_Encode(t *testing.T) { + context := CreateTestInputContext(t) + collection := mapper.Prototype().NewCollection(context) + encodedByte, err := common.Codec.MarshalJSON(queryResponse{Success: true, Error: nil, List: collection.GetList()}) + encodedByteWithError, _err := common.Codec.MarshalJSON(queryResponse{Success: false, Error: constants.IncorrectFormat, List: collection.GetList()}) + require.Nil(t, err) + type fields struct { + Success bool + Error error + List []helpers.Mappable + } + tests := []struct { + name string + fields fields + want []byte + wantErr bool + }{ + + {"+ve", fields{Success: true, Error: nil, List: collection.GetList()}, encodedByte, false}, + {"-ve with error", fields{Success: false, Error: _err, List: collection.GetList()}, encodedByteWithError, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryResponse := queryResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + List: tt.fields.List, + } + got, err := queryResponse.Encode() + if (err != nil) != tt.wantErr { + t.Errorf("Encode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Encode() got = %v, want %v", got, tt.want) + } + }) + } +} - decodedResponse, _ := queryResponse{}.LegacyAminoDecode(bytes) - require.Equal(t, testQueryResponse, decodedResponse) +func Test_queryResponse_GetError(t *testing.T) { + type fields struct { + Success bool + Error error + List []helpers.Mappable + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + + {"+ve", fields{Success: true, Error: nil}, false}, + {"-ve", fields{Success: true, Error: constants.IncorrectFormat}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryResponse := queryResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + List: tt.fields.List, + } + if err := queryResponse.GetError(); (err != nil) != tt.wantErr { + t.Errorf("GetError() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} - decodedResponse2, _ := queryResponse{}.LegacyAminoDecode([]byte{}) - require.Equal(t, nil, decodedResponse2) +func Test_queryResponse_IsSuccessful(t *testing.T) { + type fields struct { + Success bool + Error error + List []helpers.Mappable + } + tests := []struct { + name string + fields fields + want bool + }{ + + {"+ve", fields{Success: true, Error: nil}, true}, + {"+ve", fields{Success: false, Error: nil}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryResponse := queryResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + List: tt.fields.List, + } + if got := queryResponse.IsSuccessful(); got != tt.want { + t.Errorf("IsSuccessful() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, queryResponse{}, responsePrototype()) +func Test_responsePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryResponse + }{ + + {"+ve", queryResponse{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := responsePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("responsePrototype() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/identities/internal/queries/prototype.go b/modules/identities/internal/queries/prototype.go new file mode 100644 index 000000000..a6a17d554 --- /dev/null +++ b/modules/identities/internal/queries/prototype.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queries + +import ( + "github.com/AssetMantle/modules/modules/identities/internal/queries/identity" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Queries { + return baseHelpers.NewQueries( + identity.Query, + ) +} diff --git a/modules/identities/internal/simulator/constants.go b/modules/identities/internal/simulator/constants.go new file mode 100644 index 000000000..0e23f0a61 --- /dev/null +++ b/modules/identities/internal/simulator/constants.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +const OpWeightSubmitTextProposal = "op_weight_submit_text_proposal" +const DefaultWeightTextProposal = 1 + +const OpWeightMsg = "OpWeightMsg" +const DefaultWeightMsg = 1 diff --git a/modules/identities/internal/simulator/genesis.go b/modules/identities/internal/simulator/genesis.go new file mode 100644 index 000000000..cb148184a --- /dev/null +++ b/modules/identities/internal/simulator/genesis.go @@ -0,0 +1,51 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "math/rand" + + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + + "github.com/AssetMantle/modules/modules/identities/internal/common" + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + identitiesModule "github.com/AssetMantle/modules/modules/identities/internal/module" + "github.com/AssetMantle/modules/modules/identities/internal/parameters" + "github.com/AssetMantle/modules/modules/identities/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/data" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + parameters2 "github.com/AssetMantle/modules/schema/parameters" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseSimulation "github.com/AssetMantle/modules/simulation/schema/types/base" +) + +func (simulator) RandomizedGenesisState(simulationState *module.SimulationState) { + var Data data.Data + + simulationState.AppParams.GetOrGenerate( + simulationState.Cdc, + dummy.ID.String(), + &Data, + simulationState.Rand, + func(rand *rand.Rand) { Data = baseData.NewDecData(sdkTypes.NewDecWithPrec(int64(rand.Intn(99)), 2)) }, + ) + + mappableList := make([]helpers.Mappable, len(simulationState.Accounts)) + + for i := range mappableList { + immutables := baseQualified.NewImmutables(baseSimulation.GenerateRandomPropertyList(simulationState.Rand)) + mutables := baseQualified.NewMutables(baseSimulation.GenerateRandomPropertyList(simulationState.Rand)) + mappableList[i] = mappable.NewMappable(base.NewIdentity(baseIDs.NewClassificationID(immutables, mutables), immutables, mutables)) + } + + genesisState := baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, nil, parameters.Prototype().GetList()).Initialize(mappableList, []parameters2.Parameter{dummy.Parameter.Mutate(Data)}) + + simulationState.GenState[identitiesModule.Name] = common.Codec.MustMarshalJSON(genesisState) +} diff --git a/modules/identities/internal/simulator/operations.go b/modules/identities/internal/simulator/operations.go index 874164578..3c3884187 100644 --- a/modules/identities/internal/simulator/operations.go +++ b/modules/identities/internal/simulator/operations.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator @@ -11,11 +9,10 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" - sdkModuleSimulation "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" ) -func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec.JSONMarshaler) simulation.WeightedOperation { +func (simulator) WeightedOperations(appParams simulation.AppParams, codec *codec.Codec) simulation.WeightedOperations { var weightMsg int appParams.GetOrGenerate(codec, OpWeightMsg, &weightMsg, nil, @@ -24,10 +21,12 @@ func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec. }, ) - return sdkModuleSimulation.NewWeightedOperation( - weightMsg, - simulateMsg(), - ) + return simulation.WeightedOperations{ + simulation.NewWeightedOperation( + weightMsg, + simulateMsg(), + ), + } } func simulateMsg() simulation.Operation { diff --git a/modules/identities/internal/simulator/params.go b/modules/identities/internal/simulator/params.go index d6e56604e..a5c0a6519 100644 --- a/modules/identities/internal/simulator/params.go +++ b/modules/identities/internal/simulator/params.go @@ -1,30 +1,28 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( "math/rand" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - simTypes "github.com/cosmos/cosmos-sdk/types/simulation" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + + "github.com/AssetMantle/modules/modules/identities/internal/common" + "github.com/AssetMantle/modules/modules/identities/internal/module" + "github.com/AssetMantle/modules/modules/identities/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/data/base" ) -func (simulator) ParamChangeList(_ *rand.Rand) []simTypes.ParamChange { - return []simTypes.ParamChange{ +func (simulator) ParamChangeList(_ *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange(module.Name, dummy.ID.String(), func(r *rand.Rand) string { - bytes, Error := common.LegacyAminoCodec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdkTypes.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) - if Error != nil { - panic(Error) + bytes, err := common.Codec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdk.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) + if err != nil { + panic(err) } return string(bytes) }), diff --git a/modules/identities/internal/simulator/proposals.go b/modules/identities/internal/simulator/proposals.go index c85fdfbd1..ce4efd54f 100644 --- a/modules/identities/internal/simulator/proposals.go +++ b/modules/identities/internal/simulator/proposals.go @@ -1,34 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( - simulation2 "github.com/cosmos/cosmos-sdk/x/simulation" "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/simulation" ) func (simulator) WeightedProposalContentList() []simulation.WeightedProposalContent { return []simulation.WeightedProposalContent{ - simulation2.NewWeightedProposalContent( - OpWeightSubmitTextProposal, - DefaultWeightTextProposal, - contentSimulatorFunc(), - ), + { + AppParamsKey: OpWeightSubmitTextProposal, + DefaultWeight: DefaultWeightTextProposal, + ContentSimulatorFn: simulateTextProposalContent, + }, } } -func contentSimulatorFunc() simulation.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) simulation.Content { - return types.NewTextProposal( - simulation.RandStringOfLength(r, 140), - simulation.RandStringOfLength(r, 5000), - ) - } +func simulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Account) types.Content { + return types.NewTextProposal( + simulation.RandStringOfLength(r, 140), + simulation.RandStringOfLength(r, 5000), + ) } diff --git a/modules/identities/internal/simulator/prototype.go b/modules/identities/internal/simulator/prototype.go new file mode 100644 index 000000000..3da39d69f --- /dev/null +++ b/modules/identities/internal/simulator/prototype.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +func Prototype() helpers.Simulator { + return newSimulator() +} diff --git a/modules/identities/internal/simulator/prototype_test.go b/modules/identities/internal/simulator/prototype_test.go new file mode 100644 index 000000000..4352a8d45 --- /dev/null +++ b/modules/identities/internal/simulator/prototype_test.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype(), newSimulator()) +} diff --git a/modules/identities/internal/simulator/simulator.go b/modules/identities/internal/simulator/simulator.go new file mode 100644 index 000000000..d963561c2 --- /dev/null +++ b/modules/identities/internal/simulator/simulator.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +type simulator struct{} + +var _ helpers.Simulator = (*simulator)(nil) + +func newSimulator() helpers.Simulator { + return simulator{} +} diff --git a/modules/identities/internal/transactions/define/keeper.go b/modules/identities/internal/transactions/define/keeper.go new file mode 100644 index 000000000..cb9a4db5d --- /dev/null +++ b/modules/identities/internal/transactions/define/keeper.go @@ -0,0 +1,90 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/define" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/super" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/schema/documents" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties/constants" + "github.com/AssetMantle/modules/schema/qualified/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + authenticateAuxiliary helpers.Auxiliary + defineAuxiliary helpers.Auxiliary + superAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromIdentity)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + mappable := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.FromIdentity)).Get(key.NewKey(message.FromIdentity)) + if mappable == nil { + return newTransactionResponse(errorConstants.EntityNotFound) + } + identity := mappable.(documents.Identity) + + if !identity.(documents.Identity).IsProvisioned(message.From) { + return newTransactionResponse(errorConstants.NotAuthorized) + } + + immutables := base.NewImmutables(baseLists.NewPropertyList(append(message.ImmutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...)...)) + + mutables := base.NewMutables(baseLists.NewPropertyList(append(append(message.MutableMetaProperties.GetList(), message.MutableProperties.GetList()...), constants.AuthenticationProperty)...)) + + classificationID, err := define.GetClassificationIDFromResponse(transactionKeeper.defineAuxiliary.GetKeeper().Help(context, define.NewAuxiliaryRequest(immutables, mutables))) + if err != nil { + return newTransactionResponse(err) + } + + if auxiliaryResponse := transactionKeeper.superAuxiliary.GetKeeper().Help(context, super.NewAuxiliaryRequest(classificationID, message.FromIdentity, mutables)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper = mapper + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + case define.Auxiliary.GetName(): + transactionKeeper.defineAuxiliary = value + case super.Auxiliary.GetName(): + transactionKeeper.superAuxiliary = value + case supplement.Auxiliary.GetName(): + transactionKeeper.supplementAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} + +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/identities/internal/transactions/define/message.go b/modules/identities/internal/transactions/define/message.go index 9b6429b33..81a107fa5 100644 --- a/modules/identities/internal/transactions/define/message.go +++ b/modules/identities/internal/transactions/define/message.go @@ -1,71 +1,83 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/identities/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromIdentity ids.IdentityID `json:"fromIdentity" valid:"required~required field fromID missing"` + ImmutableMetaProperties lists.PropertyList `json:"immutableMetaProperties" valid:"required~required field immutableMetaProperties missing"` + ImmutableProperties lists.PropertyList `json:"immutableProperties" valid:"required~required field immutableProperties missing"` + MutableMetaProperties lists.PropertyList `json:"mutableMetaProperties" valid:"required~required field mutableMetaProperties missing"` + MutableProperties lists.PropertyList `json:"mutableProperties" valid:"required~required field mutableProperties missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + if len(message.ImmutableMetaProperties.GetList()) == 0 { + message.ImmutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.ImmutableProperties.GetList()) == 0 { + message.ImmutableProperties = base.NewPropertyList(nil) + } + if len(message.MutableMetaProperties.GetList()) == 0 { + message.MutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.MutableProperties.GetList()) == 0 { + message.MutableProperties = base.NewPropertyList(nil) + } + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, immutableMetaProperties types.MetaProperties, immutableProperties types.Properties, mutableMetaProperties types.MetaProperties, mutableProperties types.Properties) *Message { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - ImmutableMetaProperties: *base.NewMetaProperties(immutableMetaProperties.GetList()...), - ImmutableProperties: *base.NewProperties(immutableProperties.GetList()...), - MutableMetaProperties: *base.NewMetaProperties(mutableMetaProperties.GetList()...), - MutableProperties: *base.NewProperties(mutableProperties.GetList()...), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, immutableMetaProperties lists.PropertyList, immutableProperties lists.PropertyList, mutableMetaProperties lists.PropertyList, mutableProperties lists.PropertyList) sdkTypes.Msg { + return message{ + From: from, + FromIdentity: fromID, + ImmutableMetaProperties: immutableMetaProperties, + ImmutableProperties: immutableProperties, + MutableMetaProperties: mutableMetaProperties, + MutableProperties: mutableProperties, } } diff --git a/modules/identities/internal/transactions/define/message.pb.go b/modules/identities/internal/transactions/define/message.pb.go deleted file mode 100644 index b7ef16879..000000000 --- a/modules/identities/internal/transactions/define/message.pb.go +++ /dev/null @@ -1,775 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/transactions/define/message.proto - -package define - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - ImmutableMetaProperties base.MetaProperties `protobuf:"bytes,3,opt,name=immutable_meta_properties,json=immutableMetaProperties,proto3" json:"immutable_meta_properties" valid:"required~required field ImmutableMetaProperties missing"` - ImmutableProperties base.Properties `protobuf:"bytes,4,opt,name=immutable_properties,json=immutableProperties,proto3" json:"immutable_properties" valid:"required~required field ImmutableProperties missing"` - MutableMetaProperties base.MetaProperties `protobuf:"bytes,5,opt,name=mutable_meta_properties,json=mutableMetaProperties,proto3" json:"mutable_meta_properties" valid:"required~required field MutableMetaProperties missing"` - MutableProperties base.Properties `protobuf:"bytes,6,opt,name=mutable_properties,json=mutableProperties,proto3" json:"mutable_properties" valid:"required~required field MutableProperties missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_c0ca958540f7b686, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_c0ca958540f7b686, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.identities.internal.transactions.define.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.identities.internal.transactions.define.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/transactions/define/message.proto", fileDescriptor_c0ca958540f7b686) -} - -var fileDescriptor_c0ca958540f7b686 = []byte{ - // 564 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x95, 0x31, 0x6f, 0xd3, 0x40, - 0x1c, 0xc5, 0x7d, 0xb4, 0xa4, 0xe5, 0x98, 0x70, 0x5b, 0x35, 0x64, 0xb0, 0xa3, 0x48, 0x48, 0x15, - 0x82, 0xb3, 0x08, 0x52, 0x25, 0x8a, 0x50, 0x95, 0x90, 0x02, 0x11, 0x8a, 0x40, 0xa5, 0x03, 0x62, - 0x89, 0x1c, 0xdf, 0x3f, 0xee, 0x89, 0xd8, 0x67, 0xee, 0x2e, 0x20, 0x06, 0x98, 0x19, 0xe1, 0x13, - 0xd0, 0x05, 0x89, 0xb1, 0x13, 0x9f, 0xa1, 0x63, 0x27, 0x84, 0x18, 0x22, 0x94, 0x2c, 0xcc, 0xfd, - 0x04, 0x28, 0x17, 0x47, 0x4e, 0x13, 0x43, 0x4c, 0x3b, 0xf9, 0x6c, 0xff, 0xff, 0xef, 0xfd, 0xf4, - 0x2c, 0x3d, 0xe3, 0x46, 0x04, 0x42, 0x32, 0xa9, 0x20, 0xf4, 0xa0, 0x29, 0xe9, 0x4b, 0x27, 0xe0, - 0xb4, 0xdb, 0x01, 0xe9, 0x30, 0x0a, 0xa1, 0x62, 0x8a, 0x0d, 0x8f, 0xa1, 0x02, 0x11, 0xba, 0x1d, - 0x47, 0x09, 0x37, 0x94, 0xae, 0xa7, 0x18, 0x0f, 0xa5, 0x43, 0xa1, 0xcd, 0x42, 0x70, 0x02, 0x90, - 0xd2, 0xf5, 0x81, 0x44, 0x82, 0x2b, 0x6e, 0x6e, 0x4f, 0xc9, 0x91, 0x58, 0x8e, 0x24, 0x72, 0x64, - 0x2c, 0x47, 0x26, 0xe5, 0xc8, 0x48, 0xae, 0xb0, 0xea, 0x73, 0x9f, 0x6b, 0x2d, 0x67, 0x78, 0x1a, - 0xc9, 0x16, 0xae, 0x4f, 0x53, 0x4a, 0x6f, 0x1f, 0x02, 0xd7, 0x51, 0x6f, 0x23, 0x90, 0x4e, 0xcb, - 0x95, 0xe0, 0x30, 0x1a, 0xcf, 0x96, 0xe7, 0xcf, 0x46, 0x82, 0x47, 0x20, 0x34, 0xcc, 0x68, 0x67, - 0x73, 0xfe, 0x4e, 0x00, 0xca, 0x7d, 0x3a, 0xb5, 0x57, 0xfa, 0xbe, 0x84, 0x97, 0x1a, 0xa3, 0x00, - 0xcc, 0x4f, 0x08, 0x2f, 0xb6, 0x05, 0x0f, 0xf2, 0xa8, 0x88, 0x36, 0x2e, 0x55, 0xdf, 0x1d, 0xf5, - 0x6c, 0xe3, 0x67, 0xcf, 0xde, 0xf1, 0x99, 0xda, 0xef, 0xb6, 0x88, 0xc7, 0x03, 0x67, 0xc2, 0xe5, - 0x49, 0x08, 0x93, 0xb7, 0xcf, 0x6a, 0x8f, 0x67, 0x3d, 0x49, 0xc5, 0xf3, 0x2a, 0x94, 0x0a, 0x90, - 0xf2, 0xa4, 0x67, 0xdf, 0x78, 0xed, 0x76, 0x18, 0xdd, 0x2a, 0x09, 0x78, 0xd5, 0x65, 0x02, 0xe8, - 0xfb, 0xf1, 0xa1, 0xd8, 0x66, 0xd0, 0xa1, 0xc5, 0x07, 0x82, 0x07, 0xc5, 0x80, 0x49, 0xc9, 0x42, - 0xbf, 0xb4, 0xab, 0x51, 0xcc, 0x37, 0x78, 0x79, 0x78, 0x6d, 0xb2, 0x26, 0xcd, 0x5f, 0x28, 0xa2, - 0x8d, 0xcb, 0xe5, 0x6b, 0x64, 0xfa, 0x0b, 0x8d, 0x6c, 0x89, 0xb6, 0x25, 0xda, 0xb6, 0x5e, 0xab, - 0x6e, 0x0e, 0xe9, 0x4f, 0x7a, 0x36, 0xc9, 0x60, 0x5a, 0xaf, 0x25, 0xb6, 0xb9, 0xb6, 0x7e, 0x60, - 0x7e, 0x43, 0xf8, 0x2a, 0x0b, 0x82, 0xae, 0x72, 0x5b, 0x1d, 0x68, 0x0e, 0xb3, 0x6b, 0x26, 0xa1, - 0xe7, 0x17, 0x34, 0xca, 0xad, 0x0c, 0x28, 0x8d, 0x53, 0xa9, 0x57, 0x1f, 0xc6, 0x58, 0xdb, 0x73, - 0xb0, 0xea, 0x63, 0xeb, 0xd3, 0xfb, 0x09, 0xe7, 0x3a, 0x4b, 0x9f, 0x30, 0xbf, 0x20, 0xbc, 0x9a, - 0x80, 0x4f, 0x30, 0x2f, 0x6a, 0xe6, 0x9b, 0x19, 0x98, 0x27, 0x78, 0xef, 0xc7, 0xbc, 0x77, 0xb3, - 0xf2, 0xa6, 0xb1, 0xae, 0xb0, 0xd9, 0xb7, 0xe6, 0x21, 0xc2, 0xeb, 0x7f, 0x8b, 0xf7, 0xe2, 0x59, - 0xe3, 0xdd, 0x89, 0x71, 0xef, 0xcd, 0xc1, 0x6d, 0xfc, 0x3b, 0xdc, 0xb5, 0xf4, 0x68, 0x3f, 0x23, - 0x6c, 0xa6, 0x04, 0x9b, 0x3b, 0x4b, 0xb0, 0x95, 0x98, 0xf4, 0x4e, 0x36, 0xd2, 0x34, 0xca, 0x2b, - 0x33, 0xa1, 0x6e, 0x2d, 0x7f, 0x38, 0xb0, 0x8d, 0xdf, 0x07, 0xb6, 0x51, 0x5a, 0xc3, 0x2b, 0x7b, - 0x49, 0x3b, 0xed, 0x82, 0x8c, 0x78, 0x28, 0xa1, 0x7c, 0x88, 0xf0, 0x42, 0x43, 0xfa, 0xe6, 0x57, - 0x84, 0x73, 0x35, 0x5d, 0x58, 0xe6, 0x23, 0x72, 0xce, 0xca, 0x23, 0x71, 0x81, 0x14, 0xf6, 0xce, - 0xad, 0x94, 0x82, 0x5c, 0x15, 0x47, 0x7d, 0x0b, 0x1d, 0xf7, 0x2d, 0xf4, 0xab, 0x6f, 0xa1, 0x8f, - 0x03, 0xcb, 0x38, 0x1e, 0x58, 0xc6, 0x8f, 0x81, 0x65, 0xbc, 0x78, 0x9e, 0xb9, 0x99, 0xfe, 0xf3, - 0x9f, 0xd0, 0xca, 0xe9, 0x76, 0xbc, 0xfd, 0x27, 0x00, 0x00, 0xff, 0xff, 0x0b, 0xfa, 0x0a, 0x63, - 0x5d, 0x06, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Define(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Define(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.identities.internal.transactions.define.Msg/Define", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Define(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Define(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Define not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Define_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Define(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.identities.internal.transactions.define.Msg/Define", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Define(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.identities.internal.transactions.define.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Define", - Handler: _Msg_Define_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/identities/internal/transactions/define/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.MutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.ImmutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ImmutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/transactions/define/message_test.go b/modules/identities/internal/transactions/define/message_test.go index f220932f7..a98e88e66 100644 --- a/modules/identities/internal/transactions/define/message_test.go +++ b/modules/identities/internal/transactions/define/message_test.go @@ -1,47 +1,413 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/identities/internal/module" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/utilities" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Define_Message(t *testing.T) { - testFromID := base.NewID("fromID") +func Test_messageFromInterface(t *testing.T) { + testFromID, err := baseIDs.ReadIdentityID("CBepOLnJFnKO9NEyZlSv7r80nKNZFFXRqHfnsObZ_KU=") + require.NoError(t, err) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + + immutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultImmutableMeta1:S|defaultImmutableMeta1") + require.Equal(t, nil, err) + immutableProperties, err := utilities.ReadMetaPropertyList("defaultImmutable1:S|defaultImmutable1") + require.Equal(t, nil, err) + mutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultMutableMeta1:S|defaultMutableMeta1") + require.Equal(t, nil, err) + mutableProperties, err := utilities.ReadMetaPropertyList("defaultMutable1:S|defaultMutable1") + require.Equal(t, nil, err) + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + + {"+ve", args{message{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}}, message{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}}, + {"+ve with nil", args{nil}, message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + testFromID, err := baseIDs.ReadIdentityID("CBepOLnJFnKO9NEyZlSv7r80nKNZFFXRqHfnsObZ_KU=") + require.NoError(t, err) + + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + + immutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultImmutableMeta1:S|defaultImmutableMeta1") + require.Equal(t, nil, err) + immutableProperties, err := utilities.ReadMetaPropertyList("defaultImmutable1:S|defaultImmutable1") + require.Equal(t, nil, err) + mutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultMutableMeta1:S|defaultMutableMeta1") + require.Equal(t, nil, err) + mutableProperties, err := utilities.ReadMetaPropertyList("defaultMutable1:S|defaultMutable1") + require.Equal(t, nil, err) + _message := message{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties} + + type fields struct { + From sdkTypes.AccAddress + FromIdentity ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []byte + }{ + + {"+ve", fields{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(_message))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromIdentity: tt.fields.FromIdentity, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + testFromID, err := baseIDs.ReadIdentityID("CBepOLnJFnKO9NEyZlSv7r80nKNZFFXRqHfnsObZ_KU=") + require.NoError(t, err) + + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + + immutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultImmutableMeta1:S|defaultImmutableMeta1") + require.Equal(t, nil, err) + immutableProperties, err := utilities.ReadMetaPropertyList("defaultImmutable1:S|defaultImmutable1") + require.Equal(t, nil, err) + mutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultMutableMeta1:S|defaultMutableMeta1") + require.Equal(t, nil, err) + mutableProperties, err := utilities.ReadMetaPropertyList("defaultMutable1:S|defaultMutable1") + require.Equal(t, nil, err) + type fields struct { + From sdkTypes.AccAddress + FromIdentity ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + + {"+ve", fields{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromIdentity: tt.fields.FromIdentity, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + testFromID, err := baseIDs.ReadIdentityID("CBepOLnJFnKO9NEyZlSv7r80nKNZFFXRqHfnsObZ_KU=") + require.NoError(t, err) + + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + + immutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultImmutableMeta1:S|defaultImmutableMeta1") + require.Equal(t, nil, err) + immutableProperties, err := utilities.ReadMetaPropertyList("defaultImmutable1:S|defaultImmutable1") + require.Equal(t, nil, err) + mutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultMutableMeta1:S|defaultMutableMeta1") + require.Equal(t, nil, err) + mutableProperties, err := utilities.ReadMetaPropertyList("defaultMutable1:S|defaultMutable1") + require.Equal(t, nil, err) + type fields struct { + From sdkTypes.AccAddress + FromIdentity ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + + {"+ve", fields{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromIdentity: tt.fields.FromIdentity, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + testFromID, err := baseIDs.ReadIdentityID("CBepOLnJFnKO9NEyZlSv7r80nKNZFFXRqHfnsObZ_KU=") + require.NoError(t, err) + + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + + immutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultImmutableMeta1:S|defaultImmutableMeta1") + require.Equal(t, nil, err) + immutableProperties, err := utilities.ReadMetaPropertyList("defaultImmutable1:S|defaultImmutable1") + require.Equal(t, nil, err) + mutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultMutableMeta1:S|defaultMutableMeta1") + require.Equal(t, nil, err) + mutableProperties, err := utilities.ReadMetaPropertyList("defaultMutable1:S|defaultMutable1") + require.Equal(t, nil, err) + type fields struct { + From sdkTypes.AccAddress + FromIdentity ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + + {"+ve", fields{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromIdentity: tt.fields.FromIdentity, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + testFromID, err := baseIDs.ReadIdentityID("CBepOLnJFnKO9NEyZlSv7r80nKNZFFXRqHfnsObZ_KU=") + require.NoError(t, err) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) require.Nil(t, err) - immutableMetaProperties, err := base.ReadMetaProperties("defaultImmutableMeta1:S|defaultImmutableMeta1") + immutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultImmutableMeta1:S|defaultImmutableMeta1") require.Equal(t, nil, err) - immutableProperties, err := base.ReadProperties("defaultImmutable1:S|defaultImmutable1") + immutableProperties, err := utilities.ReadMetaPropertyList("defaultImmutable1:S|defaultImmutable1") require.Equal(t, nil, err) - mutableMetaProperties, err := base.ReadMetaProperties("defaultMutableMeta1:S|defaultMutableMeta1") + mutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultMutableMeta1:S|defaultMutableMeta1") require.Equal(t, nil, err) - mutableProperties, err := base.ReadProperties("defaultMutable1:S|defaultMutable1") + mutableProperties, err := utilities.ReadMetaPropertyList("defaultMutable1:S|defaultMutable1") require.Equal(t, nil, err) + type fields struct { + From sdkTypes.AccAddress + FromIdentity ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + + {"+ve", fields{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromIdentity: tt.fields.FromIdentity, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} - testMessage := newMessage(fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, ImmutableMetaProperties: immutableMetaProperties, ImmutableProperties: immutableProperties, MutableMetaProperties: mutableMetaProperties, MutableProperties: mutableProperties}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +func Test_message_ValidateBasic(t *testing.T) { + testFromID, err := baseIDs.ReadIdentityID("CBepOLnJFnKO9NEyZlSv7r80nKNZFFXRqHfnsObZ_KU=") + require.NoError(t, err) + + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + + immutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultImmutableMeta1:S|defaultImmutableMeta1") + require.Equal(t, nil, err) + immutableProperties, err := utilities.ReadMetaPropertyList("defaultImmutable1:S|defaultImmutable1") + require.Equal(t, nil, err) + mutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultMutableMeta1:S|defaultMutableMeta1") + require.Equal(t, nil, err) + mutableProperties, err := utilities.ReadMetaPropertyList("defaultMutable1:S|defaultMutable1") + require.Equal(t, nil, err) + type fields struct { + From sdkTypes.AccAddress + FromIdentity ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + + {"+ve", fields{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromIdentity: tt.fields.FromIdentity, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_newMessage(t *testing.T) { + testFromID, err := baseIDs.ReadIdentityID("CBepOLnJFnKO9NEyZlSv7r80nKNZFFXRqHfnsObZ_KU=") + require.NoError(t, err) + + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + + immutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultImmutableMeta1:S|defaultImmutableMeta1") + require.Equal(t, nil, err) + immutableProperties, err := utilities.ReadMetaPropertyList("defaultImmutable1:S|defaultImmutable1") + require.Equal(t, nil, err) + mutableMetaProperties, err := utilities.ReadMetaPropertyList("defaultMutableMeta1:S|defaultMutableMeta1") + require.Equal(t, nil, err) + mutableProperties, err := utilities.ReadMetaPropertyList("defaultMutable1:S|defaultMutable1") + require.Equal(t, nil, err) + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + immutableMetaProperties lists.PropertyList + immutableProperties lists.PropertyList + mutableMetaProperties lists.PropertyList + mutableProperties lists.PropertyList + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, message{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}}, + {"+ve with nil", args{}, message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/identities/internal/transactions/define/msg_server.go b/modules/identities/internal/transactions/define/msg_server.go deleted file mode 100644 index 37c2ef69f..000000000 --- a/modules/identities/internal/transactions/define/msg_server.go +++ /dev/null @@ -1,70 +0,0 @@ -package define - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/define" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/super" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Define(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - identity := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(&message.FromID)).Get(key.FromID(&message.FromID)).(mappables.InterIdentity) - if identity == nil { - return nil, errors.EntityNotFound - } - - if !identity.IsProvisioned(message.From.AsSDKTypesAccAddress()) { - return nil, errors.NotAuthorized - } - - immutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(message.ImmutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - immutableProperties := base.NewProperties(append(immutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...)...) - - authenticationProperty := base.NewMetaProperty(base.NewID(properties.Authentication), base.NewMetaFact(base.NewListData(base.NewAccAddressData(message.From.AsSDKTypesAccAddress())))) - - updatedMutableMetaProperties := append(message.MutableMetaProperties.GetList(), authenticationProperty) - - mutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(updatedMutableMetaProperties...))) - if Error != nil { - return nil, Error - } - - mutableProperties := base.NewProperties(append(mutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...) - - classificationID, Error := define.GetClassificationIDFromResponse(msgServer.transactionKeeper.defineAuxiliary.GetKeeper().Help(ctx, define.NewAuxiliaryRequest(immutableProperties, mutableProperties))) - if Error != nil { - return nil, Error - } - - if auxiliaryResponse := msgServer.transactionKeeper.superAuxiliary.GetKeeper().Help(ctx, super.NewAuxiliaryRequest(classificationID, &message.FromID, mutableProperties)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/identities/internal/transactions/define/request.go b/modules/identities/internal/transactions/define/request.go index 5c39f26f4..a0424434c 100644 --- a/modules/identities/internal/transactions/define/request.go +++ b/modules/identities/internal/transactions/define/request.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define @@ -9,15 +7,19 @@ import ( "encoding/json" "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers/base" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -31,33 +33,40 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary define identities transaction -// @Descrption define identities with mutable immutable properties +// Validate godoc +// @Summary Define an identity +// @Description Define identities with mutable immutable properties // @Accept text/plain // @Produce json // @Tags Identities -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body body transactionRequest true "Deputize identities" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /identities/define [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + if err != nil { + return err + } + inputValidator := base.NewInputValidator(constants.PropertyExpression) + if !inputValidator.IsValid(transactionRequest.ImmutableProperties, transactionRequest.ImmutableMetaProperties, transactionRequest.MutableProperties, transactionRequest.MutableMetaProperties) { + return errorConstants.IncorrectFormat + } + return nil } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ImmutableMetaProperties), - cliCommand.ReadString(flags.ImmutableProperties), - cliCommand.ReadString(flags.MutableMetaProperties), - cliCommand.ReadString(flags.MutableProperties), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ImmutableMetaProperties), + cliCommand.ReadString(constants.ImmutableProperties), + cliCommand.ReadString(constants.MutableMetaProperties), + cliCommand.ReadString(constants.MutableProperties), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -65,48 +74,55 @@ func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } + func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + immutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableMetaProperties) + if err != nil { + return nil, err } - immutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.ImmutableMetaProperties) - if Error != nil { - return nil, Error + immutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableProperties) + if err != nil { + return nil, err } + immutableProperties = immutableProperties.ScrubData() - immutableProperties, Error := base.ReadProperties(transactionRequest.ImmutableProperties) - if Error != nil { - return nil, Error + mutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableMetaProperties) + if err != nil { + return nil, err } - mutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.MutableMetaProperties) - if Error != nil { - return nil, Error + mutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableProperties) + if err != nil { + return nil, err } + mutableProperties = mutableProperties.ScrubData() - mutableProperties, Error := base.ReadProperties(transactionRequest.MutableProperties) - if Error != nil { - return nil, Error + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), + fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} } - func newTransactionRequest(baseReq rest.BaseReq, fromID string, immutableMetaProperties string, immutableProperties string, mutableMetaProperties string, mutableProperties string) helpers.TransactionRequest { return transactionRequest{ BaseReq: baseReq, diff --git a/modules/identities/internal/transactions/define/request_test.go b/modules/identities/internal/transactions/define/request_test.go index 612955f05..db30b54f4 100644 --- a/modules/identities/internal/transactions/define/request_test.go +++ b/modules/identities/internal/transactions/define/request_test.go @@ -1,104 +1,388 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define import ( "encoding/json" + "reflect" "testing" - "github.com/cosmos/cosmos-sdk/client" + "github.com/AssetMantle/modules/schema/lists/utilities" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + utilitiesProperties "github.com/AssetMantle/modules/schema/properties/utilities" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" ) -func Test_Define_Request(t *testing.T) { +func Test_newTransactionRequest(t *testing.T) { + + immutableMetaPropertiesString := "defaultImmutableMeta1:S|defaultImmutableMeta1" + immutablePropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" + mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" + mutablePropertiesString := "defaultMutable1:S|defaultMutable1" + + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} + type args struct { + baseReq rest.BaseReq + fromID string + immutableMetaProperties string + immutableProperties string + mutableMetaProperties string + mutableProperties string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + + {"+ve", args{testBaseReq, "fromID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.ImmutableMetaProperties, constants.ImmutableProperties, constants.MutableMetaProperties, constants.MutableProperties}) + cliContext := context.NewCLIContext().WithCodec(codec.Cdc) + + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + + {"+ve", fields{BaseReq: testBaseReq, FromID: "", ImmutableMetaProperties: "", ImmutableProperties: "", MutableMetaProperties: "", MutableProperties: ""}, args{cliCommand, cliContext}, transactionRequest{cliCommand.ReadBaseReq(cliContext), cliCommand.ReadString(constants.FromID), cliCommand.ReadString(constants.ImmutableMetaProperties), cliCommand.ReadString(constants.ImmutableProperties), cliCommand.ReadString(constants.MutableMetaProperties), cliCommand.ReadString(constants.MutableProperties)}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionRequest_FromJSON(t *testing.T) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.ImmutableMetaProperties, flags.ImmutableProperties, flags.MutableMetaProperties, flags.MutableProperties}) - cliContext := context.NewCLIContext().WithCodec(Codec) immutableMetaPropertiesString := "defaultImmutableMeta1:S|defaultImmutableMeta1" immutablePropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - immutableMetaProperties, Error := base.ReadMetaProperties(immutableMetaPropertiesString) - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties(immutablePropertiesString) - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties(mutableMetaPropertiesString) - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties(mutablePropertiesString) - require.Equal(t, nil, Error) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} + jsonMessage, _ := json.Marshal(transactionRequest{testBaseReq, "fromID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}) + + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{BaseReq: testBaseReq, FromID: "fromID", ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, args{jsonMessage}, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionRequest_GetBaseReq(t *testing.T) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + immutableMetaPropertiesString := "defaultImmutableMeta1:S|defaultImmutableMeta1" + immutablePropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" + mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" + mutablePropertiesString := "defaultMutable1:S|defaultMutable1" fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString) + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{BaseReq: testBaseReq, FromID: "fromID", ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, testBaseReq}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) +func Test_transactionRequest_MakeMsg(t *testing.T) { - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ImmutableMetaProperties: "", ImmutableProperties: "", MutableMetaProperties: "", MutableProperties: ""}, requestFromCLI) + immutableMetaPropertiesString := "defaultImmutableMeta1:S|defaultImmutableMeta1" + immutablePropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" + mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" + mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) + immutableMetaProperties, err := utilitiesProperties.ReadMetaProperty(immutableMetaPropertiesString) + require.Equal(t, nil, err) + immutableProperties, err := utilities.ReadMetaPropertyList(immutablePropertiesString) + require.Equal(t, nil, err) + mutableMetaProperties, err := utilitiesProperties.ReadMetaProperty(mutableMetaPropertiesString) + require.Equal(t, nil, err) + mutableProperties, err := utilities.ReadMetaPropertyList(mutablePropertiesString) + require.Equal(t, nil, err) - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties), msg) - require.Nil(t, Error) + testIdentity := baseIDs.NewIdentityID(baseIDs.NewClassificationID(baseQualified.NewImmutables(immutableProperties), baseQualified.NewMutables(mutableProperties)), baseQualified.NewImmutables(immutableProperties)) - msg, Error = newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want sdkTypes.Msg + wantErr bool + }{ + {"+ve", fields{BaseReq: testBaseReq, FromID: testIdentity.String(), ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, newMessage(fromAccAddress, testIdentity, baseLists.NewPropertyList(immutableMetaProperties), immutableProperties.ScrubData(), baseLists.NewPropertyList(mutableMetaProperties), mutableProperties.ScrubData()), false}, + {"-ve wrong Identity", fields{BaseReq: testBaseReq, FromID: "WrongIdentity", ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, nil, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "randomString", immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + immutableMetaPropertiesString := "defaultImmutableMeta1:S|defaultImmutableMeta1" + immutablePropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" + mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" + mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", immutableMetaPropertiesString, "randomString", mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", immutableMetaPropertiesString, immutablePropertiesString, "randomString", mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{BaseReq: testBaseReq, FromID: "fromID", ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, "randomString").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_Validate(t *testing.T) { + immutableMetaPropertiesString := "defaultImmutableMeta1:S|defaultImmutableMeta1" + immutablePropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" + mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" + mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{BaseReq: testBaseReq, FromID: "fromID", ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/identities/internal/transactions/define/response.go b/modules/identities/internal/transactions/define/response.go new file mode 100644 index 000000000..bd134e694 --- /dev/null +++ b/modules/identities/internal/transactions/define/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/identities/internal/transactions/define/response_test.go b/modules/identities/internal/transactions/define/response_test.go new file mode 100644 index 000000000..767607053 --- /dev/null +++ b/modules/identities/internal/transactions/define/response_test.go @@ -0,0 +1,88 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + "reflect" + "testing" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +func Test_newTransactionResponse(t *testing.T) { + type args struct { + error error + } + tests := []struct { + name string + args args + want helpers.TransactionResponse + }{ + + {"-ve", args{constants.IncorrectMessage}, transactionResponse{false, constants.IncorrectMessage}}, + {"+ve", args{nil}, transactionResponse{true, nil}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionResponse(tt.args.error); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionResponse() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionResponse_GetError(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + + {"+ve", fields{false, constants.IncorrectFormat}, true}, + {"-ve", fields{true, nil}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if err := transactionResponse.GetError(); (err != nil) != tt.wantErr { + t.Errorf("GetError() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_transactionResponse_IsSuccessful(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + want bool + }{ + + {"+ve", fields{true, nil}, true}, + {"-ve", fields{false, constants.IncorrectFormat}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if got := transactionResponse.IsSuccessful(); got != tt.want { + t.Errorf("IsSuccessful() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/identities/internal/transactions/define/transaction.go b/modules/identities/internal/transactions/define/transaction.go new file mode 100644 index 000000000..f4c9961d7 --- /dev/null +++ b/modules/identities/internal/transactions/define/transaction.go @@ -0,0 +1,25 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "define", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.ImmutableMetaProperties, + constants.ImmutableProperties, + constants.MutableMetaProperties, + constants.MutableProperties, +) diff --git a/modules/identities/internal/transactions/deputize/keeper.go b/modules/identities/internal/transactions/deputize/keeper.go new file mode 100644 index 000000000..d390f3e2c --- /dev/null +++ b/modules/identities/internal/transactions/deputize/keeper.go @@ -0,0 +1,57 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/deputize" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + deputizeAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + if auxiliaryResponse := transactionKeeper.deputizeAuxiliary.GetKeeper().Help(context, deputize.NewAuxiliaryRequest(message.FromID, message.ToID, message.ClassificationID, message.MaintainedProperties, message.CanMintAsset, message.CanBurnAsset, message.CanRenumerateAsset, message.CanAddMaintainer, message.CanRemoveMaintainer, message.CanMutateMaintainer)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + return newTransactionResponse(nil) +} +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case deputize.Auxiliary.GetName(): + transactionKeeper.deputizeAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(constants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/identities/internal/transactions/deputize/message.go b/modules/identities/internal/transactions/deputize/message.go index f98521bc3..093724087 100644 --- a/modules/identities/internal/transactions/deputize/message.go +++ b/modules/identities/internal/transactions/deputize/message.go @@ -1,74 +1,85 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/identities/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ToID ids.IdentityID `json:"toID" valid:"required~required field toID missing"` + ClassificationID ids.ClassificationID `json:"classificationID" valid:"required~required field classificationID missing"` + MaintainedProperties lists.PropertyList `json:"maintainedProperties" valid:"required~required field maintainedProperties missing"` + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + if len(message.MaintainedProperties.GetList()) == 0 { + message.MaintainedProperties = base.NewPropertyList(nil) + } + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, toID types.ID, classificationID types.ID, maintainedProperties types.Properties, addMaintainer bool, removeMaintainer bool, mutateMaintainer bool) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - ToID: *base.NewID(toID.String()), - ClassificationID: *base.NewID(classificationID.String()), - MaintainedProperties: *base.NewProperties(maintainedProperties.GetList()...), - AddMaintainer: addMaintainer, - RemoveMaintainer: removeMaintainer, - MutateMaintainer: mutateMaintainer, +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, toID ids.IdentityID, classificationID ids.ClassificationID, maintainedProperties lists.PropertyList, canMintAsset bool, canBurnAsset bool, canRenumerateAsset bool, canAddMaintainer bool, canRemoveMaintainer bool, canMutateMaintainer bool) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + ToID: toID, + ClassificationID: classificationID, + MaintainedProperties: maintainedProperties, + CanMintAsset: canMintAsset, + CanBurnAsset: canBurnAsset, + CanRenumerateAsset: canRenumerateAsset, + CanAddMaintainer: canAddMaintainer, + CanRemoveMaintainer: canRemoveMaintainer, + CanMutateMaintainer: canMutateMaintainer, } } diff --git a/modules/identities/internal/transactions/deputize/message.pb.go b/modules/identities/internal/transactions/deputize/message.pb.go deleted file mode 100644 index 7684a3cd4..000000000 --- a/modules/identities/internal/transactions/deputize/message.pb.go +++ /dev/null @@ -1,831 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/transactions/deputize/message.proto - -package deputize - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field from missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field fromID missing"` - ToID base.ID `protobuf:"bytes,3,opt,name=to_i_d,json=toID,proto3" json:"to_i_d" valid:"required~required field toID missing"` - ClassificationID base.ID `protobuf:"bytes,4,opt,name=classification_i_d,json=classificationID,proto3" json:"classification_i_d" valid:"required~required field classificationID missing"` - MaintainedProperties base.Properties `protobuf:"bytes,5,opt,name=maintained_properties,json=maintainedProperties,proto3" json:"maintained_properties" valid:"required~required field maintainedProperties missing"` - AddMaintainer bool `protobuf:"varint,6,opt,name=add_maintainer,json=addMaintainer,proto3" json:"add_maintainer,omitempty"` - RemoveMaintainer bool `protobuf:"varint,7,opt,name=remove_maintainer,json=removeMaintainer,proto3" json:"remove_maintainer,omitempty"` - MutateMaintainer bool `protobuf:"varint,8,opt,name=mutate_maintainer,json=mutateMaintainer,proto3" json:"mutate_maintainer,omitempty"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_f3062f28d652d259, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_f3062f28d652d259, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "modules.identities.internal.transactions.deputize.Message") - proto.RegisterType((*TransactionResponse)(nil), "modules.identities.internal.transactions.deputize.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/transactions/deputize/message.proto", fileDescriptor_f3062f28d652d259) -} - -var fileDescriptor_f3062f28d652d259 = []byte{ - // 573 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x94, 0x4f, 0x6b, 0x13, 0x41, - 0x18, 0xc6, 0x77, 0x6c, 0x4d, 0xe3, 0x88, 0x52, 0xd7, 0x16, 0x42, 0x0f, 0xbb, 0x4b, 0xa0, 0x50, - 0xfc, 0x33, 0x8b, 0x55, 0x44, 0x8a, 0x07, 0x1b, 0xa2, 0x50, 0x24, 0x54, 0xa2, 0xa7, 0x5e, 0xc2, - 0x64, 0xe7, 0xcd, 0x76, 0x30, 0xbb, 0xb3, 0x9d, 0x99, 0x54, 0x14, 0xf4, 0xec, 0x49, 0xf4, 0xa0, - 0xe7, 0x1e, 0xfd, 0x28, 0x3d, 0xf6, 0xa6, 0x78, 0x08, 0x92, 0x5c, 0x3c, 0xf7, 0x13, 0xc8, 0xfe, - 0x49, 0x76, 0x13, 0x0b, 0x49, 0x3c, 0xed, 0xec, 0xbc, 0xcf, 0xfb, 0xfc, 0x9e, 0x81, 0x99, 0x17, - 0xef, 0x47, 0x20, 0x15, 0x57, 0x1a, 0x42, 0x0f, 0x5a, 0x8a, 0xbd, 0x76, 0x03, 0xc1, 0x7a, 0x5d, - 0x50, 0x2e, 0x67, 0x10, 0x6a, 0xae, 0x79, 0xbc, 0x0c, 0x35, 0xc8, 0x90, 0x76, 0x5d, 0x2d, 0x69, - 0xa8, 0xa8, 0xa7, 0xb9, 0x08, 0x95, 0xcb, 0x20, 0xea, 0x69, 0xfe, 0x0e, 0xdc, 0x00, 0x94, 0xa2, - 0x3e, 0x90, 0x48, 0x0a, 0x2d, 0xcc, 0x7b, 0x99, 0x01, 0xc9, 0x0d, 0xc8, 0xc8, 0x80, 0x14, 0x0d, - 0xc8, 0xc8, 0x60, 0x63, 0xcd, 0x17, 0xbe, 0x48, 0xba, 0xdd, 0x78, 0x95, 0x1a, 0x6d, 0xdc, 0x9a, - 0x4e, 0xa6, 0xbc, 0x43, 0x08, 0xa8, 0xab, 0xdf, 0x46, 0xa0, 0xdc, 0x36, 0x55, 0xe0, 0x72, 0x96, - 0x69, 0xb7, 0x67, 0x6b, 0x23, 0x29, 0x22, 0x90, 0x49, 0x9c, 0xa4, 0xa7, 0xfa, 0xa3, 0x84, 0x57, - 0x1a, 0x69, 0x74, 0xf3, 0x0b, 0xc2, 0xcb, 0x1d, 0x29, 0x82, 0x0a, 0x72, 0xd0, 0xd6, 0x95, 0xda, - 0xfb, 0xd3, 0xbe, 0x6d, 0xfc, 0xea, 0xdb, 0x4f, 0x7d, 0xae, 0x0f, 0x7b, 0x6d, 0xe2, 0x89, 0xc0, - 0x2d, 0x10, 0xf6, 0x43, 0x28, 0xfe, 0xbe, 0xac, 0x3f, 0xff, 0x97, 0x47, 0x76, 0x3d, 0x6f, 0x97, - 0x31, 0x09, 0x4a, 0x9d, 0xf7, 0xed, 0x3b, 0xc7, 0xb4, 0xcb, 0xd9, 0x4e, 0x55, 0xc2, 0x51, 0x8f, - 0x4b, 0x60, 0x1f, 0x46, 0x0b, 0xa7, 0xc3, 0xa1, 0xcb, 0x9c, 0x98, 0xed, 0x04, 0x5c, 0x29, 0x1e, - 0xfa, 0xd5, 0x66, 0x12, 0xc5, 0x7c, 0x83, 0xcb, 0xf1, 0xb7, 0xc5, 0x5b, 0xac, 0x72, 0xc9, 0x41, - 0x5b, 0x57, 0xb7, 0x37, 0xc9, 0xd4, 0x31, 0x49, 0x8a, 0x25, 0x09, 0x96, 0x24, 0xd8, 0xbd, 0x7a, - 0xed, 0x61, 0x9c, 0xfe, 0xbc, 0x6f, 0x93, 0x39, 0xa0, 0x7b, 0xf5, 0x1c, 0x5b, 0x4a, 0x37, 0xcc, - 0x23, 0x5c, 0xd2, 0x22, 0xc1, 0x2e, 0x2d, 0x82, 0x7d, 0x90, 0x61, 0x67, 0x9d, 0x55, 0x8b, 0x22, - 0x74, 0x39, 0xfe, 0x35, 0xbf, 0x22, 0x6c, 0x7a, 0x5d, 0xaa, 0x14, 0xef, 0x70, 0x8f, 0xc6, 0xd7, - 0x23, 0xe1, 0x2f, 0x2f, 0xc2, 0x7f, 0x92, 0xf1, 0x1f, 0xcd, 0xe0, 0x4f, 0x72, 0x8a, 0x59, 0x56, - 0xa7, 0x4b, 0xe6, 0x77, 0x84, 0xd7, 0x03, 0xca, 0x43, 0x4d, 0x79, 0x08, 0xac, 0x95, 0xdf, 0xa1, - 0xca, 0xe5, 0x24, 0xda, 0xdd, 0x39, 0xa2, 0xbd, 0x18, 0x37, 0xd5, 0xea, 0x59, 0xc4, 0xc7, 0x33, - 0x22, 0xe6, 0xc8, 0xbc, 0x39, 0x8f, 0xb9, 0x76, 0x51, 0xd9, 0xdc, 0xc4, 0xd7, 0x29, 0x63, 0xad, - 0x71, 0x4d, 0x56, 0x4a, 0x0e, 0xda, 0x2a, 0x37, 0xaf, 0x51, 0xc6, 0x1a, 0xe3, 0x4d, 0xf3, 0x36, - 0xbe, 0x21, 0x21, 0x10, 0xc7, 0x50, 0x54, 0xae, 0x24, 0xca, 0xd5, 0xb4, 0x30, 0x29, 0x0e, 0x7a, - 0x9a, 0xea, 0x09, 0x71, 0x39, 0x15, 0xa7, 0x85, 0x5c, 0xbc, 0x53, 0xfe, 0x78, 0x62, 0x1b, 0x7f, - 0x4e, 0x6c, 0xa3, 0xba, 0x8e, 0x6f, 0xbe, 0xca, 0x1f, 0x7a, 0x13, 0x54, 0x24, 0x42, 0x05, 0xdb, - 0xdf, 0x10, 0x5e, 0x6a, 0x28, 0xdf, 0xfc, 0x84, 0x70, 0xb9, 0x9e, 0xbd, 0x7d, 0x73, 0x87, 0x2c, - 0x3c, 0x2f, 0x48, 0xf6, 0x6a, 0x37, 0x9e, 0xfd, 0x47, 0xef, 0x05, 0xc1, 0x6a, 0xfa, 0x74, 0x60, - 0xa1, 0xb3, 0x81, 0x85, 0x7e, 0x0f, 0x2c, 0xf4, 0x79, 0x68, 0x19, 0x67, 0x43, 0xcb, 0xf8, 0x39, - 0xb4, 0x8c, 0x83, 0x83, 0xb9, 0x07, 0xc0, 0xc2, 0x63, 0xb3, 0x5d, 0x4a, 0xc6, 0xd0, 0xfd, 0xbf, - 0x01, 0x00, 0x00, 0xff, 0xff, 0xef, 0xf0, 0xee, 0x36, 0x82, 0x05, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Deputize(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Deputize(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/modules.identities.internal.transactions.deputize.Msg/Deputize", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Deputize(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Deputize(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deputize not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Deputize_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Deputize(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/modules.identities.internal.transactions.deputize.Msg/Deputize", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Deputize(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "modules.identities.internal.transactions.deputize.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Deputize", - Handler: _Msg_Deputize_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/identities/internal/transactions/deputize/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.MutateMaintainer { - i-- - if m.MutateMaintainer { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x40 - } - if m.RemoveMaintainer { - i-- - if m.RemoveMaintainer { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x38 - } - if m.AddMaintainer { - i-- - if m.AddMaintainer { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x30 - } - { - size, err := m.MaintainedProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.ClassificationID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ToID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ToID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ClassificationID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MaintainedProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - if m.AddMaintainer { - n += 2 - } - if m.RemoveMaintainer { - n += 2 - } - if m.MutateMaintainer { - n += 2 - } - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ToID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ToID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaintainedProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MaintainedProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AddMaintainer", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.AddMaintainer = bool(v != 0) - case 7: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field RemoveMaintainer", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.RemoveMaintainer = bool(v != 0) - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MutateMaintainer", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.MutateMaintainer = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/transactions/deputize/message_test.go b/modules/identities/internal/transactions/deputize/message_test.go index 7b0635c88..5132e5eb3 100644 --- a/modules/identities/internal/transactions/deputize/message_test.go +++ b/modules/identities/internal/transactions/deputize/message_test.go @@ -1,44 +1,382 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( + "reflect" "testing" + "github.com/AssetMantle/modules/schema/lists/utilities" + + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/identities/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Deputize_Message(t *testing.T) { - testFromID := base.NewID("fromID") - testToID := base.NewID("toID") - testClassificationID := base.NewID("classificationID") - +func createTestInput(t *testing.T) (ids.IdentityID, ids.IdentityID, ids.ClassificationID, sdkTypes.AccAddress, lists.PropertyList) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) + testToID := baseIDs.NewIdentityID(testClassificationID, immutables) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) require.Nil(t, err) maintainedProperty := "maintainedProperty:S|maintainedProperty" - maintainedProperties, err := base.ReadProperties(maintainedProperty) - require.Equal(t, nil, err) - - testMessage := newMessage(fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, ToID: testToID, ClassificationID: testClassificationID, MaintainedProperties: maintainedProperties, AddMaintainer: false, RemoveMaintainer: false, MutateMaintainer: false}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) + maintainedProperties, err := utilities.ReadMetaPropertyList(maintainedProperty) + return testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties +} + +func Test_messageFromInterface(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties := createTestInput(t) + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + + {"+ve", args{message{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false, false, false, false}}, message{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false, false, false, false}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + fields fields + want []byte + }{ + + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false, false, false, false}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false, false, false, false}))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false, false, false, false}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false, false, false, false}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + fields fields + want string + }{ + + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false, false, false, false}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + fields fields + want string + }{ + + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false, false, false, false}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false, false, false, false}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties := createTestInput(t) + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + toID ids.IdentityID + classificationID ids.ClassificationID + maintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false, false, false, false}, message{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false, false, false, false}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.toID, tt.args.classificationID, tt.args.maintainedProperties, tt.args.CanMintAsset, tt.args.CanBurnAsset, tt.args.CanRenumerateAsset, tt.args.CanAddMaintainer, tt.args.CanRemoveMaintainer, tt.args.CanMutateMaintainer); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/identities/internal/transactions/deputize/msg_server.go b/modules/identities/internal/transactions/deputize/msg_server.go deleted file mode 100644 index 9ae3b4be7..000000000 --- a/modules/identities/internal/transactions/deputize/msg_server.go +++ /dev/null @@ -1,30 +0,0 @@ -package deputize - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/deputize" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Deputize(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - if auxiliaryResponse := msgServer.transactionKeeper.deputizeAuxiliary.GetKeeper().Help(ctx, deputize.NewAuxiliaryRequest(&message.FromID, &message.ToID, &message.ClassificationID, &message.MaintainedProperties, message.AddMaintainer, message.RemoveMaintainer, message.MutateMaintainer)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/identities/internal/transactions/deputize/request.go b/modules/identities/internal/transactions/deputize/request.go index 14df677d7..496f46216 100644 --- a/modules/identities/internal/transactions/deputize/request.go +++ b/modules/identities/internal/transactions/deputize/request.go @@ -1,23 +1,25 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( "encoding/json" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -26,42 +28,55 @@ type transactionRequest struct { ToID string `json:"toID" valid:"required~required field toID missing, matches(^[A-Za-z0-9-_=.|]+$)~invalid field toID"` ClassificationID string `json:"classificationID" valid:"required~required field classificationID missing, matches(^[A-Za-z0-9-_=.]+$)~invalid field classificationID"` MaintainedProperties string `json:"maintainedProperties" valid:"required~required field maintainedProperties missing, matches(^.*$)~invalid field maintainedProperties"` - AddMaintainer bool `json:"addMaintainer"` - RemoveMaintainer bool `json:"removeMaintainer"` - MutateMaintainer bool `json:"mutateMaintainer"` + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` } var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary deputize identities transaction -// @Descrption deputize transaction +// Validate godoc +// @Summary Deputize an identity +// @Description A transaction to deputize a maintainer for an identity classification. // @Accept text/plain // @Produce json // @Tags Identities -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body transactionRequest true "Request body to deputize identity" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /identities/deputize [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + if err != nil { + return err + } + inputValidator := base.NewInputValidator(constants.PropertyExpression) + if !inputValidator.IsValid(transactionRequest.MaintainedProperties) { + return errorConstants.IncorrectFormat + } + return nil } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ToID), - cliCommand.ReadString(flags.ClassificationID), - cliCommand.ReadString(flags.MaintainedProperties), - cliCommand.ReadBool(flags.AddMaintainer), - cliCommand.ReadBool(flags.RemoveMaintainer), - cliCommand.ReadBool(flags.MutateMaintainer), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ToID), + cliCommand.ReadString(constants.ClassificationID), + cliCommand.ReadString(constants.MaintainedProperties), + cliCommand.ReadBool(constants.CanMintAsset), + cliCommand.ReadBool(constants.CanBurnAsset), + cliCommand.ReadBool(constants.CanRenumerateAsset), + cliCommand.ReadBool(constants.CanAddMaintainer), + cliCommand.ReadBool(constants.CanRemoveMaintainer), + cliCommand.ReadBool(constants.CanMutateMaintainer), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -70,43 +85,63 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + maintainedProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MaintainedProperties) + if err != nil { + return nil, err } - maintainedProperties, Error := base.ReadProperties(transactionRequest.MaintainedProperties) - if Error != nil { - return nil, Error + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + toID, err := baseIDs.ReadIdentityID(transactionRequest.ToID) + if err != nil { + return nil, err + } + + classificationID, err := baseIDs.ReadClassificationID(transactionRequest.ClassificationID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.ToID), - base.NewID(transactionRequest.ClassificationID), + fromID, + toID, + classificationID, maintainedProperties, - transactionRequest.AddMaintainer, - transactionRequest.RemoveMaintainer, - transactionRequest.MutateMaintainer, + transactionRequest.CanMintAsset, + transactionRequest.CanBurnAsset, + transactionRequest.CanRenumerateAsset, + transactionRequest.CanAddMaintainer, + transactionRequest.CanRemoveMaintainer, + transactionRequest.CanMutateMaintainer, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} } - -func newTransactionRequest(baseReq rest.BaseReq, fromID string, toID string, classificationID string, maintainedProperties string, addMaintainer bool, removeMaintainer bool, mutateMaintainer bool) helpers.TransactionRequest { +func newTransactionRequest(baseReq rest.BaseReq, fromID string, toID string, classificationID string, maintainedProperties string, canMintAsset bool, canBurnAsset bool, canRenumerateAsset bool, canAddMaintainer bool, canRemoveMaintainer bool, canMutateMaintainer bool) helpers.TransactionRequest { return transactionRequest{ BaseReq: baseReq, FromID: fromID, ToID: toID, ClassificationID: classificationID, MaintainedProperties: maintainedProperties, - AddMaintainer: addMaintainer, - RemoveMaintainer: removeMaintainer, - MutateMaintainer: mutateMaintainer, + CanMintAsset: canMintAsset, + CanBurnAsset: canBurnAsset, + CanRenumerateAsset: canRenumerateAsset, + CanAddMaintainer: canAddMaintainer, + CanRemoveMaintainer: canRemoveMaintainer, + CanMutateMaintainer: canMutateMaintainer, } } diff --git a/modules/identities/internal/transactions/deputize/request_test.go b/modules/identities/internal/transactions/deputize/request_test.go index 6a72729e4..21c52bdb0 100644 --- a/modules/identities/internal/transactions/deputize/request_test.go +++ b/modules/identities/internal/transactions/deputize/request_test.go @@ -1,82 +1,389 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( "encoding/json" + "reflect" "testing" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/stretchr/testify/require" - - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" ) -func Test_Deputize_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.ToID, flags.ClassificationID, flags.MaintainedProperties, flags.AddMaintainer, flags.RemoveMaintainer, flags.MutateMaintainer}) - cliContext := context.NewCLIContext().WithCodec(Codec) +func Test_newTransactionRequest(t *testing.T) { fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, err) maintainedProperty := "maintainedProperties:S|maintainedProperties" - maintainedProperties, err := base.ReadProperties(maintainedProperty) - require.Equal(t, nil, err) testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID", maintainedProperty, false, false, false) + type args struct { + baseReq rest.BaseReq + fromID string + toID string + classificationID string + maintainedProperties string + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseReq, "fromID", "toID", "classificationID", maintainedProperty, false, false, false, false, false, false}, transactionRequest{testBaseReq, "fromID", "toID", "classificationID", maintainedProperty, false, false, false, false, false, false}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.toID, tt.args.classificationID, tt.args.maintainedProperties, tt.args.CanMintAsset, tt.args.CanBurnAsset, tt.args.CanRenumerateAsset, tt.args.CanAddMaintainer, tt.args.CanRemoveMaintainer, tt.args.CanMutateMaintainer); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ToID: "toID", ClassificationID: "classificationID", MaintainedProperties: maintainedProperty, AddMaintainer: false, RemoveMaintainer: false, MutateMaintainer: false}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - requestFromCLI, err := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, err) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ToID: "", ClassificationID: "", MaintainedProperties: "", AddMaintainer: false, RemoveMaintainer: false, MutateMaintainer: false}, requestFromCLI) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.ToID, constants.ClassificationID, constants.MaintainedProperties, constants.CanMintAsset, constants.CanBurnAsset, constants.CanRenumerateAsset, constants.CanAddMaintainer, constants.CanRemoveMaintainer, constants.CanMutateMaintainer}) + cliContext := context.NewCLIContext().WithCodec(codec.Cdc) - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, err := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, err) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ToID: "", ClassificationID: "", MaintainedProperties: "", CanMintAsset: false, CanBurnAsset: false, CanRenumerateAsset: false, CanAddMaintainer: false, CanRemoveMaintainer: false, CanMutateMaintainer: false}, args{cliCommand, cliContext}, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ToID: "", ClassificationID: "", MaintainedProperties: "", CanAddMaintainer: false, CanRemoveMaintainer: false, CanMutateMaintainer: false}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, err := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, err) +func Test_transactionRequest_FromJSON(t *testing.T) { - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - msg, err := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("toID"), base.NewID("classificationID"), maintainedProperties, false, false, false), msg) - require.Nil(t, err) + maintainedProperty := "maintainedProperties:S|maintainedProperties" + + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} + jsonMessage, _ := json.Marshal(newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID", maintainedProperty, false, false, false, false, false, false)) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, "fromID", "toID", "classificationID", maintainedProperty, false, false, false, false, false, false}, args{jsonMessage}, transactionRequest{testBaseReq, "fromID", "toID", "classificationID", maintainedProperty, false, false, false, false, false, false}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionRequest_GetBaseReq(t *testing.T) { + + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + + maintainedProperty := "maintainedProperties:S|maintainedProperties" + + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseReq, "fromID", "toID", "classificationID", maintainedProperty, false, false, false, false, false, false}, testBaseReq}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg2, err := newTransactionRequest(rest.BaseReq{From: "randomString", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "toID", "classificationID", maintainedProperty, false, false, false).MakeMsg() - require.NotNil(t, err) - require.Nil(t, msg2) +func Test_transactionRequest_MakeMsg(t *testing.T) { - msg2, err = newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID", "randomString", false, false, false).MakeMsg() - require.NotNil(t, err) - require.Nil(t, msg2) + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties := createTestInput(t) - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) + testBaseReq := rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()} + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + fields fields + want sdkTypes.Msg + wantErr bool + }{ + {"+ve", fields{testBaseReq, testFromID.String(), testFromID.String(), testClassificationID.String(), "maintainedProperty:S|maintainedProperty", false, false, false, false, false, false}, newMessage(fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, false, false, false, false, false, false), false}, // TODO: issue==> getting MetaDataError that is not expected + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionRequest_RegisterCodec(t *testing.T) { + + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + + maintainedProperty := "maintainedProperties:S|maintainedProperties" + + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseReq, "fromID", "toID", "classificationID", maintainedProperty, false, false, false, false, false, false}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_transactionRequest_Validate(t *testing.T) { + + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + + maintainedProperty := "maintainedProperties:S|maintainedProperties" + + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseReq, "fromID", "toID", "classificationID", maintainedProperty, false, false, false, false, false, false}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/identities/internal/transactions/deputize/response.go b/modules/identities/internal/transactions/deputize/response.go new file mode 100644 index 000000000..f6c13abcf --- /dev/null +++ b/modules/identities/internal/transactions/deputize/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/identities/internal/transactions/deputize/response_test.go b/modules/identities/internal/transactions/deputize/response_test.go new file mode 100644 index 000000000..792b0d5da --- /dev/null +++ b/modules/identities/internal/transactions/deputize/response_test.go @@ -0,0 +1,88 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + "reflect" + "testing" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +func Test_newTransactionResponse(t *testing.T) { + type args struct { + error error + } + tests := []struct { + name string + args args + want helpers.TransactionResponse + }{ + + {"+ve", args{error: nil}, transactionResponse{Success: true, Error: nil}}, + {"-ve", args{error: constants.IncorrectFormat}, transactionResponse{Success: false, Error: constants.IncorrectFormat}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionResponse(tt.args.error); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionResponse() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionResponse_GetError(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + + {"+ve", fields{Success: true, Error: nil}, false}, + {"-ve", fields{Success: false, Error: constants.IncorrectFormat}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if err := transactionResponse.GetError(); (err != nil) != tt.wantErr { + t.Errorf("GetError() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_transactionResponse_IsSuccessful(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + want bool + }{ + + {"+ve", fields{Success: true, Error: nil}, true}, + {"-ve", fields{Success: false, Error: constants.IncorrectFormat}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if got := transactionResponse.IsSuccessful(); got != tt.want { + t.Errorf("IsSuccessful() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/identities/internal/transactions/deputize/transaction.go b/modules/identities/internal/transactions/deputize/transaction.go new file mode 100644 index 000000000..ba0b78dd2 --- /dev/null +++ b/modules/identities/internal/transactions/deputize/transaction.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "deputize", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.ToID, + constants.ClassificationID, + constants.MaintainedProperties, + constants.CanMintAsset, + constants.CanBurnAsset, + constants.CanRenumerateAsset, + constants.CanAddMaintainer, + constants.CanRemoveMaintainer, + constants.CanMutateMaintainer, +) diff --git a/modules/identities/internal/transactions/issue/keeper.go b/modules/identities/internal/transactions/issue/keeper.go new file mode 100644 index 000000000..47aa3b0d2 --- /dev/null +++ b/modules/identities/internal/transactions/issue/keeper.go @@ -0,0 +1,92 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package issue + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/verify" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/properties/constants" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + authenticateAuxiliary helpers.Auxiliary + conformAuxiliary helpers.Auxiliary + maintainersVerifyAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + + if auxiliaryResponse := transactionKeeper.maintainersVerifyAuxiliary.GetKeeper().Help(context, verify.NewAuxiliaryRequest(message.ClassificationID, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(append(message.ImmutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...)...)) + + identityID := baseIDs.NewIdentityID(message.ClassificationID, immutables) + + identities := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(identityID)) + if identities.Get(key.NewKey(identityID)) != nil { + return newTransactionResponse(errorConstants.EntityAlreadyExists) + } + + authenticationProperty := baseProperties.NewMetaProperty(constants.AuthenticationProperty.GetKey(), baseData.NewListData(baseLists.NewDataList(baseData.NewAccAddressData(message.To)))) + mutableMetaProperties := baseLists.NewPropertyList(append(message.MutableMetaProperties.GetList(), authenticationProperty)...) + + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(append(mutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...)) + + if auxiliaryResponse := transactionKeeper.conformAuxiliary.GetKeeper().Help(context, conform.NewAuxiliaryRequest(message.ClassificationID, immutables, mutables)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + identities.Add(mappable.NewMappable(base.NewIdentity(message.ClassificationID, immutables, mutables))) + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper = mapper + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case conform.Auxiliary.GetName(): + transactionKeeper.conformAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + case verify.Auxiliary.GetName(): + transactionKeeper.maintainersVerifyAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} + +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/identities/internal/transactions/issue/keeper_test.go b/modules/identities/internal/transactions/issue/keeper_test.go new file mode 100644 index 000000000..cd57f1929 --- /dev/null +++ b/modules/identities/internal/transactions/issue/keeper_test.go @@ -0,0 +1,198 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package issue + +import ( + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/modules/identities/internal/parameters" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/verify" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type TestKeepers struct { + IssueKeeper helpers.TransactionKeeper +} + +var ( + Parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + conformAuxiliary helpers.Auxiliary + maintainersVerifyAuxiliary helpers.Auxiliary +) + +func CreateTestInput(t *testing.T) (types.Context, TestKeepers, helpers.Mapper) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := types.NewKVStoreKey("test") + paramsStoreKey := types.NewKVStoreKey("testParams") + paramsTransientStoreKeys := types.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters = parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, types.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := types.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + conformAuxiliary = conform.AuxiliaryMock.Initialize(Mapper, Parameters) + maintainersVerifyAuxiliary = verify.AuxiliaryMock.Initialize(Mapper, Parameters) + keepers := TestKeepers{ + IssueKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{authenticateAuxiliary, conformAuxiliary, maintainersVerifyAuxiliary}).(helpers.TransactionKeeper), + } + + return context, keepers, Mapper +} + +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper := CreateTestInput(t) + type fields struct { + mapper helpers.Mapper + authenticateAuxiliary helpers.Auxiliary + conformAuxiliary helpers.Auxiliary + maintainersVerifyAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve with nil", fields{}, args{}, transactionKeeper{}}, + {"+ve", fields{Mapper, authenticateAuxiliary, conformAuxiliary, maintainersVerifyAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, authenticateAuxiliary, conformAuxiliary, maintainersVerifyAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + conformAuxiliary: tt.fields.conformAuxiliary, + maintainersVerifyAuxiliary: tt.fields.maintainersVerifyAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.in1, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, mapper := CreateTestInput(t) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + toAddress := "cosmos1x53dugvr4xvew442l9v2r5x7j8gfvged2zk5ef" + toAccAddress, err := types.AccAddressFromBech32(toAddress) + require.Nil(t, err) + immutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData"))) + immutableProperties := baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIds.NewStringID("ID11"), baseData.NewStringData("ImmutableData"))) + mutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutableProperties := baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIds.NewStringID("authentication"), baseData.NewStringData("MutableData"))) + immutables := baseQualified.NewImmutables(immutableMetaProperties) + mutables := baseQualified.NewMutables(mutableMetaProperties) + classificationID := baseIds.NewClassificationID(immutables, mutables) + fromIdentityID := baseIds.NewIdentityID(classificationID, immutables) + identity := baseDocuments.NewIdentity(classificationID, immutables, mutables) + identity = identity.ProvisionAddress([]types.AccAddress{fromAccAddress}...) + identity.Mutate(immutableMetaProperties.GetList()...) + keepers.IssueKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(identity)) + type fields struct { + mapper helpers.Mapper + authenticateAuxiliary helpers.Auxiliary + conformAuxiliary helpers.Auxiliary + maintainersVerifyAuxiliary helpers.Auxiliary + } + type args struct { + context types.Context + msg types.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + // NOTE: When test individually run 2nd test will fail + {"+ve", fields{mapper, authenticateAuxiliary, conformAuxiliary, maintainersVerifyAuxiliary}, args{context, newMessage(fromAccAddress, toAccAddress, fromIdentityID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)}, newTransactionResponse(nil)}, + {"+ve Entity Already Exists", fields{mapper, authenticateAuxiliary, conformAuxiliary, maintainersVerifyAuxiliary}, args{context, newMessage(fromAccAddress, toAccAddress, fromIdentityID, classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)}, newTransactionResponse(errorConstants.EntityAlreadyExists)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + conformAuxiliary: tt.fields.conformAuxiliary, + maintainersVerifyAuxiliary: tt.fields.maintainersVerifyAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/identities/internal/transactions/issue/message.go b/modules/identities/internal/transactions/issue/message.go index 07ad91f24..3044ae4d7 100644 --- a/modules/identities/internal/transactions/issue/message.go +++ b/modules/identities/internal/transactions/issue/message.go @@ -1,73 +1,87 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package issue import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/identities/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + To sdkTypes.AccAddress `json:"to" valid:"required~required field to missing, matches(^[a-z0-9]*$)~invalid field to"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ids.ClassificationID `json:"classificationID" valid:"required~required field classificationID missing"` + ImmutableMetaProperties lists.PropertyList `json:"immutableMetaProperties" valid:"required~required field immutableMetaProperties missing"` + ImmutableProperties lists.PropertyList `json:"immutableProperties" valid:"required~required field immutableProperties missing"` + MutableMetaProperties lists.PropertyList `json:"mutableMetaProperties" valid:"required~required field mutableMetaProperties missing"` + MutableProperties lists.PropertyList `json:"mutableProperties" valid:"required~required field mutableProperties missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + if len(message.ImmutableMetaProperties.GetList()) == 0 { + message.ImmutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.ImmutableProperties.GetList()) == 0 { + message.ImmutableProperties = base.NewPropertyList(nil) + } + if len(message.MutableMetaProperties.GetList()) == 0 { + message.MutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.MutableProperties.GetList()) == 0 { + message.MutableProperties = base.NewPropertyList(nil) + } + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, to sdkTypes.AccAddress, fromID types.ID, classificationID types.ID, immutableMetaProperties types.MetaProperties, immutableProperties types.Properties, mutableMetaProperties types.MetaProperties, mutableProperties types.Properties) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - To: base.NewAccAddressFromSDKTypesAccAddress(to), - FromID: *base.NewID(fromID.String()), - ClassificationID: *base.NewID(classificationID.String()), - ImmutableMetaProperties: *base.NewMetaProperties(immutableMetaProperties.GetList()...), - ImmutableProperties: *base.NewProperties(immutableProperties.GetList()...), - MutableMetaProperties: *base.NewMetaProperties(mutableMetaProperties.GetList()...), - MutableProperties: *base.NewProperties(mutableProperties.GetList()...), +func newMessage(from sdkTypes.AccAddress, to sdkTypes.AccAddress, fromID ids.IdentityID, classificationID ids.ClassificationID, immutableMetaProperties lists.PropertyList, immutableProperties lists.PropertyList, mutableMetaProperties lists.PropertyList, mutableProperties lists.PropertyList) sdkTypes.Msg { + return message{ + From: from, + To: to, + FromID: fromID, + ClassificationID: classificationID, + ImmutableMetaProperties: immutableMetaProperties, + ImmutableProperties: immutableProperties, + MutableMetaProperties: mutableMetaProperties, + MutableProperties: mutableProperties, } } diff --git a/modules/identities/internal/transactions/issue/message.pb.go b/modules/identities/internal/transactions/issue/message.pb.go deleted file mode 100644 index 63050758b..000000000 --- a/modules/identities/internal/transactions/issue/message.pb.go +++ /dev/null @@ -1,871 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/transactions/issue/message.proto - -package issue - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - To github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,2,opt,name=to,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"to" valid:"required~required field To missing"` - FromID base.ID `protobuf:"bytes,3,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - ClassificationID base.ID `protobuf:"bytes,4,opt,name=classification_i_d,json=classificationID,proto3" json:"classification_i_d" valid:"required~required field ClassificationID missing"` - ImmutableMetaProperties base.MetaProperties `protobuf:"bytes,5,opt,name=immutable_meta_properties,json=immutableMetaProperties,proto3" json:"immutable_meta_properties" valid:"required~required field ImmutableMetaProperties missing"` - ImmutableProperties base.Properties `protobuf:"bytes,6,opt,name=immutable_properties,json=immutableProperties,proto3" json:"immutable_properties" valid:"required~required field ImmutableProperties missing"` - MutableMetaProperties base.MetaProperties `protobuf:"bytes,7,opt,name=mutable_meta_properties,json=mutableMetaProperties,proto3" json:"mutable_meta_properties" valid:"required~required field MutableMetaProperties missing"` - MutableProperties base.Properties `protobuf:"bytes,8,opt,name=mutable_properties,json=mutableProperties,proto3" json:"mutable_properties" valid:"required~required field MutableProperties missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_dc77da3b012079a2, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_dc77da3b012079a2, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "modules.identities.internal.transactions.issue.Message") - proto.RegisterType((*TransactionResponse)(nil), "modules.identities.internal.transactions.issue.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/transactions/issue/message.proto", fileDescriptor_dc77da3b012079a2) -} - -var fileDescriptor_dc77da3b012079a2 = []byte{ - // 618 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0xd5, 0xcf, 0x6b, 0x13, 0x41, - 0x1c, 0x05, 0xf0, 0x9d, 0xfe, 0xee, 0x78, 0xd1, 0x69, 0x4b, 0x63, 0x0f, 0xbb, 0x21, 0x20, 0x94, - 0xa2, 0xb3, 0x58, 0xa1, 0x6a, 0x45, 0xb4, 0x69, 0xaa, 0x04, 0x0d, 0x4a, 0x2d, 0x08, 0x5e, 0xc2, - 0x66, 0x77, 0xb2, 0x1d, 0xdc, 0xdd, 0xd9, 0xee, 0x4c, 0x14, 0x11, 0xbd, 0x09, 0x82, 0x08, 0x7a, - 0xf0, 0x6c, 0x2f, 0xde, 0x3d, 0xf9, 0x37, 0xf4, 0xd8, 0xa3, 0x78, 0x08, 0x92, 0x5c, 0x3c, 0xf7, - 0xec, 0x41, 0x76, 0xb2, 0x61, 0x37, 0xc9, 0xea, 0x6e, 0x8a, 0xb7, 0x4d, 0x76, 0x5e, 0xbe, 0x9f, - 0x3c, 0x86, 0x19, 0x78, 0xdf, 0x27, 0x01, 0xa7, 0x5c, 0x10, 0xcf, 0x24, 0x75, 0x6e, 0x3d, 0xd5, - 0x5d, 0x66, 0xb5, 0x1c, 0xc2, 0x75, 0x6a, 0x11, 0x4f, 0x50, 0x41, 0xc3, 0x47, 0x4f, 0x90, 0xc0, - 0x33, 0x1c, 0x5d, 0x04, 0x86, 0xc7, 0x0d, 0x53, 0x50, 0xe6, 0x71, 0x9d, 0x72, 0xde, 0x22, 0xba, - 0x4b, 0x38, 0x37, 0x6c, 0x82, 0xfd, 0x80, 0x09, 0x86, 0x70, 0x94, 0xc6, 0x71, 0x1a, 0xf7, 0xd3, - 0x38, 0x99, 0xc6, 0x32, 0xbd, 0xb2, 0x68, 0x33, 0x9b, 0xc9, 0xa8, 0x1e, 0x3e, 0xf5, 0x7e, 0x65, - 0x65, 0x6d, 0xd8, 0xc4, 0xcd, 0x7d, 0xe2, 0x1a, 0xba, 0x78, 0xe1, 0x13, 0xae, 0x37, 0x0c, 0x4e, - 0x74, 0x6a, 0x45, 0x6b, 0xd7, 0xb3, 0xd7, 0xfa, 0x01, 0xf3, 0x49, 0x20, 0x2d, 0xbd, 0xcc, 0x46, - 0x76, 0xc6, 0x25, 0xc2, 0x78, 0x38, 0x94, 0x2b, 0xfd, 0x9e, 0x87, 0xb3, 0xb5, 0xde, 0xff, 0x45, - 0x1f, 0x01, 0x9c, 0x6a, 0x06, 0xcc, 0x2d, 0x80, 0x22, 0x58, 0x9d, 0x2f, 0xbf, 0x3a, 0x6a, 0x6b, - 0xca, 0x8f, 0xb6, 0xb6, 0x63, 0x53, 0xb1, 0xdf, 0x6a, 0x60, 0x93, 0xb9, 0x7a, 0x62, 0xca, 0x03, - 0x8f, 0x24, 0x3f, 0x3e, 0xaa, 0xdc, 0x1b, 0x9d, 0x89, 0xb7, 0x4c, 0x73, 0xcb, 0xb2, 0x02, 0xc2, - 0xf9, 0x49, 0x5b, 0xbb, 0xf8, 0xcc, 0x70, 0xa8, 0xb5, 0x59, 0x0a, 0xc8, 0x41, 0x8b, 0x06, 0xc4, - 0x7a, 0xdd, 0x7f, 0x28, 0x36, 0x29, 0x71, 0xac, 0xe2, 0x9d, 0x80, 0xb9, 0x45, 0x97, 0x72, 0x4e, - 0x3d, 0xbb, 0xb4, 0x2b, 0x29, 0xe8, 0x1d, 0x80, 0x13, 0x82, 0x15, 0x26, 0xa4, 0xe8, 0xe5, 0xff, - 0x16, 0xad, 0x65, 0x88, 0xf6, 0x58, 0xec, 0x99, 0x10, 0x0c, 0x3d, 0x87, 0x73, 0xa1, 0xaa, 0x4e, - 0xeb, 0x56, 0x61, 0xb2, 0x08, 0x56, 0xcf, 0xac, 0x5f, 0xc0, 0x43, 0xc5, 0xe3, 0xde, 0x48, 0x2c, - 0x47, 0x62, 0x39, 0xb2, 0x5a, 0x29, 0x6f, 0x84, 0xf2, 0x93, 0xb6, 0x86, 0x73, 0x54, 0x50, 0xad, - 0xc4, 0x43, 0x67, 0x9a, 0xf2, 0x0b, 0xf4, 0x09, 0x40, 0x64, 0x3a, 0x06, 0xe7, 0xb4, 0x49, 0x4d, - 0x23, 0xdc, 0x6e, 0xd2, 0x30, 0x35, 0x8e, 0xe1, 0x76, 0x64, 0xb8, 0x96, 0x61, 0xd8, 0x1e, 0x98, - 0x93, 0xd4, 0x9c, 0x35, 0x87, 0x5e, 0xa1, 0x6f, 0x00, 0x9e, 0xa7, 0xae, 0xdb, 0x12, 0x46, 0xc3, - 0x21, 0xf5, 0x70, 0x87, 0xd5, 0xe3, 0xad, 0x59, 0x98, 0x96, 0xbc, 0xcb, 0x39, 0x78, 0xb5, 0x81, - 0xbd, 0x59, 0xbe, 0x1b, 0x51, 0x6f, 0x65, 0x50, 0xab, 0xfd, 0xd1, 0x83, 0xf9, 0x58, 0xbc, 0x4c, - 0xd3, 0x57, 0xa0, 0x2f, 0x00, 0x2e, 0xc6, 0xf0, 0x84, 0x79, 0x46, 0x9a, 0x2f, 0xe5, 0x30, 0x27, - 0xbc, 0xdb, 0x91, 0xf7, 0x46, 0x5e, 0x6f, 0x9a, 0x75, 0x81, 0x8e, 0xbe, 0x45, 0x5f, 0x01, 0x5c, - 0xfe, 0x5b, 0xbd, 0xb3, 0xa7, 0xad, 0x77, 0x27, 0xe2, 0xde, 0xcc, 0xe0, 0xd6, 0xfe, 0x5d, 0xee, - 0x52, 0x7a, 0xb5, 0x9f, 0x01, 0x44, 0x29, 0xc5, 0xce, 0x9d, 0xa6, 0xd8, 0xad, 0x48, 0x7a, 0x3d, - 0x9f, 0x34, 0x4d, 0x79, 0x6e, 0xa4, 0xd4, 0xcd, 0xb9, 0xb7, 0x87, 0x9a, 0xf2, 0xeb, 0x50, 0x53, - 0x4a, 0x4b, 0x70, 0x61, 0x2f, 0x3e, 0xc2, 0x77, 0x09, 0xf7, 0x99, 0xc7, 0xc9, 0xfa, 0x7b, 0x00, - 0x27, 0x6b, 0xdc, 0x46, 0x6f, 0x00, 0x9c, 0xae, 0x86, 0xa7, 0x3a, 0xba, 0x3a, 0xe6, 0x35, 0x80, - 0xa3, 0x43, 0x75, 0x65, 0x7b, 0xdc, 0x60, 0x8a, 0xa7, 0x7c, 0x70, 0xd4, 0x51, 0xc1, 0x71, 0x47, - 0x05, 0x3f, 0x3b, 0x2a, 0xf8, 0xd0, 0x55, 0x95, 0xe3, 0xae, 0xaa, 0x7c, 0xef, 0xaa, 0xca, 0x93, - 0xc7, 0xb9, 0x8f, 0xc2, 0xf1, 0x2e, 0xc1, 0xc6, 0x8c, 0xbc, 0x1f, 0xae, 0xfc, 0x09, 0x00, 0x00, - 0xff, 0xff, 0x82, 0x56, 0xab, 0x88, 0x4d, 0x07, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Issue(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Issue(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/modules.identities.internal.transactions.issue.Msg/Issue", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Issue(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Issue(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Issue not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Issue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Issue(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/modules.identities.internal.transactions.issue.Msg/Issue", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Issue(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "modules.identities.internal.transactions.issue.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Issue", - Handler: _Msg_Issue_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/identities/internal/transactions/issue/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - { - size, err := m.MutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size, err := m.ImmutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.ImmutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.ClassificationID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.To.Size() - i -= size - if _, err := m.To.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.To.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ClassificationID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field To", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.To.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/transactions/issue/message_test.go b/modules/identities/internal/transactions/issue/message_test.go index 08b699386..4816513f9 100644 --- a/modules/identities/internal/transactions/issue/message_test.go +++ b/modules/identities/internal/transactions/issue/message_test.go @@ -1,52 +1,359 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package issue import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/identities/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Issue_Message(t *testing.T) { - - testFromID := base.NewID("fromID") - testClassificationID := base.NewID("classificationID") - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - toAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - toAccAddress, Error := sdkTypes.AccAddressFromBech32(toAddress) - require.Nil(t, Error) - - immutableMetaProperties, Error := base.ReadMetaProperties("defaultImmutableMeta1:S|defaultImmutableMeta1") - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties("defaultImmutable1:S|defaultImmutable1") - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties("defaultMutableMeta1:S|defaultMutableMeta1") - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties("defaultMutable1:S|defaultMutable1") - require.Equal(t, nil, Error) - - testMessage := newMessage(fromAccAddress, toAccAddress, testFromID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties) - require.Equal(t, Message{From: fromAccAddress, To: toAccAddress, FromID: testFromID, ClassificationID: testClassificationID, ImmutableMetaProperties: immutableMetaProperties, ImmutableProperties: immutableProperties, MutableMetaProperties: mutableMetaProperties, MutableProperties: mutableProperties}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +func createTestInput(t *testing.T) (ids.IdentityID, ids.ClassificationID, string, sdkTypes.AccAddress, string, sdkTypes.AccAddress, lists.PropertyList, lists.PropertyList, lists.PropertyList, lists.PropertyList) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) + + const fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + + const toAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + var toAccAddress sdkTypes.AccAddress + toAccAddress, err = sdkTypes.AccAddressFromBech32(toAddress) + require.Nil(t, err) + + var immutableMetaProperties lists.PropertyList + immutableMetaProperties, err = utilities.ReadMetaPropertyList("defaultImmutableMeta1:S|defaultImmutableMeta1") + require.Equal(t, nil, err) + + var immutableProperties lists.PropertyList + immutableProperties, err = utilities.ReadMetaPropertyList("defaultImmutable1:S|defaultImmutable1") + require.Equal(t, nil, err) + + var mutableMetaProperties lists.PropertyList + mutableMetaProperties, err = utilities.ReadMetaPropertyList("defaultMutableMeta1:S|defaultMutableMeta1") + require.Equal(t, nil, err) + + var mutableProperties lists.PropertyList + mutableProperties, err = utilities.ReadMetaPropertyList("defaultMutable1:S|defaultMutable1") + require.Equal(t, nil, err) + + return testFromID, testClassificationID, fromAddress, fromAccAddress, toAddress, toAccAddress, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties +} + +func Test_messageFromInterface(t *testing.T) { + testFromID, testClassificationID, _, fromAccAddress, _, toAccAddress, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties := createTestInput(t) + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + + {"+ve", args{newMessage(fromAccAddress, toAccAddress, testFromID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)}, message{fromAccAddress, toAccAddress, testFromID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}}, + {"+ve with nil", args{}, message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + testFromID, testClassificationID, _, fromAccAddress, _, toAccAddress, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []byte + }{ + + {"+ve", fields{fromAccAddress, toAccAddress, testFromID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, toAccAddress, testFromID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + testFromID, testClassificationID, _, fromAccAddress, _, toAccAddress, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testFromID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + testFromID, testClassificationID, _, fromAccAddress, _, toAccAddress, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testFromID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + To: tt.fields.To, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + testFromID, testClassificationID, _, fromAccAddress, _, toAccAddress, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testFromID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + testFromID, testClassificationID, _, fromAccAddress, _, toAccAddress, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testFromID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + testFromID, testClassificationID, _, fromAccAddress, _, toAccAddress, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testFromID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, false}, + {"-ve with nil", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + testFromID, testClassificationID, _, fromAccAddress, _, toAccAddress, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties := createTestInput(t) + type args struct { + from sdkTypes.AccAddress + to sdkTypes.AccAddress + fromID ids.IdentityID + classificationID ids.ClassificationID + immutableMetaProperties lists.PropertyList + immutableProperties lists.PropertyList + mutableMetaProperties lists.PropertyList + mutableProperties lists.PropertyList + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, toAccAddress, testFromID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, newMessage(fromAccAddress, toAccAddress, testFromID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)}, + {"-ve with nil", args{}, message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.to, tt.args.fromID, tt.args.classificationID, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/identities/internal/transactions/issue/msg_server.go b/modules/identities/internal/transactions/issue/msg_server.go deleted file mode 100644 index 5546fd783..000000000 --- a/modules/identities/internal/transactions/issue/msg_server.go +++ /dev/null @@ -1,64 +0,0 @@ -package issue - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/conform" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Issue(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - immutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(message.ImmutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - immutableProperties := base.NewProperties(append(immutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...)...) - - identityID := key.NewIdentityID(&message.ClassificationID, immutableProperties) - - identities := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(identityID)) - if identities.Get(key.FromID(identityID)) != nil { - return nil, errors.EntityAlreadyExists - } - - authenticationProperty := base.NewMetaProperty(base.NewID(properties.Authentication), base.NewMetaFact(base.NewListData(base.NewAccAddressData(message.To.AsSDKTypesAccAddress())))) - - updatedMutableMetaProperties := append(message.MutableMetaProperties.GetList(), authenticationProperty) - - mutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(updatedMutableMetaProperties...))) - if Error != nil { - return nil, Error - } - - mutableProperties := base.NewProperties(append(mutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...) - - if auxiliaryResponse := msgServer.transactionKeeper.conformAuxiliary.GetKeeper().Help(ctx, conform.NewAuxiliaryRequest(&message.ClassificationID, immutableProperties, mutableProperties)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - identities.Add(mappable.NewIdentity(identityID, immutableProperties, mutableProperties)) - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/identities/internal/transactions/issue/request.go b/modules/identities/internal/transactions/issue/request.go index 2676d50e5..cf7a3030c 100644 --- a/modules/identities/internal/transactions/issue/request.go +++ b/modules/identities/internal/transactions/issue/request.go @@ -1,23 +1,25 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package issue import ( "encoding/json" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -33,35 +35,42 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary issue identities transaction -// @Descrption issue identities with mutable immutable properties +// Validate godoc +// @Summary Issue an identity +// @Description Issue identities with mutable immutable properties // @Accept text/plain // @Produce json // @Tags Identities -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body body transactionRequest true "A transaction to issue an identity." +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /identities/issue [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + if err != nil { + return err + } + inputValidator := base.NewInputValidator(constants.PropertyExpression) + if !inputValidator.IsValid(transactionRequest.ImmutableProperties, transactionRequest.ImmutableMetaProperties, transactionRequest.MutableProperties, transactionRequest.MutableMetaProperties) { + return errorConstants.IncorrectFormat + } + return nil } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.To), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ClassificationID), - cliCommand.ReadString(flags.ImmutableMetaProperties), - cliCommand.ReadString(flags.ImmutableProperties), - cliCommand.ReadString(flags.MutableMetaProperties), - cliCommand.ReadString(flags.MutableProperties), + cliCommand.ReadString(constants.To), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ClassificationID), + cliCommand.ReadString(constants.ImmutableMetaProperties), + cliCommand.ReadString(constants.ImmutableProperties), + cliCommand.ReadString(constants.MutableMetaProperties), + cliCommand.ReadString(constants.MutableProperties), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -70,54 +79,64 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err } - to, Error := sdkTypes.AccAddressFromBech32(transactionRequest.To) - if Error != nil { - return nil, Error + to, err := sdkTypes.AccAddressFromBech32(transactionRequest.To) + if err != nil { + return nil, err } - immutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.ImmutableMetaProperties) - if Error != nil { - return nil, Error + immutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableMetaProperties) + if err != nil { + return nil, err } - immutableProperties, Error := base.ReadProperties(transactionRequest.ImmutableProperties) - if Error != nil { - return nil, Error + immutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableProperties) + if err != nil { + return nil, err } + immutableProperties = immutableProperties.ScrubData() - mutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.MutableMetaProperties) - if Error != nil { - return nil, Error + mutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableMetaProperties) + if err != nil { + return nil, err } - mutableProperties, Error := base.ReadProperties(transactionRequest.MutableProperties) - if Error != nil { - return nil, Error + mutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableProperties) + if err != nil { + return nil, err } + mutableProperties = mutableProperties.ScrubData() + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + classificationID, err := baseIDs.ReadClassificationID(transactionRequest.ClassificationID) + if err != nil { + return nil, err + } return newMessage( from, to, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.ClassificationID), + fromID, + classificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} } - func newTransactionRequest(baseReq rest.BaseReq, to string, fromID string, classificationID string, immutableMetaProperties string, immutableProperties string, mutableMetaProperties string, mutableProperties string) helpers.TransactionRequest { return transactionRequest{ BaseReq: baseReq, diff --git a/modules/identities/internal/transactions/issue/request_test.go b/modules/identities/internal/transactions/issue/request_test.go index e455c28e7..0fb131843 100644 --- a/modules/identities/internal/transactions/issue/request_test.go +++ b/modules/identities/internal/transactions/issue/request_test.go @@ -1,37 +1,45 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package issue import ( "encoding/json" + "fmt" + "reflect" "testing" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" ) -func Test_Mint_Request(t *testing.T) { +func createTestInputForRequest(t *testing.T) (*codec.Codec, helpers.CLICommand, context.CLIContext, string, string, string, string, lists.PropertyList, lists.PropertyList, lists.PropertyList, lists.PropertyList, string, sdkTypes.AccAddress, string, sdkTypes.AccAddress, rest.BaseReq) { + var Codec = codec.New() - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.To, flags.ClassificationID, flags.ImmutableMetaProperties, flags.ImmutableProperties, flags.MutableMetaProperties, flags.MutableProperties}) + + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.To, constants.ClassificationID, constants.ImmutableMetaProperties, constants.ImmutableProperties, constants.MutableMetaProperties, constants.MutableProperties}) cliContext := context.NewCLIContext().WithCodec(Codec) immutableMetaPropertiesString := "defaultImmutableMeta1:S|defaultImmutableMeta1" @@ -39,74 +47,349 @@ func Test_Mint_Request(t *testing.T) { mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - immutableMetaProperties, Error := base.ReadMetaProperties(immutableMetaPropertiesString) - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties(immutablePropertiesString) - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties(mutableMetaPropertiesString) - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties(mutablePropertiesString) - require.Equal(t, nil, Error) + immutableMetaProperties, err := utilities.ReadMetaPropertyList(immutableMetaPropertiesString) + require.Equal(t, nil, err) + + var immutableProperties lists.PropertyList + immutableProperties, err = utilities.ReadMetaPropertyList(immutablePropertiesString) + require.Equal(t, nil, err) + + var mutableMetaProperties lists.PropertyList + mutableMetaProperties, err = utilities.ReadMetaPropertyList(mutableMetaPropertiesString) + require.Equal(t, nil, err) + + var mutableProperties lists.PropertyList + mutableProperties, err = utilities.ReadMetaPropertyList(mutablePropertiesString) + require.Equal(t, nil, err) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) + var fromAccAddress sdkTypes.AccAddress + fromAccAddress, err = sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) toAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - toAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) + var toAccAddress sdkTypes.AccAddress + toAccAddress, err = sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString) - require.Equal(t, transactionRequest{BaseReq: testBaseReq, To: toAddress, FromID: "fromID", ClassificationID: "classificationID", ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) + return Codec, cliCommand, cliContext, immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties, fromAddress, fromAccAddress, toAddress, toAccAddress, testBaseReq +} + +func Test_newTransactionRequest(t *testing.T) { + _, _, _, immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString, _, _, _, _, _, _, toAddress, _, testBaseReq := createTestInputForRequest(t) + type args struct { + baseReq rest.BaseReq + to string + fromID string + classificationID string + immutableMetaProperties string + immutableProperties string + mutableMetaProperties string + mutableProperties string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, To: "", FromID: "", ClassificationID: "", ImmutableMetaProperties: "", ImmutableProperties: "", MutableMetaProperties: "", MutableProperties: ""}, requestFromCLI) + {"+ve", args{testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, transactionRequest{testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.to, tt.args.fromID, tt.args.classificationID, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromCLI(t *testing.T) { + _, cliCommand, cliContext, immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString, _, _, _, _, _, _, toAddress, _, testBaseReq := createTestInputForRequest(t) + type fields struct { + BaseReq rest.BaseReq + To string + FromID string + ClassificationID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, cliContext}, transactionRequest{cliCommand.ReadBaseReq(cliContext), cliCommand.ReadString(constants.To), cliCommand.ReadString(constants.FromID), cliCommand.ReadString(constants.ClassificationID), cliCommand.ReadString(constants.ImmutableMetaProperties), cliCommand.ReadString(constants.ImmutableProperties), cliCommand.ReadString(constants.MutableMetaProperties), cliCommand.ReadString(constants.MutableProperties)}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, toAccAddress, base.NewID("fromID"), base.NewID("classificationID"), immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties), msg) - require.Nil(t, Error) +func Test_transactionRequest_FromJSON(t *testing.T) { + _, _, _, immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString, _, _, _, _, _, _, toAddress, _, testBaseReq := createTestInputForRequest(t) + jsonMessage, err := json.Marshal(newTransactionRequest(testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString)) + require.Equal(t, nil, err) + jsonMessage1, err := json.Marshal(newTransactionRequest(testBaseReq, toAddress, "", "", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString)) + require.Equal(t, nil, err) + type fields struct { + BaseReq rest.BaseReq + To string + FromID string + ClassificationID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ - msg, Error = newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) + {"+ve", fields{testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{jsonMessage}, transactionRequest{testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + {"+ve", fields{testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{jsonMessage1}, transactionRequest{testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: fromAddress, ChainID: "test"}, "randomString", "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + _, _, _, immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString, _, _, _, _, _, _, toAddress, _, testBaseReq := createTestInputForRequest(t) + type fields struct { + BaseReq rest.BaseReq + To string + FromID string + ClassificationID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ - msg, Error = newTransactionRequest(testBaseReq, toAddress, "fromID", "classificationID", "randomString", immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) + {"+ve", fields{testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, testBaseReq}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, "randomString", mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_MakeMsg(t *testing.T) { + _, _, _, immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties, _, fromAccAddress, toAddress, toAccAddress, testBaseReq := createTestInputForRequest(t) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) + type fields struct { + BaseReq rest.BaseReq + To string + FromID string + ClassificationID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want sdkTypes.Msg + wantErr bool + }{ + {"+ve", fields{testBaseReq, toAddress, "9UNIA3_tulK2vRE0nSmsHKNzhDxoCBHI4z8XXfLO1FM=", "9UNIA3_tulK2vRE0nSmsHKNzhDxoCBHI4z8XXfLO1FM=", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, newMessage(fromAccAddress, toAccAddress, testFromID, testClassificationID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties), false}, // TODO: issue==> getting MetaDataError that is not expected + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, "randomString", mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + _, _, _, immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString, _, _, _, _, _, _, toAddress, _, testBaseReq := createTestInputForRequest(t) + type fields struct { + BaseReq rest.BaseReq + To string + FromID string + ClassificationID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, "randomString").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_Validate(t *testing.T) { + _, _, _, immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString, _, _, _, _, _, _, toAddress, _, testBaseReq := createTestInputForRequest(t) + testBaseReq1 := rest.BaseReq{} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) + type fields struct { + BaseReq rest.BaseReq + To string + FromID string + ClassificationID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseReq, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + {"+ve", fields{testBaseReq1, toAddress, "fromID", "classificationID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + {"-ve", fields{ClassificationID: ""}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/identities/internal/transactions/issue/response.go b/modules/identities/internal/transactions/issue/response.go new file mode 100644 index 000000000..4ab7f08dd --- /dev/null +++ b/modules/identities/internal/transactions/issue/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package issue + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/identities/internal/transactions/issue/response_test.go b/modules/identities/internal/transactions/issue/response_test.go new file mode 100644 index 000000000..0f82ef0d4 --- /dev/null +++ b/modules/identities/internal/transactions/issue/response_test.go @@ -0,0 +1,88 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package issue + +import ( + "reflect" + "testing" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +func Test_newTransactionResponse(t *testing.T) { + type args struct { + error error + } + tests := []struct { + name string + args args + want helpers.TransactionResponse + }{ + + {"+ve", args{nil}, transactionResponse{Success: true, Error: nil}}, + {"-ve", args{constants.IncorrectMessage}, transactionResponse{Success: false, Error: constants.IncorrectMessage}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionResponse(tt.args.error); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionResponse() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionResponse_GetError(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + + {"-ve", fields{Success: false, Error: constants.IncorrectMessage}, true}, + {"+ve", fields{Success: true, Error: nil}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if err := transactionResponse.GetError(); (err != nil) != tt.wantErr { + t.Errorf("GetError() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_transactionResponse_IsSuccessful(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + want bool + }{ + + {"-ve", fields{Success: false, Error: constants.IncorrectMessage}, false}, + {"+ve", fields{Success: true, Error: nil}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if got := transactionResponse.IsSuccessful(); got != tt.want { + t.Errorf("IsSuccessful() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/identities/internal/transactions/issue/transaction.go b/modules/identities/internal/transactions/issue/transaction.go new file mode 100644 index 000000000..ebabfb207 --- /dev/null +++ b/modules/identities/internal/transactions/issue/transaction.go @@ -0,0 +1,27 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package issue + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "issue", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.To, + constants.FromID, + constants.ClassificationID, + constants.ImmutableMetaProperties, + constants.ImmutableProperties, + constants.MutableMetaProperties, + constants.MutableProperties, +) diff --git a/modules/identities/internal/transactions/mutate/keeper.go b/modules/identities/internal/transactions/mutate/keeper.go new file mode 100644 index 000000000..d5672ced1 --- /dev/null +++ b/modules/identities/internal/transactions/mutate/keeper.go @@ -0,0 +1,84 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mutate + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/member" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/maintain" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + authenticateAuxiliary helpers.Auxiliary + maintainAuxiliary helpers.Auxiliary + memberAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + identities := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.IdentityID)) + + Mappable := identities.Get(key.NewKey(message.IdentityID)) + if Mappable == nil { + return newTransactionResponse(constants.EntityNotFound) + } + identity := Mappable.(documents.Identity) + + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(append(message.MutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...)) + + if auxiliaryResponse := transactionKeeper.memberAuxiliary.GetKeeper().Help(context, member.NewAuxiliaryRequest(identity.GetClassificationID(), nil, mutables)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + if auxiliaryResponse := transactionKeeper.maintainAuxiliary.GetKeeper().Help(context, maintain.NewAuxiliaryRequest(identity.GetClassificationID(), message.FromID, mutables)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + identities.Mutate(mappable.NewMappable(base.NewIdentity(identity.GetClassificationID(), identity.GetImmutables(), baseQualified.NewMutables(identity.GetMutables().GetMutablePropertyList().Mutate(mutables.GetMutablePropertyList().GetList()...))))) + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper = mapper + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case member.Auxiliary.GetName(): + transactionKeeper.memberAuxiliary = value + case maintain.Auxiliary.GetName(): + transactionKeeper.maintainAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(constants.UninitializedUsage) + } + } + + return transactionKeeper +} + +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/identities/internal/transactions/mutate/message.go b/modules/identities/internal/transactions/mutate/message.go index fd31d15bc..3534f035f 100644 --- a/modules/identities/internal/transactions/mutate/message.go +++ b/modules/identities/internal/transactions/mutate/message.go @@ -1,70 +1,75 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mutate import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/identities/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + IdentityID ids.IdentityID `json:"identityID" valid:"required~required field identityID missing"` + MutableMetaProperties lists.PropertyList `json:"mutableMetaProperties" valid:"required~required field mutableMetaProperties missing"` + MutableProperties lists.PropertyList `json:"mutableProperties" valid:"required~required field mutableProperties missing"` +} + +var _ helpers.Message = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + if len(message.MutableMetaProperties.GetList()) == 0 { + message.MutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.MutableProperties.GetList()) == 0 { + message.MutableProperties = base.NewPropertyList(nil) + } + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, identityID types.ID, mutableMetaProperties types.MetaProperties, mutableProperties types.Properties) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - IdentityID: *base.NewID(identityID.String()), - MutableMetaProperties: *base.NewMetaProperties(mutableMetaProperties.GetList()...), - MutableProperties: *base.NewProperties(mutableProperties.GetList()...), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, identityID ids.IdentityID, mutableMetaProperties lists.PropertyList, mutableProperties lists.PropertyList) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + IdentityID: identityID, + MutableMetaProperties: mutableMetaProperties, + MutableProperties: mutableProperties, } } diff --git a/modules/identities/internal/transactions/mutate/message.pb.go b/modules/identities/internal/transactions/mutate/message.pb.go deleted file mode 100644 index 0002d7dbb..000000000 --- a/modules/identities/internal/transactions/mutate/message.pb.go +++ /dev/null @@ -1,727 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/transactions/mutate/message.proto - -package mutate - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - IdentityID base.ID `protobuf:"bytes,3,opt,name=identity_i_d,json=identityID,proto3" json:"identity_i_d" valid:"required~required field IdentityID missing"` - MutableMetaProperties base.MetaProperties `protobuf:"bytes,4,opt,name=mutable_meta_properties,json=mutableMetaProperties,proto3" json:"mutable_meta_properties" valid:"required~required field MutableMetaProperties missing"` - MutableProperties base.Properties `protobuf:"bytes,5,opt,name=mutable_properties,json=mutableProperties,proto3" json:"mutable_properties" valid:"required~required field MutableProperties missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_530cc32622399757, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_530cc32622399757, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "modules.identities.internal.transactions.mutate.Message") - proto.RegisterType((*TransactionResponse)(nil), "modules.identities.internal.transactions.mutate.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/transactions/mutate/message.proto", fileDescriptor_530cc32622399757) -} - -var fileDescriptor_530cc32622399757 = []byte{ - // 535 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xb1, 0x6e, 0xd3, 0x40, - 0x18, 0xc7, 0x7d, 0xb4, 0x0d, 0xe5, 0x60, 0xc1, 0x50, 0x11, 0x65, 0xb0, 0xa3, 0x48, 0x48, 0x15, - 0x82, 0xb3, 0x08, 0x52, 0x05, 0x91, 0x18, 0x12, 0xa5, 0x48, 0x11, 0xb2, 0x40, 0x85, 0x01, 0xb1, - 0x44, 0x8e, 0xef, 0x8b, 0x7b, 0x22, 0xe7, 0x33, 0x77, 0x17, 0x50, 0x07, 0x58, 0x58, 0x3a, 0x96, - 0x27, 0xa0, 0x8f, 0xc0, 0x63, 0x74, 0xec, 0x88, 0x18, 0x22, 0x94, 0x2c, 0xcc, 0x5d, 0x59, 0x90, - 0xcf, 0x0e, 0x71, 0x43, 0xa4, 0x24, 0x93, 0xcf, 0x77, 0xf7, 0xf7, 0xef, 0x77, 0xfa, 0xfc, 0x1d, - 0xf6, 0x13, 0x90, 0x8a, 0x29, 0x0d, 0x71, 0x08, 0x5d, 0x45, 0xdf, 0x79, 0x5c, 0xd0, 0xe1, 0x00, - 0x94, 0xc7, 0x28, 0xc4, 0x9a, 0x69, 0x96, 0x0e, 0x63, 0x0d, 0x32, 0x0e, 0x06, 0x9e, 0x96, 0x41, - 0xac, 0x82, 0x50, 0x33, 0x11, 0x2b, 0x8f, 0x0f, 0x75, 0xa0, 0xc1, 0xe3, 0xa0, 0x54, 0x10, 0x01, - 0x49, 0xa4, 0xd0, 0xc2, 0x9e, 0xc6, 0xc9, 0x2c, 0x4e, 0xa6, 0x71, 0x52, 0x8c, 0x93, 0x2c, 0x5e, - 0xb9, 0x1d, 0x89, 0x48, 0x98, 0xac, 0x97, 0x8e, 0xb2, 0xcf, 0x54, 0xee, 0xcd, 0x5b, 0xa9, 0xf0, - 0x10, 0x78, 0xe0, 0xe9, 0xa3, 0x04, 0x94, 0xd7, 0x0b, 0x14, 0x78, 0x8c, 0xe6, 0x7b, 0xeb, 0xcb, - 0xf7, 0x26, 0x52, 0x24, 0x20, 0x8d, 0x4c, 0x96, 0xd9, 0x5b, 0x9e, 0xe1, 0xa0, 0x83, 0x97, 0x73, - 0xb9, 0xda, 0x9f, 0x2d, 0x7c, 0xd5, 0xcf, 0x0e, 0x6c, 0x7f, 0x45, 0x78, 0xb3, 0x2f, 0x05, 0x2f, - 0xa3, 0x2a, 0xda, 0xbd, 0xd6, 0xfa, 0x74, 0x36, 0x72, 0xad, 0x9f, 0x23, 0x77, 0x3f, 0x62, 0xfa, - 0x70, 0xd8, 0x23, 0xa1, 0xe0, 0x5e, 0x81, 0xf2, 0x22, 0x86, 0xe2, 0xeb, 0xab, 0xf6, 0xf3, 0xff, - 0x99, 0xa4, 0x19, 0x86, 0x4d, 0x4a, 0x25, 0x28, 0x75, 0x31, 0x72, 0xef, 0x7f, 0x08, 0x06, 0x8c, - 0x36, 0x6a, 0x12, 0xde, 0x0f, 0x99, 0x04, 0xfa, 0x79, 0x3a, 0xa8, 0xf6, 0x19, 0x0c, 0x68, 0xf5, - 0x99, 0x14, 0xbc, 0xca, 0x99, 0x52, 0x2c, 0x8e, 0x6a, 0x07, 0x46, 0xc5, 0xfe, 0x88, 0xb7, 0xd3, - 0x67, 0x97, 0x75, 0x69, 0xf9, 0x4a, 0x15, 0xed, 0x5e, 0xaf, 0xdf, 0x25, 0x73, 0x47, 0x25, 0x19, - 0x96, 0x18, 0x2c, 0x31, 0xd8, 0x4e, 0xbb, 0xb5, 0x97, 0xda, 0x5f, 0x8c, 0x5c, 0xb2, 0x02, 0xb4, - 0xd3, 0x9e, 0x61, 0x4b, 0x7d, 0x33, 0x61, 0x7f, 0x41, 0xf8, 0x46, 0x5e, 0xf2, 0x23, 0x43, 0xdf, - 0x58, 0x87, 0xde, 0xc8, 0xe9, 0xf5, 0x25, 0xf4, 0x4e, 0x4e, 0x28, 0x1a, 0x60, 0xf6, 0x6f, 0xd2, - 0xfe, 0x8e, 0xf0, 0x9d, 0xf4, 0xbf, 0xea, 0x0d, 0xa0, 0x9b, 0xd6, 0xaf, 0x3b, 0x2b, 0x7c, 0x79, - 0xd3, 0x08, 0x3d, 0x5c, 0x41, 0xc8, 0xbf, 0x54, 0xf9, 0xd6, 0x7e, 0x2e, 0xf7, 0x74, 0x89, 0x9c, - 0x9f, 0x81, 0x2f, 0xa7, 0x67, 0x9e, 0x3b, 0x7c, 0xd1, 0xba, 0xfd, 0x0d, 0x61, 0x7b, 0xaa, 0x5c, - 0xb0, 0xdd, 0x32, 0xb6, 0x0f, 0x56, 0xb0, 0x2d, 0x98, 0x36, 0x73, 0xd3, 0x27, 0xab, 0x99, 0x2e, - 0xb2, 0xbc, 0xc9, 0xe7, 0xd7, 0x1a, 0xdb, 0xc7, 0xa7, 0xae, 0xf5, 0xfb, 0xd4, 0xb5, 0x6a, 0x3b, - 0xf8, 0xd6, 0xeb, 0x59, 0x0b, 0x1f, 0x80, 0x4a, 0x44, 0xac, 0xa0, 0x7e, 0x82, 0xf0, 0x86, 0xaf, - 0x22, 0xfb, 0x18, 0xe1, 0x92, 0x6f, 0xba, 0xda, 0x7e, 0x4c, 0xd6, 0xbc, 0x07, 0x48, 0xde, 0x55, - 0x95, 0xf6, 0xda, 0xc9, 0x05, 0x4a, 0x2d, 0x79, 0x36, 0x76, 0xd0, 0xf9, 0xd8, 0x41, 0xbf, 0xc6, - 0x0e, 0x3a, 0x99, 0x38, 0xd6, 0xf9, 0xc4, 0xb1, 0x7e, 0x4c, 0x1c, 0xeb, 0xed, 0x9b, 0x95, 0xdb, - 0x73, 0xcd, 0x8b, 0xb0, 0x57, 0x32, 0x57, 0xc4, 0xa3, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x99, - 0x65, 0x29, 0x4f, 0x52, 0x05, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Mutate(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Mutate(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/modules.identities.internal.transactions.mutate.Msg/Mutate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Mutate(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Mutate(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Mutate not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Mutate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Mutate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/modules.identities.internal.transactions.mutate.Msg/Mutate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Mutate(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "modules.identities.internal.transactions.mutate.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Mutate", - Handler: _Msg_Mutate_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/identities/internal/transactions/mutate/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.MutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.IdentityID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.IdentityID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IdentityID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IdentityID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/transactions/mutate/message_test.go b/modules/identities/internal/transactions/mutate/message_test.go index 480178213..9c87f866d 100644 --- a/modules/identities/internal/transactions/mutate/message_test.go +++ b/modules/identities/internal/transactions/mutate/message_test.go @@ -1,44 +1,303 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mutate import ( + "reflect" "testing" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/identities/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Mutate_Message(t *testing.T) { - testFromID := base.NewID("fromID") - testIdentityID := base.NewID("identityID") - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) +func createTestInputForMessage(t *testing.T) (types.AccAddress, ids.IdentityID, ids.IdentityID, lists.PropertyList, lists.PropertyList) { + testFrom, err := types.AccAddressFromBech32("cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c") require.Nil(t, err) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) + testIdentityID := baseIDs.NewIdentityID(testClassificationID, immutables) + metaProperty := baseProperties.NewMetaProperty(baseIDs.NewStringID("id"), baseData.NewStringData("Data")) + mesaProperty := baseProperties.NewMesaProperty(baseIDs.NewStringID("id1"), baseData.NewStringData("Data1")) + testMutableMetaProperties := baseLists.NewPropertyList([]properties.Property{metaProperty}...) + testMutableProperties := baseLists.NewPropertyList([]properties.Property{mesaProperty}...) + + return testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties +} + +func Test_messageFromInterface(t *testing.T) { + testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties := createTestInputForMessage(t) + type args struct { + msg types.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve with nil", args{}, message{}}, + {"+ve", args{message{testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties}}, message{testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties := createTestInputForMessage(t) + type fields struct { + From types.AccAddress + FromID ids.IdentityID + IdentityID ids.IdentityID + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties}, types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties}))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} - mutableMetaProperties, err := base.ReadMetaProperties("defaultMutableMeta1:S|defaultMutableMeta1") - require.Equal(t, nil, err) - mutableProperties, err := base.ReadProperties("defaultMutable1:S|defaultMutable1") - require.Equal(t, nil, err) - - testMessage := newMessage(fromAccAddress, testFromID, testIdentityID, mutableMetaProperties, mutableProperties) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, IdentityID: testIdentityID, MutableMetaProperties: mutableMetaProperties, MutableProperties: mutableProperties}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +func Test_message_GetSigners(t *testing.T) { + testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties := createTestInputForMessage(t) + type fields struct { + From types.AccAddress + FromID ids.IdentityID + IdentityID ids.IdentityID + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []types.AccAddress + }{ + {"+ve with nil", fields{}, []types.AccAddress{nil}}, + {"+ve", fields{testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties}, []types.AccAddress{testFrom}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties := createTestInputForMessage(t) + type fields struct { + From types.AccAddress + FromID ids.IdentityID + IdentityID ids.IdentityID + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve with nil", fields{}, args{codec.New()}}, + {"+ve", fields{testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties := createTestInputForMessage(t) + type fields struct { + From types.AccAddress + FromID ids.IdentityID + IdentityID ids.IdentityID + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve with nil", fields{}, module.Name}, + {"+ve", fields{testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties := createTestInputForMessage(t) + type fields struct { + From types.AccAddress + FromID ids.IdentityID + IdentityID ids.IdentityID + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve with nil", fields{}, Transaction.GetName()}, + {"+ve", fields{testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties := createTestInputForMessage(t) + type fields struct { + From types.AccAddress + FromID ids.IdentityID + IdentityID ids.IdentityID + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve with nil", fields{}, true}, + {"+ve", fields{testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties := createTestInputForMessage(t) + type args struct { + from types.AccAddress + fromID ids.IdentityID + identityID ids.IdentityID + mutableMetaProperties lists.PropertyList + mutableProperties lists.PropertyList + } + tests := []struct { + name string + args args + want types.Msg + }{ + {"+ve with nil", args{}, message{}}, + {"+ve", args{testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties}, message{testFrom, testFromID, testIdentityID, testMutableMetaProperties, testMutableProperties}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.identityID, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/identities/internal/transactions/mutate/msg_server.go b/modules/identities/internal/transactions/mutate/msg_server.go deleted file mode 100644 index 7f2b726ba..000000000 --- a/modules/identities/internal/transactions/mutate/msg_server.go +++ /dev/null @@ -1,58 +0,0 @@ -package mutate - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/conform" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/maintain" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Mutate(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - identities := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(&message.IdentityID)) - - identity := identities.Get(key.FromID(&message.IdentityID)) - if identity == nil { - return nil, errors.EntityNotFound - } - - mutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(message.MutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - mutableProperties := base.NewProperties(append(mutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...) - - if auxiliaryResponse := msgServer.transactionKeeper.conformAuxiliary.GetKeeper().Help(ctx, conform.NewAuxiliaryRequest(identity.(mappables.InterIdentity).GetClassificationID(), nil, mutableProperties)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - if auxiliaryResponse := msgServer.transactionKeeper.maintainAuxiliary.GetKeeper().Help(ctx, maintain.NewAuxiliaryRequest(identity.(mappables.InterIdentity).GetClassificationID(), &message.FromID, mutableProperties)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - identities.Mutate(mappable.NewIdentity(identity.(mappables.InterIdentity).GetID(), identity.(mappables.InterIdentity).GetImmutableProperties(), identity.(mappables.InterIdentity).GetImmutableProperties().Mutate(mutableProperties.GetList()...))) - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/identities/internal/transactions/mutate/request.go b/modules/identities/internal/transactions/mutate/request.go index d3a6bebc6..be40c909f 100644 --- a/modules/identities/internal/transactions/mutate/request.go +++ b/modules/identities/internal/transactions/mutate/request.go @@ -1,23 +1,25 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mutate import ( "encoding/json" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -30,32 +32,39 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary mutate identities transaction -// @Descrption mutate identity properties +// Validate godoc +// @Summary Mutate an identity +// @Description Mutate identity properties // @Accept text/plain // @Produce json // @Tags Identities -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body body transactionRequest true "Request body to mutate Identity" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /identities/mutate [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + if err != nil { + return err + } + inputValidator := base.NewInputValidator(constants.PropertyExpression) + if !inputValidator.IsValid(transactionRequest.MutableProperties, transactionRequest.MutableMetaProperties) { + return errorConstants.IncorrectFormat + } + return nil } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.IdentityID), - cliCommand.ReadString(flags.MutableMetaProperties), - cliCommand.ReadString(flags.MutableProperties), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.IdentityID), + cliCommand.ReadString(constants.MutableMetaProperties), + cliCommand.ReadString(constants.MutableProperties), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -64,36 +73,46 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err } - mutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.MutableMetaProperties) - if Error != nil { - return nil, Error + mutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableMetaProperties) + if err != nil { + return nil, err } - mutableProperties, Error := base.ReadProperties(transactionRequest.MutableProperties) - if Error != nil { - return nil, Error + mutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableProperties) + if err != nil { + return nil, err + } + mutableProperties = mutableProperties.ScrubData() + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + identityID, err := baseIDs.ReadIdentityID(transactionRequest.IdentityID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.IdentityID), + fromID, + identityID, mutableMetaProperties, mutableProperties, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} } - func newTransactionRequest(baseReq rest.BaseReq, fromID string, identityID string, mutableMetaProperties string, mutableProperties string) helpers.TransactionRequest { return transactionRequest{ BaseReq: baseReq, diff --git a/modules/identities/internal/transactions/mutate/request_test.go b/modules/identities/internal/transactions/mutate/request_test.go index 1af3f3cb0..d1992091f 100644 --- a/modules/identities/internal/transactions/mutate/request_test.go +++ b/modules/identities/internal/transactions/mutate/request_test.go @@ -1,90 +1,330 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mutate import ( "encoding/json" + "reflect" "testing" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" -) -func Test_Define_Request(t *testing.T) { + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func createTestInput(t *testing.T) (*codec.Codec, helpers.CLICommand, context.CLIContext, string, string, lists.PropertyList, lists.PropertyList, string, sdkTypes.AccAddress, rest.BaseReq) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.IdentityID, flags.MutableMetaProperties, flags.MutableProperties}) + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.IdentityID, constants.MutableMetaProperties, constants.MutableProperties}) cliContext := context.NewCLIContext().WithCodec(Codec) mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - mutableMetaProperties, Error := base.ReadMetaProperties(mutableMetaPropertiesString) - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties(mutablePropertiesString) - require.Equal(t, nil, Error) + mutableMetaProperties, err := utilities.ReadMetaPropertyList(mutableMetaPropertiesString) + require.Equal(t, nil, err) + mutableProperties, err := utilities.ReadMetaPropertyList(mutablePropertiesString) + require.Equal(t, nil, err) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "identityID", mutableMetaPropertiesString, mutablePropertiesString) - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", IdentityID: "identityID", MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) + return Codec, cliCommand, cliContext, mutableMetaPropertiesString, mutablePropertiesString, mutableMetaProperties, mutableProperties, fromAddress, fromAccAddress, testBaseReq +} - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", MutableMetaProperties: "", MutableProperties: ""}, requestFromCLI) +func Test_newTransactionRequest(t *testing.T) { + _, _, _, mutableMetaPropertiesString, mutablePropertiesString, _, _, _, _, testBaseReq := createTestInput(t) + type args struct { + baseReq rest.BaseReq + fromID string + identityID string + mutableMetaProperties string + mutableProperties string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseReq, "fromID", "identityID", mutableMetaPropertiesString, mutablePropertiesString}, transactionRequest{testBaseReq, "fromID", "identityID", mutableMetaPropertiesString, mutablePropertiesString}}, + {"-ve with nil", args{}, transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.identityID, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +func Test_transactionRequest_FromCLI(t *testing.T) { + _, cliCommand, cliContext, mutableMetaPropertiesString, mutablePropertiesString, _, _, _, _, testBaseReq := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + FromID string + IdentityID string + MutableMetaProperties string + MutableProperties string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, "fromID", "identityID", mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand: cliCommand, cliContext: cliContext}, transactionRequest{cliCommand.ReadBaseReq(cliContext), cliCommand.ReadString(constants.FromID), cliCommand.ReadString(constants.IdentityID), cliCommand.ReadString(constants.MutableMetaProperties), cliCommand.ReadString(constants.MutableProperties)}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromJSON(t *testing.T) { + _, _, _, mutableMetaPropertiesString, mutablePropertiesString, _, _, _, _, testBaseReq := createTestInput(t) + jsonMessage, _ := json.Marshal(transactionRequest{testBaseReq, "fromID", "identityID", mutableMetaPropertiesString, mutablePropertiesString}) - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("identityID"), mutableMetaProperties, mutableProperties), msg) - require.Nil(t, Error) + type fields struct { + BaseReq rest.BaseReq + FromID string + IdentityID string + MutableMetaProperties string + MutableProperties string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, "fromID", "identityID", mutableMetaPropertiesString, mutablePropertiesString}, args{jsonMessage}, transactionRequest{testBaseReq, "fromID", "identityID", mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", "identityID", mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + _, _, cliContext, mutableMetaPropertiesString, mutablePropertiesString, _, _, _, _, testBaseReq := createTestInput(t) - msg, Error = newTransactionRequest(testBaseReq, "fromID", "identityID", "randomString", mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) + type fields struct { + BaseReq rest.BaseReq + FromID string + IdentityID string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{}, rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}}, + {"+ve", fields{testBaseReq, "fromID", "identityID", mutableMetaPropertiesString, mutablePropertiesString}, testBaseReq}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionRequest_MakeMsg(t *testing.T) { + _, _, _, mutableMetaPropertiesString, mutablePropertiesString, mutableMetaProperties, mutableProperties, _, fromAccAddress, testBaseReq := createTestInput(t) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) + type fields struct { + BaseReq rest.BaseReq + FromID string + IdentityID string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want sdkTypes.Msg + wantErr bool + }{ + {"+ve", fields{testBaseReq, testFromID.String(), testFromID.String(), mutableMetaPropertiesString, mutablePropertiesString}, newMessage(fromAccAddress, testFromID, testFromID, mutableMetaProperties, mutableProperties.ScrubData()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionRequest_RegisterCodec(t *testing.T) { + _, _, _, mutableMetaPropertiesString, mutablePropertiesString, _, _, _, _, testBaseReq := createTestInput(t) + + type fields struct { + BaseReq rest.BaseReq + FromID string + IdentityID string + MutableMetaProperties string + MutableProperties string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseReq, "fromID", "identityID", mutableMetaPropertiesString, mutablePropertiesString}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, "fromID", "identityID", mutableMetaPropertiesString, "randomString").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_Validate(t *testing.T) { + _, _, _, mutableMetaPropertiesString, mutablePropertiesString, _, _, _, _, testBaseReq := createTestInput(t) - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) + type fields struct { + BaseReq rest.BaseReq + FromID string + IdentityID string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseReq, "fromID", "identityID", mutableMetaPropertiesString, mutablePropertiesString}, false}, + {"+ve with nil", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/identities/internal/transactions/mutate/response.go b/modules/identities/internal/transactions/mutate/response.go new file mode 100644 index 000000000..d21b7c28b --- /dev/null +++ b/modules/identities/internal/transactions/mutate/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mutate + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/identities/internal/transactions/mutate/transaction.go b/modules/identities/internal/transactions/mutate/transaction.go new file mode 100644 index 000000000..b1826fa28 --- /dev/null +++ b/modules/identities/internal/transactions/mutate/transaction.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mutate + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "mutate", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.IdentityID, + constants.FromID, + constants.MutableMetaProperties, + constants.MutableProperties, +) diff --git a/modules/identities/internal/transactions/nub/keeper.go b/modules/identities/internal/transactions/nub/keeper.go new file mode 100644 index 000000000..a344ca48d --- /dev/null +++ b/modules/identities/internal/transactions/nub/keeper.go @@ -0,0 +1,70 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package nub + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/define" + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/ids/constansts" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/properties/constants" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + defineAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(constants.NubIDProperty.GetKey(), baseData.NewIDData(message.NubID)))) + + // TODO ***** add nub classificationID to genesis + + identityID := baseIDs.NewIdentityID(constansts.NubClassificationID, immutables) + + identities := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(identityID)) + if identities.Get(key.NewKey(identityID)) != nil { + return newTransactionResponse(errorConstants.EntityAlreadyExists) + } + + identities.Add(mappable.NewMappable(base.NewIdentity(constansts.NubClassificationID, immutables, baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(constants.AuthenticationProperty.GetKey(), baseData.NewListData(baseLists.NewDataList(baseData.NewAccAddressData(message.From))))))))) + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper = mapper + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case define.Auxiliary.GetName(): + transactionKeeper.defineAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} + +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/identities/internal/transactions/nub/keeper_test.go b/modules/identities/internal/transactions/nub/keeper_test.go new file mode 100644 index 000000000..96fef6c95 --- /dev/null +++ b/modules/identities/internal/transactions/nub/keeper_test.go @@ -0,0 +1,97 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package nub + +import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/define" + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/modules/identities/internal/parameters" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/scrub" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +type TestKeepers struct { + IdentitiesKeeper helpers.TransactionKeeper +} + +func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + scrubAuxiliary := scrub.AuxiliaryMock.Initialize(mapper, Parameters) + defineAuxiliary := define.AuxiliaryMock.Initialize(mapper, Parameters) + keepers := TestKeepers{ + IdentitiesKeeper: keeperPrototype().Initialize(mapper, Parameters, + []interface{}{scrubAuxiliary, + defineAuxiliary}).(helpers.TransactionKeeper), + } + + return context, keepers +} + +func Test_transactionKeeper_Transact(t *testing.T) { + ctx, keepers := CreateTestInput(t) + + t.Run("PositiveCase", func(t *testing.T) { + want := newTransactionResponse(nil) + if got := keepers.IdentitiesKeeper.Transact(ctx, newMessage(sdkTypes.AccAddress("addr"), baseIDs.NewStringID("nubID"))); !reflect.DeepEqual(got, want) { + t.Errorf("Transact() = %v, want %v", got, want) + } + }) + + t.Run("NegativeCase-Duplicate", func(t *testing.T) { + t.Parallel() + want := newTransactionResponse(constants.EntityAlreadyExists) + if got := keepers.IdentitiesKeeper.Transact(ctx, newMessage(sdkTypes.AccAddress("addr"), baseIDs.NewStringID("nubID"))); !reflect.DeepEqual(got, want) { + t.Errorf("Transact() = %v, want %v", got, want) + } + }) + +} diff --git a/modules/identities/internal/transactions/nub/message.go b/modules/identities/internal/transactions/nub/message.go index 5c56af86a..6c1138fdc 100644 --- a/modules/identities/internal/transactions/nub/message.go +++ b/modules/identities/internal/transactions/nub/message.go @@ -1,67 +1,61 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package nub import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/identities/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + NubID ids.ID `json:"nubID" valid:"required~required field nubID missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, nubID types.ID) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - NubID: *base.NewID(nubID.String()), +func newMessage(from sdkTypes.AccAddress, nubID ids.ID) sdkTypes.Msg { + return message{ + From: from, + NubID: nubID, } } diff --git a/modules/identities/internal/transactions/nub/message.pb.go b/modules/identities/internal/transactions/nub/message.pb.go deleted file mode 100644 index 786406a01..000000000 --- a/modules/identities/internal/transactions/nub/message.pb.go +++ /dev/null @@ -1,581 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/transactions/nub/message.proto - -package nub - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - NubID base.ID `protobuf:"bytes,2,opt,name=nub_i_d,json=nubID,proto3" json:"nub_i_d" valid:"required~required field NubID missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_4a91bc736e1ead03, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4a91bc736e1ead03, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.identities.internal.transactions.nub.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.identities.internal.transactions.nub.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/transactions/nub/message.proto", fileDescriptor_4a91bc736e1ead03) -} - -var fileDescriptor_4a91bc736e1ead03 = []byte{ - // 416 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0x41, 0x6b, 0xd4, 0x40, - 0x14, 0xc7, 0x33, 0xad, 0x5a, 0x8d, 0xb7, 0xa8, 0x50, 0xf6, 0x90, 0x84, 0x80, 0x50, 0x44, 0x67, - 0xa0, 0xe2, 0xa5, 0x78, 0xe9, 0xb2, 0x15, 0xaa, 0xb4, 0x62, 0xd5, 0x8b, 0x97, 0x25, 0x93, 0x79, - 0x4d, 0x07, 0x93, 0x99, 0x38, 0x6f, 0x46, 0xf0, 0xa0, 0x67, 0x8f, 0xfa, 0x01, 0xc4, 0xde, 0xfc, - 0x2a, 0x3d, 0xf6, 0x28, 0x1e, 0x82, 0xec, 0x5e, 0x3c, 0xef, 0x27, 0x90, 0x24, 0xbb, 0xec, 0xb2, - 0x0a, 0x5a, 0xf6, 0xf6, 0x06, 0x86, 0xdf, 0xef, 0xcf, 0xfb, 0x3f, 0xff, 0x71, 0x05, 0x06, 0x25, - 0x5a, 0x50, 0x19, 0x0c, 0x51, 0xbc, 0x66, 0xa5, 0x16, 0xae, 0x00, 0x64, 0x52, 0x80, 0xb2, 0xd2, - 0xca, 0x66, 0x54, 0x16, 0x8c, 0x4a, 0x0b, 0x66, 0x4d, 0xaa, 0x30, 0xcd, 0xac, 0xd4, 0x0a, 0x99, - 0x72, 0x9c, 0x95, 0x80, 0x98, 0xe6, 0x40, 0x2b, 0xa3, 0xad, 0x0e, 0x1e, 0x2e, 0xb1, 0xe8, 0x94, - 0x45, 0xe7, 0x2c, 0x3a, 0x63, 0xd1, 0x45, 0x16, 0x55, 0x8e, 0xf7, 0x6e, 0xe6, 0x3a, 0xd7, 0x2d, - 0x88, 0x35, 0x53, 0xc7, 0xec, 0xdd, 0x59, 0xce, 0x87, 0xd9, 0x09, 0x94, 0x29, 0xb3, 0xef, 0x2a, - 0x40, 0xc6, 0x53, 0x04, 0x26, 0x45, 0xf7, 0x37, 0xf9, 0xb2, 0xe6, 0x6f, 0x1c, 0x74, 0x89, 0x82, - 0xcf, 0xc4, 0xbf, 0x74, 0x6c, 0x74, 0xb9, 0x49, 0x62, 0xb2, 0x75, 0xad, 0xff, 0xfe, 0xac, 0x8e, - 0xbc, 0x1f, 0x75, 0xb4, 0x97, 0x4b, 0x7b, 0xe2, 0x38, 0xcd, 0x74, 0xc9, 0x16, 0xc8, 0x4f, 0x15, - 0x2c, 0x3e, 0x9f, 0x0f, 0x9e, 0xfc, 0xe9, 0xa1, 0xbb, 0x59, 0xb6, 0x2b, 0x84, 0x01, 0xc4, 0x49, - 0x1d, 0xdd, 0x7d, 0x9b, 0x16, 0x52, 0xec, 0x24, 0x06, 0xde, 0x38, 0x69, 0x40, 0x7c, 0x98, 0x0d, - 0xf1, 0xb1, 0x84, 0x42, 0xc4, 0x8f, 0x8c, 0x2e, 0xe3, 0x52, 0x22, 0x4a, 0x95, 0x27, 0x47, 0x6d, - 0x94, 0xc0, 0xfa, 0x1b, 0xca, 0xf1, 0xa1, 0x1c, 0x8a, 0xcd, 0xb5, 0x98, 0x6c, 0x5d, 0xdf, 0xbe, - 0x4d, 0x97, 0x37, 0xd6, 0x59, 0x69, 0x6b, 0xa5, 0xad, 0x75, 0x7f, 0xd0, 0x7f, 0xd0, 0x84, 0x9f, - 0xd4, 0xd1, 0xbd, 0x7f, 0x38, 0x0f, 0x1d, 0xdf, 0x1f, 0xcc, 0xa5, 0x97, 0x55, 0xf3, 0xde, 0xb9, - 0xfa, 0xf1, 0x34, 0xf2, 0x7e, 0x9d, 0x46, 0x5e, 0x72, 0xcb, 0xbf, 0xf1, 0x62, 0xbe, 0xf5, 0x23, - 0xc0, 0x4a, 0x2b, 0x84, 0xed, 0x6f, 0xc4, 0x5f, 0x3f, 0xc0, 0x3c, 0xf8, 0x4a, 0xfc, 0xf5, 0x43, - 0xc7, 0x83, 0x3d, 0xba, 0x4a, 0x8f, 0x74, 0xda, 0x40, 0xef, 0xd9, 0x6a, 0x98, 0xbf, 0x24, 0xed, - 0xeb, 0xb3, 0x51, 0x48, 0xce, 0x47, 0x21, 0xf9, 0x39, 0x0a, 0xc9, 0xa7, 0x71, 0xe8, 0x9d, 0x8f, - 0x43, 0xef, 0xfb, 0x38, 0xf4, 0x5e, 0xbd, 0xfc, 0xef, 0x5e, 0x2f, 0x72, 0xdf, 0xfc, 0x4a, 0x7b, - 0x58, 0xf7, 0x7f, 0x07, 0x00, 0x00, 0xff, 0xff, 0x48, 0xd5, 0x26, 0x17, 0x26, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Nub(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Nub(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.identities.internal.transactions.nub.Msg/Nub", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Nub(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Nub(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Nub not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Nub_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Nub(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.identities.internal.transactions.nub.Msg/Nub", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Nub(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.identities.internal.transactions.nub.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Nub", - Handler: _Msg_Nub_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/identities/internal/transactions/nub/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.NubID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.NubID.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NubID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.NubID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/transactions/nub/message_test.go b/modules/identities/internal/transactions/nub/message_test.go index 303be93d5..c34220f73 100644 --- a/modules/identities/internal/transactions/nub/message_test.go +++ b/modules/identities/internal/transactions/nub/message_test.go @@ -1,38 +1,247 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package nub import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/identities/internal/module" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Nub_Message(t *testing.T) { - testNubID := base.NewID("nubID") +func createTestInput(t *testing.T) (ids.ID, string, sdkTypes.AccAddress) { + testNubID := baseIDs.NewStringID("nubID") fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) require.Nil(t, err) - testMessage := newMessage(fromAccAddress, testNubID) - require.Equal(t, Message{From: fromAccAddress, NubID: testNubID}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) + return testNubID, fromAddress, fromAccAddress +} + +func Test_messageFromInterface(t *testing.T) { + testNubID, _, fromAccAddress := createTestInput(t) + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{message{From: fromAccAddress, NubID: testNubID}}, message{From: fromAccAddress, NubID: testNubID}}, + {"+ve", args{nil}, message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + testNubID, _, fromAccAddress := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + NubID ids.ID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, testNubID}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, testNubID}))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + NubID: tt.fields.NubID, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + testNubID, _, fromAccAddress := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + NubID ids.ID + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, testNubID}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + NubID: tt.fields.NubID, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + testNubID, _, fromAccAddress := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + NubID ids.ID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, testNubID}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + NubID: tt.fields.NubID, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + testNubID, _, fromAccAddress := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + NubID ids.ID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testNubID}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + NubID: tt.fields.NubID, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + testNubID, _, fromAccAddress := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + NubID ids.ID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testNubID}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + NubID: tt.fields.NubID, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + testNubID, _, fromAccAddress := createTestInput(t) + type fields struct { + From sdkTypes.AccAddress + NubID ids.ID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, testNubID}, false}, + {"-ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + NubID: tt.fields.NubID, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + testNubID, _, fromAccAddress := createTestInput(t) + type args struct { + from sdkTypes.AccAddress + nubID ids.ID + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, testNubID}, message{fromAccAddress, testNubID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.nubID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/identities/internal/transactions/nub/msg_server.go b/modules/identities/internal/transactions/nub/msg_server.go deleted file mode 100644 index 9ffe183dd..000000000 --- a/modules/identities/internal/transactions/nub/msg_server.go +++ /dev/null @@ -1,54 +0,0 @@ -package nub - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/define" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Nub(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - nubIDProperty := base.NewMetaProperty(base.NewID(properties.NubID), base.NewMetaFact(base.NewIDData(&message.NubID))) - - immutableProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(nubIDProperty))) - if Error != nil { - return nil, Error - } - - authenticationProperty := base.NewMetaProperty(base.NewID(properties.Authentication), base.NewMetaFact(base.NewListData(base.NewAccAddressData(message.From.AsSDKTypesAccAddress())))) - mutableProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(authenticationProperty))) - if Error != nil { - return nil, Error - } - - classificationID, Error := define.GetClassificationIDFromResponse(msgServer.transactionKeeper.defineAuxiliary.GetKeeper().Help(ctx, define.NewAuxiliaryRequest(base.NewProperties(base.NewProperty(base.NewID(properties.NubID), base.NewFact(base.NewIDData(base.NewID(""))))), base.NewProperties(base.NewProperty(base.NewID(properties.Authentication), base.NewFact(base.NewAccAddressData(nil).ZeroValue())))))) - if classificationID == nil && Error != nil { - return nil, Error - } - - identityID := key.NewIdentityID(classificationID, immutableProperties) - identities := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(identityID)) - if identities.Get(key.FromID(identityID)) != nil { - return nil, errors.EntityAlreadyExists - } - - identities.Add(mappable.NewIdentity(identityID, immutableProperties, mutableProperties)) - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/identities/internal/transactions/nub/request.go b/modules/identities/internal/transactions/nub/request.go index 7605256b8..ffa08ef88 100644 --- a/modules/identities/internal/transactions/nub/request.go +++ b/modules/identities/internal/transactions/nub/request.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package nub @@ -9,15 +7,18 @@ import ( "encoding/json" "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers/base" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -27,29 +28,36 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary nub identities transaction -// @Descrption nub transaction +// Validate godoc +// @Summary Nub an identity +// @Description A transaction to nub an identity. // @Accept text/plain // @Produce json // @Tags Identities -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body transactionRequest true "A transaction to nub a base identity." +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /identities/nub [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + if err != nil { + return err + } + inputValidator := base.NewInputValidator(constants.NubIDExpression) + if !inputValidator.IsValid(transactionRequest.NubID) { + return errorConstants.IncorrectFormat + } + return nil } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.NubID), + cliCommand.ReadString(constants.NubID), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -58,23 +66,22 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.NubID), + baseIDs.NewStringID(transactionRequest.NubID), ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} } - func newTransactionRequest(baseReq rest.BaseReq, nubID string) helpers.TransactionRequest { return transactionRequest{ BaseReq: baseReq, diff --git a/modules/identities/internal/transactions/nub/request_test.go b/modules/identities/internal/transactions/nub/request_test.go index 9e4264fa4..044b1f295 100644 --- a/modules/identities/internal/transactions/nub/request_test.go +++ b/modules/identities/internal/transactions/nub/request_test.go @@ -1,73 +1,272 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package nub import ( "encoding/json" - "github.com/cosmos/cosmos-sdk/client" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" - "testing" -) -func Test_Define_Request(t *testing.T) { + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/utilities/transaction" +) - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func CreateTestInputForRequest(t *testing.T) (*codec.Codec, helpers.CLICommand, context.CLIContext, string, sdkTypes.AccAddress, rest.BaseReq) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.NubID}) + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.NubID}) cliContext := context.NewCLIContext().WithCodec(Codec) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "nubID") - require.Equal(t, transactionRequest{BaseReq: testBaseReq, NubID: "nubID"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) + return Codec, cliCommand, cliContext, fromAddress, fromAccAddress, testBaseReq +} + +func Test_newTransactionRequest(t *testing.T) { + _, _, _, _, _, testBaseReq := CreateTestInputForRequest(t) + type args struct { + baseReq rest.BaseReq + nubID string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseReq, "nubID"}, transactionRequest{testBaseReq, "nubID"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.nubID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionRequest_FromCLI(t *testing.T) { + _, cliCommand, cliContext, _, _, testBaseReq := CreateTestInputForRequest(t) + + type fields struct { + BaseReq rest.BaseReq + NubID string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, "nubID"}, args{cliCommand, cliContext}, transactionRequest{cliCommand.ReadBaseReq(cliContext), cliCommand.ReadString(constants.NubID)}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + NubID: tt.fields.NubID, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionRequest_FromJSON(t *testing.T) { + _, _, _, _, fromAccAddress, testBaseReq := CreateTestInputForRequest(t) + + type fields struct { + BaseReq rest.BaseReq + NubID string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, "nubID"}, args{sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, baseIds.NewStringID("nubID")}))}, transactionRequest{testBaseReq, "nubID"}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + NubID: tt.fields.NubID, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, NubID: ""}, requestFromCLI) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + _, _, _, _, _, testBaseReq := CreateTestInputForRequest(t) - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) + type fields struct { + BaseReq rest.BaseReq + NubID string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseReq, "nubID"}, testBaseReq}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + NubID: tt.fields.NubID, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +func Test_transactionRequest_MakeMsg(t *testing.T) { + _, _, _, _, fromAccAddress, testBaseReq := CreateTestInputForRequest(t) - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) + type fields struct { + BaseReq rest.BaseReq + NubID string + } + tests := []struct { + name string + fields fields + want sdkTypes.Msg + wantErr bool + }{ + {"+ve", fields{testBaseReq, "nubID"}, message{fromAccAddress, baseIds.NewStringID("nubID")}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + NubID: tt.fields.NubID, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("nubID")), msg) - require.Nil(t, Error) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + _, _, _, _, _, testBaseReq := CreateTestInputForRequest(t) + + type fields struct { + BaseReq rest.BaseReq + NubID string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseReq, "nubID"}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + NubID: tt.fields.NubID, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "nubID").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_Validate(t *testing.T) { + _, _, _, _, _, testBaseReq := CreateTestInputForRequest(t) - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) + type fields struct { + BaseReq rest.BaseReq + NubID string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseReq, "nubID"}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + NubID: tt.fields.NubID, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/identities/internal/transactions/nub/response.go b/modules/identities/internal/transactions/nub/response.go new file mode 100644 index 000000000..3a0f15b5a --- /dev/null +++ b/modules/identities/internal/transactions/nub/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package nub + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/identities/internal/transactions/nub/transaction.go b/modules/identities/internal/transactions/nub/transaction.go new file mode 100644 index 000000000..777bb4f56 --- /dev/null +++ b/modules/identities/internal/transactions/nub/transaction.go @@ -0,0 +1,21 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package nub + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "nub", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.NubID, +) diff --git a/modules/identities/internal/transactions/prototype.go b/modules/identities/internal/transactions/prototype.go new file mode 100644 index 000000000..1d03734dd --- /dev/null +++ b/modules/identities/internal/transactions/prototype.go @@ -0,0 +1,32 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transactions + +import ( + "github.com/AssetMantle/modules/modules/identities/internal/transactions/define" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/deputize" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/issue" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/mutate" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/nub" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/provision" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/quash" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/revoke" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/unprovision" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Transactions { + return baseHelpers.NewTransactions( + define.Transaction, + deputize.Transaction, + issue.Transaction, + mutate.Transaction, + nub.Transaction, + provision.Transaction, + quash.Transaction, + revoke.Transaction, + unprovision.Transaction, + ) +} diff --git a/modules/identities/internal/transactions/prototype_test.go b/modules/identities/internal/transactions/prototype_test.go new file mode 100644 index 000000000..fce3f1033 --- /dev/null +++ b/modules/identities/internal/transactions/prototype_test.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transactions + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/identities/internal/transactions/define" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/deputize" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/issue" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/nub" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/provision" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/revoke" + "github.com/AssetMantle/modules/modules/identities/internal/transactions/unprovision" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Get("unprovision").GetName(), baseHelpers.NewTransactions( + define.Transaction, + deputize.Transaction, + issue.Transaction, + nub.Transaction, + provision.Transaction, + revoke.Transaction, + unprovision.Transaction, + ).Get("unprovision").GetName()) +} diff --git a/modules/identities/internal/transactions/provision/keeper.go b/modules/identities/internal/transactions/provision/keeper.go new file mode 100644 index 000000000..94bf0dd1a --- /dev/null +++ b/modules/identities/internal/transactions/provision/keeper.go @@ -0,0 +1,81 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package provision + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/define" + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/schema/documents" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionKeeper struct { + mapper helpers.Mapper + supplementAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + identityID := message.IdentityID + identities := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(identityID)) + + Mappable := identities.Get(key.NewKey(identityID)) + if Mappable == nil { + return newTransactionResponse(errorConstants.EntityNotFound) + } + identity := Mappable.(documents.Identity) + + if !identity.IsProvisioned(message.From) { + return newTransactionResponse(errorConstants.NotAuthorized) + } + + if identity.IsProvisioned(message.To) { + return newTransactionResponse(errorConstants.EntityAlreadyExists) + } + + identities.Mutate(mappable.NewMappable(identity.ProvisionAddress(message.To))) + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper = mapper + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case define.Auxiliary.GetName(): + transactionKeeper.supplementAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case supplement.Auxiliary.GetName(): + transactionKeeper.supplementAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} + +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/identities/internal/transactions/provision/message.go b/modules/identities/internal/transactions/provision/message.go index 35ac2f245..3521d2dca 100644 --- a/modules/identities/internal/transactions/provision/message.go +++ b/modules/identities/internal/transactions/provision/message.go @@ -1,68 +1,63 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package provision import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/identities/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing, matches(^[a-z0-9]*$)~field from is invalid"` + To sdkTypes.AccAddress `json:"to" valid:"required~required field to missing, matches(^[a-z0-9]*$)~field to is invalid"` + IdentityID ids.IdentityID `json:"identityID" valid:"required~required field identityID missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, to sdkTypes.AccAddress, identityID types.ID) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - To: base.NewAccAddressFromSDKTypesAccAddress(to), - IdentityID: *base.NewID(identityID.String()), +func newMessage(from sdkTypes.AccAddress, to sdkTypes.AccAddress, identityID ids.IdentityID) sdkTypes.Msg { + return message{ + From: from, + To: to, + IdentityID: identityID, } } diff --git a/modules/identities/internal/transactions/provision/message.pb.go b/modules/identities/internal/transactions/provision/message.pb.go deleted file mode 100644 index d027e2921..000000000 --- a/modules/identities/internal/transactions/provision/message.pb.go +++ /dev/null @@ -1,630 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/transactions/provision/message.proto - -package provision - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - To github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,2,opt,name=to,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"to" valid:"required~required field To missing"` - IdentityID base.ID `protobuf:"bytes,3,opt,name=identity_i_d,json=identityID,proto3" json:"identity_i_d" valid:"required~required IdentityID missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_0604abea0b2258dd, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0604abea0b2258dd, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "modules.identities.internal.transactions.provision.Message") - proto.RegisterType((*TransactionResponse)(nil), "modules.identities.internal.transactions.provision.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/transactions/provision/message.proto", fileDescriptor_0604abea0b2258dd) -} - -var fileDescriptor_0604abea0b2258dd = []byte{ - // 442 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x93, 0x41, 0x6b, 0x13, 0x41, - 0x14, 0xc7, 0x77, 0x12, 0x51, 0x3b, 0x7a, 0x5a, 0x15, 0x42, 0x0e, 0xbb, 0x4b, 0x40, 0x28, 0x45, - 0x66, 0x20, 0x7a, 0xaa, 0xa7, 0x86, 0xa8, 0x04, 0x29, 0x96, 0xda, 0x93, 0x1e, 0xc2, 0x66, 0xe7, - 0x75, 0xfb, 0x30, 0x3b, 0xb3, 0xce, 0x9b, 0x14, 0x8a, 0xd4, 0xb3, 0xe0, 0x45, 0x8f, 0xde, 0xfa, - 0x21, 0xfc, 0x10, 0x3d, 0xf6, 0x28, 0x1e, 0x82, 0x24, 0x17, 0xcf, 0x7e, 0x02, 0xc9, 0x66, 0xd3, - 0x0d, 0x55, 0xd4, 0x48, 0x6f, 0x6f, 0x97, 0x9d, 0xdf, 0xff, 0xc7, 0xbc, 0xff, 0xf2, 0x9d, 0x1c, - 0x2c, 0x21, 0x39, 0xd0, 0x09, 0xf4, 0x49, 0xbd, 0x92, 0x99, 0x51, 0xa3, 0x21, 0x90, 0x44, 0x05, - 0xda, 0xa1, 0xc3, 0xd9, 0xa8, 0x1d, 0x58, 0x1d, 0x0f, 0xa5, 0xb3, 0xb1, 0xa6, 0x38, 0x71, 0x68, - 0x34, 0xc9, 0xdc, 0x9a, 0x43, 0x24, 0x34, 0x5a, 0x66, 0x40, 0x14, 0xa7, 0x20, 0x72, 0x6b, 0x9c, - 0xf1, 0xdb, 0x25, 0x41, 0x54, 0x04, 0xb1, 0x20, 0x88, 0x65, 0x82, 0x38, 0x27, 0x34, 0x6f, 0xa7, - 0x26, 0x35, 0xc5, 0x71, 0x39, 0x9b, 0xe6, 0xa4, 0xe6, 0xc6, 0x45, 0x37, 0x4a, 0x0e, 0x20, 0x8b, - 0xa5, 0x3b, 0xca, 0x81, 0xe4, 0x20, 0x26, 0x90, 0xa8, 0xe6, 0xdf, 0xb6, 0x3e, 0xd7, 0xf9, 0xb5, - 0xed, 0xb9, 0x87, 0xff, 0x91, 0xf1, 0x2b, 0xfb, 0xd6, 0x64, 0x0d, 0x16, 0xb1, 0xf5, 0xb5, 0xce, - 0xf1, 0xe9, 0x38, 0xf4, 0xbe, 0x8e, 0xc3, 0x47, 0x29, 0xba, 0x83, 0xd1, 0x40, 0x24, 0x26, 0x93, - 0x4b, 0xe4, 0x67, 0x1a, 0x96, 0x1f, 0x9f, 0x77, 0x9f, 0xfe, 0x9a, 0x23, 0xb6, 0x92, 0x64, 0x4b, - 0x29, 0x0b, 0x44, 0x3f, 0xc6, 0xe1, 0xbd, 0xc3, 0x78, 0x88, 0x6a, 0xb3, 0x65, 0xe1, 0xf5, 0x08, - 0x2d, 0xa8, 0xb7, 0x8b, 0x21, 0xda, 0x47, 0x18, 0xaa, 0xe8, 0xb1, 0x35, 0x59, 0x94, 0x21, 0x11, - 0xea, 0xb4, 0xb5, 0x5b, 0xa8, 0xf8, 0xef, 0x19, 0xaf, 0x39, 0xd3, 0xa8, 0x15, 0x46, 0x6f, 0x2e, - 0xdb, 0x68, 0xe3, 0x2f, 0x46, 0x7b, 0xa6, 0xf2, 0xa9, 0x39, 0xe3, 0x1f, 0xf3, 0x9b, 0xe5, 0x76, - 0x8e, 0xfa, 0xd8, 0x57, 0x8d, 0x7a, 0xc4, 0xd6, 0x6f, 0xb4, 0xef, 0x8a, 0x0b, 0x17, 0x2e, 0xe6, - 0xb1, 0xa2, 0x88, 0x15, 0x45, 0x6c, 0xaf, 0xdb, 0x79, 0x30, 0xb3, 0xff, 0xe3, 0x35, 0xf4, 0x4a, - 0x76, 0xaf, 0x5b, 0xc5, 0x72, 0x3c, 0x7f, 0xb9, 0x79, 0xfd, 0xdd, 0x49, 0xe8, 0x7d, 0x3f, 0x09, - 0xbd, 0xd6, 0x1d, 0x7e, 0x6b, 0xaf, 0xaa, 0xc4, 0x2e, 0x50, 0x6e, 0x34, 0x41, 0xfb, 0x13, 0xe3, - 0xf5, 0x6d, 0x4a, 0x67, 0x9b, 0x5c, 0xdb, 0x59, 0xb4, 0xc4, 0x7f, 0x28, 0x56, 0xaf, 0x96, 0x28, - 0x4b, 0xd1, 0x7c, 0xf2, 0x3f, 0x87, 0x7f, 0xe3, 0xd6, 0x19, 0x9d, 0x4e, 0x02, 0x76, 0x36, 0x09, - 0xd8, 0xb7, 0x49, 0xc0, 0x3e, 0x4c, 0x03, 0xef, 0x6c, 0x1a, 0x78, 0x5f, 0xa6, 0x81, 0xf7, 0xe2, - 0xe5, 0x3f, 0xaf, 0x73, 0xf5, 0x9f, 0x6c, 0x70, 0xb5, 0xe8, 0xf9, 0xfd, 0x9f, 0x01, 0x00, 0x00, - 0xff, 0xff, 0x6f, 0x54, 0xfd, 0x58, 0xb1, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Provision(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Provision(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/modules.identities.internal.transactions.provision.Msg/Provision", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Provision(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Provision(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Provision not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Provision_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Provision(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/modules.identities.internal.transactions.provision.Msg/Provision", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Provision(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "modules.identities.internal.transactions.provision.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Provision", - Handler: _Msg_Provision_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/identities/internal/transactions/provision/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.IdentityID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.To.Size() - i -= size - if _, err := m.To.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.To.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.IdentityID.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field To", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.To.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IdentityID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IdentityID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/transactions/provision/message_test.go b/modules/identities/internal/transactions/provision/message_test.go index d9f9a9437..dbfd680a0 100644 --- a/modules/identities/internal/transactions/provision/message_test.go +++ b/modules/identities/internal/transactions/provision/message_test.go @@ -1,23 +1,32 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package provision import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/identities/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Provision_Message(t *testing.T) { - testIdentityID := base.NewID("identityID") +func createInputForMessage(t *testing.T) (ids.IdentityID, string, sdkTypes.AccAddress, string, sdkTypes.AccAddress, sdkTypes.Msg) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testIdentityID := baseIDs.NewIdentityID(testClassificationID, immutables) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) @@ -28,15 +37,242 @@ func Test_Provision_Message(t *testing.T) { require.Nil(t, err) testMessage := newMessage(fromAccAddress, toAccAddress, testIdentityID) - require.Equal(t, Message{From: fromAccAddress, To: toAccAddress, IdentityID: testIdentityID}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) + return testIdentityID, fromAddress, fromAccAddress, toAddress, toAccAddress, testMessage +} + +func Test_messageFromInterface(t *testing.T) { + testIdentityID, _, fromAccAddress, _, toAccAddress, testMessage := createInputForMessage(t) + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{testMessage}, message{fromAccAddress, toAccAddress, testIdentityID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + testIdentityID, _, fromAccAddress, _, toAccAddress, testMessage := createInputForMessage(t) + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + IdentityID ids.IdentityID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testIdentityID}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(testMessage))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + testIdentityID, _, fromAccAddress, _, toAccAddress, _ := createInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + IdentityID ids.IdentityID + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testIdentityID}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + testIdentityID, _, fromAccAddress, _, toAccAddress, _ := createInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + IdentityID ids.IdentityID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testIdentityID}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + testIdentityID, _, fromAccAddress, _, toAccAddress, _ := createInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + IdentityID ids.IdentityID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testIdentityID}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + testIdentityID, _, fromAccAddress, _, toAccAddress, _ := createInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + IdentityID ids.IdentityID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testIdentityID}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + testIdentityID, _, fromAccAddress, _, toAccAddress, _ := createInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + IdentityID ids.IdentityID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testIdentityID}, false}, + {"+ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_newMessage(t *testing.T) { + testIdentityID, _, fromAccAddress, _, toAccAddress, _ := createInputForMessage(t) + + type args struct { + from sdkTypes.AccAddress + to sdkTypes.AccAddress + identityID ids.IdentityID + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, toAccAddress, testIdentityID}, message{fromAccAddress, toAccAddress, testIdentityID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.to, tt.args.identityID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/identities/internal/transactions/provision/msg_server.go b/modules/identities/internal/transactions/provision/msg_server.go deleted file mode 100644 index df142116c..000000000 --- a/modules/identities/internal/transactions/provision/msg_server.go +++ /dev/null @@ -1,64 +0,0 @@ -package provision - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Provision(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - identityID := message.IdentityID - identities := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(&identityID)) - - identity := identities.Get(key.FromID(&identityID)) - if identity == nil { - return nil, errors.EntityNotFound - } - - if !identity.(mappables.InterIdentity).IsProvisioned(message.From.AsSDKTypesAccAddress()) { - return nil, errors.NotAuthorized - } - - if !identity.(mappables.InterIdentity).IsProvisioned(message.To.AsSDKTypesAccAddress()) { - return nil, errors.EntityAlreadyExists - } - - identityAuthenticationProperty := identity.(mappables.InterIdentity).GetAuthentication() - metaProperties, Error := supplement.GetMetaPropertiesFromResponse(msgServer.transactionKeeper.supplementAuxiliary.GetKeeper().Help(ctx, supplement.NewAuxiliaryRequest(identityAuthenticationProperty))) - if Error != nil { - return nil, Error - } - listData, Error := metaProperties.GetList()[0].GetMetaFact().GetData().AsListData() - if Error != nil { - return nil, Error - } - listData.Add(base.NewAccAddressData(message.To.AsSDKTypesAccAddress())) - authenticationProperty := base.NewMetaProperty(base.NewID(properties.Authentication), base.NewMetaFact(listData)) - mutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(authenticationProperty))) - if Error != nil { - return nil, Error - } - modifiedMutableProperties := identity.(mappables.InterIdentity).GetMutableProperties().Mutate(mutableMetaProperties.GetList()...) - identities.Mutate(mappable.NewIdentity(&identityID, identity.(mappables.InterIdentity).GetImmutableProperties(), modifiedMutableProperties)) - //identities.Mutate(identity.(mappables.InterIdentity).ProvisionAddress(message.To.AsSDKTypesAccAddress())) - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/identities/internal/transactions/provision/request.go b/modules/identities/internal/transactions/provision/request.go index 0ffcca059..4d4f28b05 100644 --- a/modules/identities/internal/transactions/provision/request.go +++ b/modules/identities/internal/transactions/provision/request.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package provision @@ -9,15 +7,15 @@ import ( "encoding/json" "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -28,30 +26,30 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary provision identities transaction -// @Descrption provision identities +// Validate godoc +// @Summary Provision an identity +// @Description Provision identities // @Accept text/plain // @Produce json // @Tags Identities -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body body transactionRequest true "Request body for provision identity" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /identities/provision [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.To), - cliCommand.ReadString(flags.IdentityID), + cliCommand.ReadString(constants.To), + cliCommand.ReadString(constants.IdentityID), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -60,24 +58,29 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + to, err := sdkTypes.AccAddressFromBech32(transactionRequest.To) + if err != nil { + return nil, err } - to, Error := sdkTypes.AccAddressFromBech32(transactionRequest.To) - if Error != nil { - return nil, Error + identityID, err := baseIDs.ReadIdentityID(transactionRequest.IdentityID) + if err != nil { + return nil, err } return newMessage( from, to, - base.NewID(transactionRequest.IdentityID), + identityID, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/identities/internal/transactions/provision/request_test.go b/modules/identities/internal/transactions/provision/request_test.go index 3ddd86f31..e68ca8dbc 100644 --- a/modules/identities/internal/transactions/provision/request_test.go +++ b/modules/identities/internal/transactions/provision/request_test.go @@ -1,81 +1,292 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package provision import ( "encoding/json" - "github.com/cosmos/cosmos-sdk/client" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" - "testing" + + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Provision_Request(t *testing.T) { +func createTestInput(t *testing.T) (rest.BaseReq, string, ids.IdentityID) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + testToAddress := "cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x" + return testBaseReq, testToAddress, testFromID +} + +func Test_newTransactionRequest(t *testing.T) { + testBaseReq, testToAddress, testFromID := createTestInput(t) + type args struct { + baseReq rest.BaseReq + to string + identityID string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve with nil", args{}, transactionRequest{}}, + {"+ve", args{testBaseReq, testToAddress, testFromID.String()}, transactionRequest{testBaseReq, testToAddress, testFromID.String()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.to, tt.args.identityID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func Test_transactionRequest_FromCLI(t *testing.T) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.IdentityID, flags.To}) + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.To, constants.IdentityID}) cliContext := context.NewCLIContext().WithCodec(Codec) + testBaseReq, testToAddress, testFromID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + To string + IdentityID string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, testToAddress, testFromID.String()}, args{cliCommand: cliCommand, cliContext: cliContext}, transactionRequest{cliCommand.ReadBaseReq(cliContext), cliCommand.ReadString(constants.To), cliCommand.ReadString(constants.IdentityID)}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - toAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - toAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, toAddress, "identityID") - - require.Equal(t, transactionRequest{BaseReq: testBaseReq, To: toAddress, IdentityID: "identityID"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) - - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, To: "", IdentityID: ""}, requestFromCLI) - - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) - - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) - - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromJSON(t *testing.T) { + testBaseReq, testToAddress, testFromID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + To string + IdentityID string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, testToAddress, testFromID.String()}, args{types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{types.AccAddress("cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c"), types.AccAddress(testToAddress), testFromID}))}, transactionRequest{testBaseReq, testToAddress, testFromID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, toAccAddress, base.NewID("identityID")), msg) - require.Nil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + testBaseReq, testToAddress, testFromID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + To string + IdentityID string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseReq, testToAddress, testFromID.String()}, testBaseReq}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, toAddress, "identityID").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_MakeMsg(t *testing.T) { + testBaseReq, testToAddress, testFromID := createTestInput(t) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + toAccAddress, err := types.AccAddressFromBech32(testToAddress) + require.Nil(t, err) + type fields struct { + BaseReq rest.BaseReq + To string + IdentityID string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseReq, testToAddress, testFromID.String()}, message{fromAccAddress, toAccAddress, testFromID}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: fromAddress, ChainID: "test"}, "randomString", "identityID").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + testBaseReq, testToAddress, testFromID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + To string + IdentityID string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve with nil", fields{}, args{codec.New()}}, + {"+ve", fields{testBaseReq, testToAddress, testFromID.String()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + testBaseReq, testToAddress, testFromID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + To string + IdentityID string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve with nil", fields{}, true}, + {"+ve", fields{testBaseReq, testToAddress, testFromID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/identities/internal/transactions/provision/response.go b/modules/identities/internal/transactions/provision/response.go new file mode 100644 index 000000000..e6a9cebbb --- /dev/null +++ b/modules/identities/internal/transactions/provision/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package provision + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/identities/internal/transactions/provision/transaction.go b/modules/identities/internal/transactions/provision/transaction.go new file mode 100644 index 000000000..355b48d55 --- /dev/null +++ b/modules/identities/internal/transactions/provision/transaction.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package provision + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "provision", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.To, + constants.IdentityID, +) diff --git a/modules/identities/internal/transactions/quash/keeper.go b/modules/identities/internal/transactions/quash/keeper.go new file mode 100644 index 000000000..bb18007af --- /dev/null +++ b/modules/identities/internal/transactions/quash/keeper.go @@ -0,0 +1,73 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package quash + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/schema/documents" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + supplementAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + identities := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.IdentityID)) + + Mappable := identities.Get(key.NewKey(message.IdentityID)) + if Mappable == nil { + return newTransactionResponse(errorConstants.EntityNotFound) + } + identity := Mappable.(documents.Identity) + + if identity.GetExpiry().Compare(baseTypes.NewHeight(context.BlockHeight())) > 0 { + return newTransactionResponse(errorConstants.NotAuthorized) + } + + identities.Remove(mappable.NewMappable(identity)) + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper = mapper + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case supplement.Auxiliary.GetName(): + transactionKeeper.supplementAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} + +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/identities/internal/transactions/quash/keeper_test.go b/modules/identities/internal/transactions/quash/keeper_test.go new file mode 100644 index 000000000..8d61751c7 --- /dev/null +++ b/modules/identities/internal/transactions/quash/keeper_test.go @@ -0,0 +1,182 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package quash + +import ( + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/modules/identities/internal/parameters" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +var ( + supplementAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary +) + +type TestKeepers struct { + QuashKeeper helpers.TransactionKeeper +} + +func CreateTestInput(t *testing.T) (types.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := types.NewKVStoreKey("test") + paramsStoreKey := types.NewKVStoreKey("testParams") + paramsTransientStoreKeys := types.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, types.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + supplementAuxiliary = supplement.AuxiliaryMock.Initialize(Mapper, Parameters) + + context := types.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + keepers := TestKeepers{ + QuashKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), + } + + return context, keepers, Mapper, Parameters +} + +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := CreateTestInput(t) + type fields struct { + mapper helpers.Mapper + supplementAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve with nil", fields{}, args{}, transactionKeeper{}}, + {"+ve", fields{Mapper, supplementAuxiliary, authenticateAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, supplementAuxiliary, authenticateAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + supplementAuxiliary: tt.fields.supplementAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.in1, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, _ := CreateTestInput(t) + mutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + immutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + immutables := baseQualified.NewImmutables(immutableProperties) + mutables := baseQualified.NewMutables(mutableProperties) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + testIdentity := baseDocuments.NewIdentity(testClassificationID, immutables, mutables) + testIdentity.ProvisionAddress([]types.AccAddress{fromAccAddress}...) + keepers.QuashKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testIdentity)) + type fields struct { + mapper helpers.Mapper + supplementAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + context types.Context + msg types.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, supplementAuxiliary, authenticateAuxiliary}, args{context, newMessage(fromAccAddress, testFromID, testFromID)}, newTransactionResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + supplementAuxiliary: tt.fields.supplementAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/identities/internal/transactions/quash/message.go b/modules/identities/internal/transactions/quash/message.go index 9c54425fd..17d2b61db 100644 --- a/modules/identities/internal/transactions/quash/message.go +++ b/modules/identities/internal/transactions/quash/message.go @@ -1,68 +1,63 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package quash import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/identities/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + IdentityID ids.IdentityID `json:"identityID" valid:"required~required field identityID missing"` +} + +var _ helpers.Message = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, identityID types.ID) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - IdentityID: *base.NewID(identityID.String()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, identityID ids.IdentityID) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + IdentityID: identityID, } } diff --git a/modules/identities/internal/transactions/quash/message.pb.go b/modules/identities/internal/transactions/quash/message.pb.go deleted file mode 100644 index 0efd507e6..000000000 --- a/modules/identities/internal/transactions/quash/message.pb.go +++ /dev/null @@ -1,629 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/transactions/quash/message.proto - -package quash - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required FromID missing"` - IdentityID base.ID `protobuf:"bytes,3,opt,name=identity_i_d,json=identityID,proto3" json:"identity_i_d" valid:"required~required IdentityID missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_7a0477d664af2a02, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_7a0477d664af2a02, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.identities.internal.transactions.quash.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.identities.internal.transactions.quash.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/transactions/quash/message.proto", fileDescriptor_7a0477d664af2a02) -} - -var fileDescriptor_7a0477d664af2a02 = []byte{ - // 442 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0x4f, 0x6b, 0x13, 0x41, - 0x18, 0xc6, 0x77, 0x8c, 0xd6, 0x3a, 0x7a, 0x5a, 0x15, 0x4a, 0x0e, 0xbb, 0x21, 0xa0, 0x04, 0x91, - 0x19, 0xa9, 0x9e, 0x7a, 0x10, 0x1a, 0xa2, 0x12, 0xb4, 0x88, 0xad, 0x20, 0x78, 0x09, 0x93, 0x9d, - 0xb7, 0x9b, 0xc1, 0xec, 0x4c, 0x32, 0xef, 0x44, 0xe9, 0x41, 0xcf, 0x82, 0x17, 0xc1, 0x2f, 0xd0, - 0x8b, 0x47, 0xbf, 0x47, 0x8f, 0x3d, 0x8a, 0x87, 0x20, 0xc9, 0xc5, 0x73, 0x3f, 0x81, 0xec, 0xec, - 0xd6, 0x2c, 0xf1, 0x0f, 0x96, 0x9c, 0xf6, 0xdd, 0x61, 0xf9, 0xfd, 0x1e, 0xe6, 0x7d, 0x96, 0x3e, - 0x19, 0x81, 0x45, 0x85, 0x0e, 0x74, 0x02, 0x3d, 0x94, 0xaf, 0x78, 0x66, 0xe4, 0x64, 0x08, 0xc8, - 0x95, 0x04, 0xed, 0x94, 0x53, 0xf9, 0xa8, 0x1d, 0x58, 0x2d, 0x86, 0xdc, 0x59, 0xa1, 0x51, 0x24, - 0x4e, 0x19, 0x8d, 0x7c, 0x3c, 0x11, 0x38, 0xe0, 0x19, 0x20, 0x8a, 0x14, 0xd8, 0xc8, 0x1a, 0x67, - 0xc2, 0xfb, 0x4b, 0x34, 0x56, 0xd2, 0xd8, 0x82, 0xc6, 0x4e, 0x69, 0xac, 0x4a, 0x63, 0x9e, 0x56, - 0xbf, 0x96, 0x9a, 0xd4, 0x78, 0x14, 0xcf, 0xa7, 0x82, 0x5a, 0xbf, 0xb5, 0x9c, 0x11, 0x93, 0x01, - 0x64, 0x82, 0xbb, 0x83, 0x11, 0x20, 0xef, 0x0b, 0x04, 0xae, 0x64, 0xf1, 0x6d, 0xf3, 0x53, 0x8d, - 0x5e, 0xdc, 0x29, 0x32, 0x85, 0x1f, 0x08, 0x3d, 0xbf, 0x6f, 0x4d, 0xb6, 0x41, 0x1a, 0xa4, 0x75, - 0xa9, 0xfd, 0xe6, 0x68, 0x1a, 0x07, 0xdf, 0xa6, 0xf1, 0x83, 0x54, 0xb9, 0xc1, 0xa4, 0xcf, 0x12, - 0x93, 0xf1, 0x0a, 0xf9, 0xa9, 0x86, 0xea, 0xeb, 0x5e, 0xe7, 0xf1, 0xef, 0x1e, 0xb6, 0x9d, 0x24, - 0xdb, 0x52, 0x5a, 0x40, 0x3c, 0x99, 0xc6, 0x37, 0x5f, 0x8b, 0xa1, 0x92, 0x5b, 0x4d, 0x0b, 0xe3, - 0x89, 0xb2, 0x20, 0xdf, 0x9d, 0x0e, 0x8d, 0x87, 0xd6, 0x64, 0x8d, 0x4c, 0x21, 0x2a, 0x9d, 0x36, - 0x77, 0x7d, 0x88, 0x70, 0x4c, 0xd7, 0xf3, 0x67, 0x4f, 0xf5, 0xe4, 0xc6, 0xb9, 0x06, 0x69, 0x5d, - 0xde, 0xbc, 0xc1, 0x96, 0xaf, 0xab, 0x10, 0x32, 0x2f, 0x64, 0x5e, 0xd8, 0xed, 0xb4, 0xef, 0xe4, - 0xb9, 0x4f, 0xa6, 0x71, 0xeb, 0x9f, 0xba, 0x6e, 0x67, 0x21, 0x5c, 0xdb, 0xf7, 0x07, 0xe1, 0x5b, - 0x7a, 0xa5, 0xbc, 0xf8, 0x03, 0xaf, 0xad, 0x9d, 0x45, 0x7b, 0xaf, 0xd4, 0xde, 0xfe, 0xab, 0xb6, - 0x5b, 0xb2, 0xab, 0x6a, 0xaa, 0x7e, 0x1d, 0x6e, 0xad, 0xbf, 0x3f, 0x8c, 0x83, 0x1f, 0x87, 0x71, - 0xd0, 0xbc, 0x4e, 0xaf, 0x3e, 0x5f, 0x6c, 0x7b, 0x17, 0x70, 0x64, 0x34, 0xc2, 0xe6, 0x17, 0x42, - 0x6b, 0x3b, 0x98, 0x86, 0x9f, 0x09, 0xbd, 0xf0, 0x2c, 0x2f, 0x40, 0xf8, 0x88, 0xad, 0xd6, 0x20, - 0x56, 0xee, 0xbe, 0xbe, 0xb7, 0x2a, 0xe8, 0x0f, 0x79, 0xdb, 0xe3, 0xa3, 0x59, 0x44, 0x8e, 0x67, - 0x11, 0xf9, 0x3e, 0x8b, 0xc8, 0xc7, 0x79, 0x14, 0x1c, 0xcf, 0xa3, 0xe0, 0xeb, 0x3c, 0x0a, 0x5e, - 0xbe, 0xf8, 0xef, 0x4e, 0x9d, 0xed, 0xff, 0xea, 0xaf, 0xf9, 0x5a, 0xdf, 0xfd, 0x19, 0x00, 0x00, - 0xff, 0xff, 0xf0, 0xf9, 0x1c, 0x5a, 0xa8, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Quash(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Quash(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.identities.internal.transactions.quash.Msg/Quash", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Quash(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Quash(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Quash not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Quash_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Quash(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.identities.internal.transactions.quash.Msg/Quash", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Quash(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.identities.internal.transactions.quash.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Quash", - Handler: _Msg_Quash_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/identities/internal/transactions/quash/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.IdentityID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.IdentityID.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IdentityID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IdentityID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/transactions/quash/message_test.go b/modules/identities/internal/transactions/quash/message_test.go index 322305285..33267bebb 100644 --- a/modules/identities/internal/transactions/quash/message_test.go +++ b/modules/identities/internal/transactions/quash/message_test.go @@ -1,39 +1,271 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package quash import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/identities/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Quash_Message(t *testing.T) { - testIdentityID := base.NewID("identityID") - testFromID := base.NewID("fromID") +func createInputForMessage(t *testing.T) (ids.IdentityID, ids.IdentityID, sdkTypes.AccAddress, sdkTypes.Msg) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) + testIdentityID := baseIDs.NewIdentityID(testClassificationID, immutables) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) require.Nil(t, err) testMessage := newMessage(fromAccAddress, testFromID, testIdentityID) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, IdentityID: testIdentityID}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) + return testIdentityID, testFromID, fromAccAddress, testMessage +} + +func Test_messageFromInterface(t *testing.T) { + testIdentityID, testFromID, fromAccAddress, testMessage := createInputForMessage(t) + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{testMessage}, message{fromAccAddress, testFromID, testIdentityID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + testIdentityID, testFromID, fromAccAddress, testMessage := createInputForMessage(t) + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + IdentityID ids.IdentityID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, testFromID, testIdentityID}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(testMessage))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + testIdentityID, testFromID, fromAccAddress, _ := createInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + IdentityID ids.IdentityID + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, testFromID, testIdentityID}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + testIdentityID, testFromID, fromAccAddress, _ := createInputForMessage(t) + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + IdentityID ids.IdentityID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, testFromID, testIdentityID}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + testIdentityID, testFromID, fromAccAddress, _ := createInputForMessage(t) + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + IdentityID ids.IdentityID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testIdentityID}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + testIdentityID, testFromID, fromAccAddress, _ := createInputForMessage(t) + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + IdentityID ids.IdentityID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testIdentityID}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + testIdentityID, testFromID, fromAccAddress, _ := createInputForMessage(t) + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + IdentityID ids.IdentityID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, testFromID, testIdentityID}, false}, + {"-ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_newMessage(t *testing.T) { + testIdentityID, testFromID, fromAccAddress, _ := createInputForMessage(t) + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + identityID ids.IdentityID + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, testFromID, testIdentityID}, message{fromAccAddress, testFromID, testIdentityID}}, + {"-ve", args{}, message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.identityID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/identities/internal/transactions/quash/msg_server.go b/modules/identities/internal/transactions/quash/msg_server.go deleted file mode 100644 index b18b1b5d6..000000000 --- a/modules/identities/internal/transactions/quash/msg_server.go +++ /dev/null @@ -1,60 +0,0 @@ -package quash - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Quash(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - identities := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(&message.IdentityID)) - - identity := identities.Get(key.FromID(&message.IdentityID)) - if identity == nil { - return nil, errors.EntityNotFound - } - - metaProperties, Error := supplement.GetMetaPropertiesFromResponse(msgServer.transactionKeeper.supplementAuxiliary.GetKeeper().Help(ctx, supplement.NewAuxiliaryRequest(identity.(mappables.InterIdentity).GetExpiry()))) - if Error != nil { - return nil, Error - } - - expiryHeightMetaFact := metaProperties.Get(base.NewID(properties.Expiry)) - if expiryHeightMetaFact == nil { - return nil, errors.EntityNotFound - } - - expiryHeight, Error := expiryHeightMetaFact.GetMetaFact().GetData().AsHeight() - if Error != nil { - return nil, Error - } - - if expiryHeight.Compare(base.NewHeight(ctx.BlockHeight())) > 0 { - return nil, errors.NotAuthorized - } - - identities.Remove(identity) - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/identities/internal/transactions/quash/request.go b/modules/identities/internal/transactions/quash/request.go index 88fa3dfd3..122690e14 100644 --- a/modules/identities/internal/transactions/quash/request.go +++ b/modules/identities/internal/transactions/quash/request.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package quash @@ -9,15 +7,15 @@ import ( "encoding/json" "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -28,30 +26,30 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary quash identitity transaction -// @Descrption quash identity transaction +// Validate godoc +// @Summary Quash identity transaction +// @Description Quash identity transaction // @Accept text/plain // @Produce json // @Tags Identities -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body body transactionRequest true "Request body for quash identity" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /identities/quash [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.IdentityID), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.IdentityID), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -60,19 +58,29 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + identityID, err := baseIDs.ReadIdentityID(transactionRequest.IdentityID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.IdentityID), + fromID, + identityID, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/identities/internal/transactions/quash/request_test.go b/modules/identities/internal/transactions/quash/request_test.go index 1b8e5d63b..835f33dc2 100644 --- a/modules/identities/internal/transactions/quash/request_test.go +++ b/modules/identities/internal/transactions/quash/request_test.go @@ -1,74 +1,290 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package quash import ( "encoding/json" + "reflect" "testing" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Quash_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.IdentityID}) - cliContext := context.NewCLIContext().WithCodec(Codec) - +func createTestInput(t *testing.T) (rest.BaseReq, string, ids.IdentityID) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, err) - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "identityID") + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + testToAddress := "cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x" + return testBaseReq, testToAddress, testFromID +} - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", IdentityID: "identityID"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) +func Test_newTransactionRequest(t *testing.T) { + testBaseReq, testToAddress, testFromID := createTestInput(t) + type args struct { + baseReq rest.BaseReq + fromID string + identityID string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve with nil", args{}, transactionRequest{}}, + {"+ve", args{testBaseReq, testToAddress, testFromID.String()}, transactionRequest{testBaseReq, testToAddress, testFromID.String()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.identityID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - requestFromCLI, err := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, err) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", IdentityID: ""}, requestFromCLI) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, err := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, err) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_transactionRequest_FromCLI(t *testing.T) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.IdentityID}) + cliContext := context.NewCLIContext().WithCodec(Codec) + testBaseReq, _, testFromID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + FromID string + IdentityID string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, testFromID.String(), testFromID.String()}, args{cliCommand: cliCommand, cliContext: cliContext}, transactionRequest{cliCommand.ReadBaseReq(cliContext), cliCommand.ReadString(constants.FromID), cliCommand.ReadString(constants.IdentityID)}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, err := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, err) +func Test_transactionRequest_FromJSON(t *testing.T) { + testBaseReq, testToAddress, testFromID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + FromID string + IdentityID string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, testToAddress, testFromID.String()}, args{types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{types.AccAddress("cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c"), testFromID, testFromID}))}, transactionRequest{testBaseReq, testToAddress, testFromID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + testBaseReq, testToAddress, testFromID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + FromID string + IdentityID string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseReq, testToAddress, testFromID.String()}, testBaseReq}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, err := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("identityID")), msg) +func Test_transactionRequest_MakeMsg(t *testing.T) { + testBaseReq, _, testFromID := createTestInput(t) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) require.Nil(t, err) + type fields struct { + BaseReq rest.BaseReq + FromID string + IdentityID string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseReq, testFromID.String(), testFromID.String()}, message{fromAccAddress, testFromID, testFromID}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg2, err := newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", "identityID").MakeMsg() - require.NotNil(t, err) - require.Nil(t, msg2) - - require.Equal(t, transactionRequest{}, requestPrototype()) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + testBaseReq, testToAddress, testFromID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + FromID string + IdentityID string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve with nil", fields{}, args{codec.New()}}, + {"+ve", fields{testBaseReq, testToAddress, testFromID.String()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + testBaseReq, testToAddress, testFromID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + FromID string + IdentityID string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve with nil", fields{}, true}, + {"+ve", fields{testBaseReq, testToAddress, testFromID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + IdentityID: tt.fields.IdentityID, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/identities/internal/transactions/quash/response.go b/modules/identities/internal/transactions/quash/response.go new file mode 100644 index 000000000..88370fee5 --- /dev/null +++ b/modules/identities/internal/transactions/quash/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package quash + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/identities/internal/transactions/quash/transaction.go b/modules/identities/internal/transactions/quash/transaction.go new file mode 100644 index 000000000..3f03d60c8 --- /dev/null +++ b/modules/identities/internal/transactions/quash/transaction.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package quash + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "quash", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.IdentityID, +) diff --git a/modules/identities/internal/transactions/revoke/keeper.go b/modules/identities/internal/transactions/revoke/keeper.go new file mode 100644 index 000000000..eec34d6b0 --- /dev/null +++ b/modules/identities/internal/transactions/revoke/keeper.go @@ -0,0 +1,57 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/revoke" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + revokeAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + if auxiliaryResponse := transactionKeeper.revokeAuxiliary.GetKeeper().Help(context, revoke.NewAuxiliaryRequest(message.FromID, message.ToID, message.ClassificationID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + return newTransactionResponse(nil) +} +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case revoke.Auxiliary.GetName(): + transactionKeeper.revokeAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(constants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/identities/internal/transactions/revoke/message.go b/modules/identities/internal/transactions/revoke/message.go index cc3180cd6..d7059517a 100644 --- a/modules/identities/internal/transactions/revoke/message.go +++ b/modules/identities/internal/transactions/revoke/message.go @@ -1,70 +1,65 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/identities/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ToID ids.IdentityID `json:"toID" valid:"required~required field toID missing"` + ids.ClassificationID `json:"classificationID" valid:"required~required field classificationID missing"` +} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) - } +var _ sdkTypes.Msg = message{} +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) + } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, toID types.ID, classificationID types.ID) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - ToID: *base.NewID(toID.String()), - ClassificationID: *base.NewID(classificationID.String()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, toID ids.IdentityID, classificationID ids.ClassificationID) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + ToID: toID, + ClassificationID: classificationID, } } diff --git a/modules/identities/internal/transactions/revoke/message.pb.go b/modules/identities/internal/transactions/revoke/message.pb.go deleted file mode 100644 index 4cc8d177f..000000000 --- a/modules/identities/internal/transactions/revoke/message.pb.go +++ /dev/null @@ -1,677 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/transactions/revoke/message.proto - -package revoke - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required FromID missing"` - ToID base.ID `protobuf:"bytes,3,opt,name=to_i_d,json=toID,proto3" json:"to_i_d" valid:"required~required ToID missing"` - ClassificationID base.ID `protobuf:"bytes,4,opt,name=classification_i_d,json=classificationID,proto3" json:"classification_i_d" valid:"required~required ClassificationID missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_9c84d09bfd503118, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9c84d09bfd503118, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.identities.internal.transactions.revoke.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.identities.internal.transactions.revoke.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/transactions/revoke/message.proto", fileDescriptor_9c84d09bfd503118) -} - -var fileDescriptor_9c84d09bfd503118 = []byte{ - // 470 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0x3f, 0x8b, 0x13, 0x41, - 0x18, 0xc6, 0x77, 0xbc, 0x10, 0xcf, 0xb5, 0x91, 0x55, 0xe1, 0x48, 0xb1, 0x1b, 0x02, 0x4a, 0xb0, - 0x98, 0x91, 0xd8, 0xa5, 0x91, 0x8b, 0x51, 0x0c, 0x12, 0x84, 0x98, 0x42, 0x6c, 0xc2, 0x66, 0xe6, - 0xcd, 0xde, 0x90, 0xec, 0x4c, 0x6e, 0xde, 0xc9, 0x89, 0x8d, 0xb5, 0x60, 0xa1, 0xe0, 0x17, 0xb8, - 0xd2, 0xd2, 0x8f, 0x71, 0xe5, 0x95, 0x62, 0x11, 0x24, 0x69, 0xac, 0xef, 0x13, 0xc8, 0xce, 0xe6, - 0xc8, 0x1a, 0x3d, 0xb9, 0x70, 0xd5, 0xbe, 0xfb, 0x87, 0xdf, 0xef, 0xd9, 0xdd, 0xe7, 0xf5, 0xbb, - 0x53, 0x30, 0x28, 0xd1, 0x82, 0xe2, 0x30, 0x40, 0x31, 0x66, 0xa9, 0x16, 0xb3, 0x09, 0x20, 0x93, - 0x02, 0x94, 0x95, 0x56, 0x66, 0xa3, 0xb2, 0x60, 0x54, 0x3c, 0x61, 0xd6, 0xc4, 0x0a, 0x63, 0x6e, - 0xa5, 0x56, 0xc8, 0x0c, 0x1c, 0xe9, 0x31, 0xb0, 0x14, 0x10, 0xe3, 0x04, 0xe8, 0xd4, 0x68, 0xab, - 0x83, 0xc7, 0x1b, 0x38, 0xba, 0xc2, 0xd1, 0x35, 0x8e, 0x9e, 0xe3, 0x68, 0x11, 0x47, 0x73, 0x5c, - 0xe5, 0x4e, 0xa2, 0x13, 0xed, 0x58, 0x2c, 0x9b, 0x72, 0x6c, 0xe5, 0xc1, 0x66, 0x4a, 0xe4, 0x07, - 0x90, 0xc6, 0xcc, 0xbe, 0x9b, 0x02, 0xb2, 0x61, 0x8c, 0xc0, 0xa4, 0xc8, 0x9f, 0xad, 0x7d, 0x29, - 0xf9, 0xd7, 0xbb, 0x79, 0xa8, 0xe0, 0x23, 0xf1, 0x4b, 0x23, 0xa3, 0xd3, 0x3d, 0x52, 0x25, 0xf5, - 0x1b, 0xad, 0xb7, 0x27, 0xf3, 0xc8, 0xfb, 0x31, 0x8f, 0x9e, 0x26, 0xd2, 0x1e, 0xcc, 0x86, 0x94, - 0xeb, 0x94, 0x15, 0xc8, 0x2f, 0x15, 0x14, 0x4f, 0x5f, 0xb5, 0x5f, 0xfc, 0xed, 0xa1, 0xfb, 0x9c, - 0xef, 0x0b, 0x61, 0x00, 0xf1, 0x6c, 0x1e, 0xdd, 0x3f, 0x8a, 0x27, 0x52, 0x34, 0x6b, 0x06, 0x0e, - 0x67, 0xd2, 0x80, 0x78, 0x7f, 0x3e, 0x54, 0x9f, 0x19, 0x9d, 0x56, 0x53, 0x89, 0x28, 0x55, 0x52, - 0xeb, 0xb9, 0x10, 0xc1, 0xa1, 0xbf, 0x9b, 0x1d, 0x07, 0x72, 0x20, 0xf6, 0xae, 0x55, 0x49, 0xfd, - 0x66, 0xe3, 0x1e, 0xdd, 0xfc, 0x5e, 0xb9, 0x90, 0x3a, 0x21, 0x75, 0xc2, 0x4e, 0xbb, 0xf5, 0x30, - 0xcb, 0x7d, 0x36, 0x8f, 0xea, 0xff, 0xd5, 0x75, 0xda, 0x6b, 0x61, 0x79, 0xe4, 0x2e, 0x04, 0x63, - 0xbf, 0x6c, 0xb5, 0x13, 0xee, 0x6c, 0x23, 0xa4, 0x2b, 0xe1, 0xc5, 0xef, 0xd7, 0xd7, 0x45, 0x5d, - 0xc9, 0xea, 0x4e, 0x3b, 0xf8, 0x44, 0xfc, 0x80, 0x4f, 0x62, 0x44, 0x39, 0x92, 0x3c, 0xce, 0x7e, - 0xab, 0x33, 0x97, 0xb6, 0x31, 0x37, 0x57, 0xe6, 0xc6, 0x85, 0xe6, 0x27, 0x7f, 0x18, 0x8a, 0x29, - 0x6e, 0xf1, 0x8d, 0x5b, 0xcd, 0xdd, 0x0f, 0xc7, 0x91, 0xf7, 0xeb, 0x38, 0xf2, 0x6a, 0x77, 0xfd, - 0xdb, 0xfd, 0x75, 0xdd, 0x7a, 0x80, 0x53, 0xad, 0x10, 0x1a, 0xdf, 0x88, 0xbf, 0xd3, 0xc5, 0x24, - 0xf8, 0x4a, 0xfc, 0x72, 0xcf, 0x35, 0x30, 0x78, 0x4e, 0xaf, 0xd8, 0x61, 0xba, 0x6a, 0x5f, 0xa5, - 0x7f, 0x65, 0xd2, 0x3f, 0x22, 0xb7, 0xcc, 0xc9, 0x22, 0x24, 0xa7, 0x8b, 0x90, 0xfc, 0x5c, 0x84, - 0xe4, 0xf3, 0x32, 0xf4, 0x4e, 0x97, 0xa1, 0xf7, 0x7d, 0x19, 0x7a, 0x6f, 0x5e, 0x5f, 0xba, 0xd6, - 0x5b, 0x2e, 0xf9, 0xb0, 0xec, 0x56, 0xeb, 0xd1, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0x03, 0xa5, - 0x61, 0xcb, 0x2e, 0x04, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Revoke(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Revoke(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.identities.internal.transactions.revoke.Msg/Revoke", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Revoke(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Revoke(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Revoke not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Revoke_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Revoke(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.identities.internal.transactions.revoke.Msg/Revoke", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Revoke(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.identities.internal.transactions.revoke.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Revoke", - Handler: _Msg_Revoke_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/identities/internal/transactions/revoke/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.ClassificationID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ToID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ToID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ClassificationID.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ToID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ToID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/transactions/revoke/message_test.go b/modules/identities/internal/transactions/revoke/message_test.go index 165904ff8..9c233640c 100644 --- a/modules/identities/internal/transactions/revoke/message_test.go +++ b/modules/identities/internal/transactions/revoke/message_test.go @@ -1,25 +1,33 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/identities/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Revoke_Message(t *testing.T) { - testFromID := base.NewID("fromID") - testToID := base.NewID("toID") - testClassificationID := base.NewID("classificationID") +func CreateTestInputForMessage(t *testing.T) (ids.IdentityID, ids.IdentityID, ids.ClassificationID, sdkTypes.AccAddress, sdkTypes.Msg) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) + testToID := baseIDs.NewIdentityID(testClassificationID, immutables) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) @@ -28,14 +36,257 @@ func Test_Revoke_Message(t *testing.T) { require.Equal(t, nil, err) testMessage := newMessage(fromAccAddress, testFromID, testToID, testClassificationID) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, ToID: testToID, ClassificationID: testClassificationID}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) + + return testFromID, testToID, testClassificationID, fromAccAddress, testMessage +} + +func Test_messageFromInterface(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, testMessage := CreateTestInputForMessage(t) + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{testMessage}, message{fromAccAddress, testFromID, testToID, testClassificationID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, testMessage := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(testMessage))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID}, false}, + {"-ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_newMessage(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, _ := CreateTestInputForMessage(t) + + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + toID ids.IdentityID + classificationID ids.ClassificationID + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, testFromID, testToID, testClassificationID}, message{fromAccAddress, testFromID, testToID, testClassificationID}}, + {"-ve with nil", args{}, message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.toID, tt.args.classificationID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/identities/internal/transactions/revoke/msg_server.go b/modules/identities/internal/transactions/revoke/msg_server.go deleted file mode 100644 index 175ff93d0..000000000 --- a/modules/identities/internal/transactions/revoke/msg_server.go +++ /dev/null @@ -1,31 +0,0 @@ -package revoke - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/revoke" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Revoke(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - if auxiliaryResponse := msgServer.transactionKeeper.revokeAuxiliary.GetKeeper().Help(ctx, revoke.NewAuxiliaryRequest(&message.FromID, &message.ToID, &message.ClassificationID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/identities/internal/transactions/revoke/request.go b/modules/identities/internal/transactions/revoke/request.go index 5d279ae65..58897a567 100644 --- a/modules/identities/internal/transactions/revoke/request.go +++ b/modules/identities/internal/transactions/revoke/request.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke @@ -9,15 +7,15 @@ import ( "encoding/json" "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -29,31 +27,31 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary revoke identity transaction -// @Descrption revoke identity transaction +// Validate godoc +// @Summary Revoke identity transaction +// @Description Revoke identity transaction // @Accept text/plain // @Produce json // @Tags Identities -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body transactionRequest true "Request body for revoke identity" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /identities/revoke [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ToID), - cliCommand.ReadString(flags.ClassificationID), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ToID), + cliCommand.ReadString(constants.ClassificationID), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -62,25 +60,38 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + toID, err := baseIDs.ReadIdentityID(transactionRequest.ToID) + if err != nil { + return nil, err + } + classificationID, err := baseIDs.ReadClassificationID(transactionRequest.ClassificationID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.ToID), - base.NewID(transactionRequest.ClassificationID), + fromID, + toID, + classificationID, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} } - func newTransactionRequest(baseReq rest.BaseReq, fromID string, toID string, classificationID string) helpers.TransactionRequest { return transactionRequest{ BaseReq: baseReq, diff --git a/modules/identities/internal/transactions/revoke/request_test.go b/modules/identities/internal/transactions/revoke/request_test.go index 351344516..c144a7873 100644 --- a/modules/identities/internal/transactions/revoke/request_test.go +++ b/modules/identities/internal/transactions/revoke/request_test.go @@ -1,80 +1,307 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke import ( "encoding/json" + "fmt" + "reflect" "testing" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Revoke_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func createTestInput(t *testing.T) (rest.BaseReq, string, ids.IdentityID, ids.IdentityID, ids.ClassificationID) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) + testToID := baseIDs.NewIdentityID(testClassificationID, immutables) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + testToAddress := "cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x" + return testBaseReq, testToAddress, testFromID, testToID, testClassificationID +} + +func Test_newTransactionRequest(t *testing.T) { + testBaseReq, _, testFromID, testToID, testClassificationID := createTestInput(t) + type args struct { + baseReq rest.BaseReq + fromID string + toID string + classificationID string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve with nil", args{}, transactionRequest{}}, + {"+ve", args{testBaseReq, testFromID.String(), testToID.String(), testClassificationID.String()}, transactionRequest{testBaseReq, testFromID.String(), testToID.String(), testClassificationID.String()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.toID, tt.args.classificationID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionRequest_FromCLI(t *testing.T) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.ToID, flags.ClassificationID, flags.MaintainedProperties, flags.AddMaintainer, flags.RemoveMaintainer, flags.MutateMaintainer}) + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.ToID, constants.ClassificationID}) cliContext := context.NewCLIContext().WithCodec(Codec) + testBaseReq, _, testFromID, testToID, testClassificationID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, testFromID.String(), testToID.String(), testClassificationID.String()}, args{cliCommand, cliContext}, transactionRequest{cliCommand.ReadBaseReq(cliContext), cliCommand.ReadString(constants.FromID), cliCommand.ReadString(constants.ToID), cliCommand.ReadString(constants.ClassificationID)}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) +func Test_transactionRequest_FromJSON(t *testing.T) { + testBaseReq, fromAddress, testFromID, testToID, testClassificationID := createTestInput(t) + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) require.Nil(t, err) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, testFromID.String(), testToID.String(), testClassificationID.String()}, args{types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, testFromID, testToID, testClassificationID}))}, transactionRequest{testBaseReq, testFromID.String(), testToID.String(), testClassificationID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, nil, err) - - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID") - - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ToID: "toID", ClassificationID: "classificationID"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) - - requestFromCLI, err := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, err) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ToID: "", ClassificationID: ""}, requestFromCLI) - - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, err := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, err) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) - - randomUnmarshall, err := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, err) - - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + testBaseReq, _, testFromID, testToID, testClassificationID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseReq, testFromID.String(), testToID.String(), testClassificationID.String()}, testBaseReq}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, err := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("toID"), base.NewID("classificationID")), msg) +func Test_transactionRequest_MakeMsg(t *testing.T) { + testBaseReq, fromAccAddress, testFromID, testToID, testClassificationID := createTestInput(t) + testFromAccAddress, err := types.AccAddressFromBech32(fromAccAddress) require.Nil(t, err) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + // TODO: Type & Data same but Not matching + {"+ve", fields{testBaseReq, testFromID.String(), testToID.String(), testClassificationID.String()}, message{testFromAccAddress, testFromID, testToID, testClassificationID}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg2, err := newTransactionRequest(rest.BaseReq{From: "randomString", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "toID", "classificationID").MakeMsg() - require.NotNil(t, err) - require.Nil(t, msg2) - - msg2, err = newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID").MakeMsg() - require.Nil(t, err) - require.NotNil(t, msg2) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + testBaseReq, _, testFromID, testToID, testClassificationID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve with nil", fields{}, args{codec.New()}}, + {"+ve", fields{testBaseReq, testFromID.String(), testToID.String(), testClassificationID.String()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + testBaseReq, _, testFromID, testToID, testClassificationID := createTestInput(t) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve with nil", fields{}, true}, + {"+ve", fields{testBaseReq, testFromID.String(), testToID.String(), testClassificationID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/identities/internal/transactions/revoke/response.go b/modules/identities/internal/transactions/revoke/response.go new file mode 100644 index 000000000..f4e2a16c2 --- /dev/null +++ b/modules/identities/internal/transactions/revoke/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/identities/internal/transactions/revoke/transaction.go b/modules/identities/internal/transactions/revoke/transaction.go new file mode 100644 index 000000000..94603fa7c --- /dev/null +++ b/modules/identities/internal/transactions/revoke/transaction.go @@ -0,0 +1,23 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "revoke", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.ToID, + constants.ClassificationID, +) diff --git a/modules/identities/internal/transactions/unprovision/keeper.go b/modules/identities/internal/transactions/unprovision/keeper.go new file mode 100644 index 000000000..29e91957b --- /dev/null +++ b/modules/identities/internal/transactions/unprovision/keeper.go @@ -0,0 +1,81 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package unprovision + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/define" + "github.com/AssetMantle/modules/modules/identities/internal/key" + "github.com/AssetMantle/modules/modules/identities/internal/mappable" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/schema/documents" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionKeeper struct { + mapper helpers.Mapper + supplementAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + identityID := message.IdentityID + identities := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(identityID)) + + Mappable := identities.Get(key.NewKey(identityID)) + if Mappable == nil { + return newTransactionResponse(errorConstants.EntityNotFound) + } + identity := Mappable.(documents.Identity) + + if !identity.IsProvisioned(message.From) { + return newTransactionResponse(errorConstants.NotAuthorized) + } + + if !identity.IsProvisioned(message.To) { + return newTransactionResponse(errorConstants.EntityNotFound) + } + + identities.Mutate(mappable.NewMappable(identity.UnprovisionAddress(message.To))) + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper = mapper + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case define.Auxiliary.GetName(): + transactionKeeper.supplementAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case supplement.Auxiliary.GetName(): + transactionKeeper.supplementAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} + +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/identities/internal/transactions/unprovision/message.go b/modules/identities/internal/transactions/unprovision/message.go index 2588ff37c..11ab69d5c 100644 --- a/modules/identities/internal/transactions/unprovision/message.go +++ b/modules/identities/internal/transactions/unprovision/message.go @@ -1,68 +1,63 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package unprovision import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/identities/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + To sdkTypes.AccAddress `json:"to" valid:"required~required field to missing, matches(^[a-z0-9]*$)~invalid field to"` + ids.IdentityID `json:"identityID" valid:"required~required field identityID missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, to sdkTypes.AccAddress, identityID types.ID) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - To: base.NewAccAddressFromSDKTypesAccAddress(to), - IdentityID: *base.NewID(identityID.String()), +func newMessage(from sdkTypes.AccAddress, to sdkTypes.AccAddress, identityID ids.IdentityID) sdkTypes.Msg { + return message{ + From: from, + To: to, + IdentityID: identityID, } } diff --git a/modules/identities/internal/transactions/unprovision/message.pb.go b/modules/identities/internal/transactions/unprovision/message.pb.go deleted file mode 100644 index 66017de01..000000000 --- a/modules/identities/internal/transactions/unprovision/message.pb.go +++ /dev/null @@ -1,631 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/identities/internal/transactions/unprovision/message.proto - -package unprovision - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required From missing"` - To github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,2,opt,name=to,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"to" valid:"required~required field To missing"` - IdentityID base.ID `protobuf:"bytes,3,opt,name=identity_i_d,json=identityID,proto3" json:"identity_i_d" valid:"required~required IdentityID missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_65434bc1915fa954, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_65434bc1915fa954, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.identities.internal.transactions.unprovision.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.identities.internal.transactions.unprovision.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/identities/internal/transactions/unprovision/message.proto", fileDescriptor_65434bc1915fa954) -} - -var fileDescriptor_65434bc1915fa954 = []byte{ - // 450 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x93, 0xcf, 0x6b, 0x13, 0x41, - 0x14, 0xc7, 0x77, 0x12, 0xf1, 0xc7, 0xd4, 0xd3, 0xaa, 0x10, 0x72, 0xd8, 0x5d, 0x16, 0x94, 0x52, - 0x64, 0x06, 0xaa, 0xa7, 0xde, 0x1a, 0xa2, 0x10, 0x24, 0x08, 0xb1, 0x1e, 0x14, 0x24, 0x6c, 0x76, - 0x5e, 0xb7, 0x0f, 0xb3, 0x33, 0xeb, 0xbc, 0x49, 0x4b, 0x11, 0x3d, 0x0b, 0x5e, 0xfc, 0x13, 0xfa, - 0x17, 0x78, 0xf7, 0xe8, 0xad, 0xc7, 0x1e, 0xc5, 0x43, 0x90, 0xe4, 0xe2, 0xb9, 0x7f, 0x81, 0x64, - 0x93, 0xba, 0x21, 0x5a, 0x10, 0xc9, 0xed, 0xed, 0xb2, 0x7c, 0xbe, 0x9f, 0xe5, 0x7d, 0x1f, 0xef, - 0x15, 0x60, 0x09, 0xc9, 0x81, 0x4e, 0xa1, 0x4f, 0xea, 0xb5, 0xcc, 0x8d, 0x1a, 0x0d, 0x81, 0x24, - 0x2a, 0xd0, 0x0e, 0x1d, 0xce, 0x46, 0xed, 0xc0, 0xea, 0x64, 0x28, 0x9d, 0x4d, 0x34, 0x25, 0xa9, - 0x43, 0xa3, 0x49, 0x8e, 0x74, 0x61, 0xcd, 0x21, 0x12, 0x1a, 0x2d, 0x73, 0x20, 0x4a, 0x32, 0x10, - 0x85, 0x35, 0xce, 0xf8, 0xed, 0x15, 0xa6, 0x58, 0x30, 0x45, 0xc5, 0x14, 0x17, 0x4c, 0xb1, 0xcc, - 0x14, 0x4b, 0xcc, 0xe6, 0xed, 0xcc, 0x64, 0xa6, 0x04, 0xca, 0xd9, 0x34, 0x67, 0x37, 0xb7, 0x56, - 0x7d, 0x29, 0x3d, 0x80, 0x3c, 0x91, 0xee, 0xb8, 0x00, 0x92, 0x83, 0x84, 0x40, 0xa2, 0x9a, 0x7f, - 0x1b, 0x7f, 0xae, 0xf3, 0x6b, 0xdd, 0xb9, 0x99, 0xff, 0x91, 0xf1, 0x2b, 0xfb, 0xd6, 0xe4, 0x0d, - 0x16, 0xb1, 0xcd, 0x1b, 0xad, 0xa3, 0xd3, 0x71, 0xe8, 0x7d, 0x1f, 0x87, 0x8f, 0x32, 0x74, 0x07, - 0xa3, 0x81, 0x48, 0x4d, 0x2e, 0x97, 0xc8, 0x4f, 0x35, 0x2c, 0x3f, 0x3e, 0x6b, 0x3f, 0xf9, 0x33, - 0x47, 0xec, 0xa6, 0xe9, 0xae, 0x52, 0x16, 0x88, 0xce, 0xc7, 0xe1, 0xbd, 0xc3, 0x64, 0x88, 0x6a, - 0x27, 0xb6, 0xf0, 0x66, 0x84, 0x16, 0xd4, 0xfb, 0x8b, 0x21, 0x7a, 0x6c, 0x4d, 0x1e, 0xe5, 0x48, - 0x84, 0x3a, 0x8b, 0x7b, 0xa5, 0xc4, 0xcc, 0xa6, 0xe6, 0x4c, 0xa3, 0x56, 0xba, 0xbc, 0x5d, 0xb7, - 0xcb, 0xd6, 0xa5, 0x2e, 0xfb, 0x08, 0x43, 0x15, 0xed, 0x99, 0xca, 0xa7, 0xe6, 0x8c, 0xff, 0x8e, - 0xdf, 0x5c, 0x6c, 0xe6, 0xb8, 0x8f, 0x7d, 0xd5, 0xa8, 0x47, 0x6c, 0x73, 0x63, 0xfb, 0xae, 0x58, - 0x5d, 0xe3, 0x3c, 0x56, 0x94, 0xb1, 0xa2, 0x8c, 0xed, 0xb4, 0x5b, 0x0f, 0x67, 0xf6, 0xe7, 0xe3, - 0xf0, 0xfe, 0xa5, 0xa1, 0x9d, 0x05, 0xbb, 0xd3, 0xae, 0x62, 0x39, 0xfe, 0x7e, 0xb9, 0x73, 0xfd, - 0xc3, 0x49, 0xe8, 0xfd, 0x3c, 0x09, 0xbd, 0xf8, 0x0e, 0xbf, 0xb5, 0x57, 0xd5, 0xa1, 0x07, 0x54, - 0x18, 0x4d, 0xb0, 0xfd, 0x95, 0xf1, 0x7a, 0x97, 0x32, 0xff, 0x0b, 0xe3, 0x1b, 0xcf, 0xab, 0x86, - 0xf8, 0x5d, 0xb1, 0x8e, 0xa2, 0x89, 0x45, 0x45, 0x9a, 0x2f, 0xd6, 0x83, 0xfb, 0xcb, 0x1f, 0xc4, - 0x5e, 0xeb, 0xe8, 0x74, 0x12, 0xb0, 0xb3, 0x49, 0xc0, 0x7e, 0x4c, 0x02, 0xf6, 0x69, 0x1a, 0x78, - 0x67, 0xd3, 0xc0, 0xfb, 0x36, 0x0d, 0xbc, 0x97, 0xaf, 0xfe, 0x79, 0xed, 0xff, 0x73, 0x9a, 0x83, - 0xab, 0xe5, 0x2d, 0x3c, 0xf8, 0x15, 0x00, 0x00, 0xff, 0xff, 0x70, 0x5b, 0x90, 0x11, 0xe9, 0x03, - 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Unprovision(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Unprovision(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.identities.internal.transactions.unprovision.Msg/Unprovision", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Unprovision(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Unprovision(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Unprovision not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Unprovision_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Unprovision(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.identities.internal.transactions.unprovision.Msg/Unprovision", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Unprovision(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.identities.internal.transactions.unprovision.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Unprovision", - Handler: _Msg_Unprovision_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/identities/internal/transactions/unprovision/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.IdentityID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.To.Size() - i -= size - if _, err := m.To.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.To.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.IdentityID.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field To", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.To.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IdentityID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IdentityID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/identities/internal/transactions/unprovision/message_test.go b/modules/identities/internal/transactions/unprovision/message_test.go index 2402a04a2..473279d4c 100644 --- a/modules/identities/internal/transactions/unprovision/message_test.go +++ b/modules/identities/internal/transactions/unprovision/message_test.go @@ -1,24 +1,32 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package unprovision import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/identities/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Unprovision_Message(t *testing.T) { - testIdentityID := base.NewID("identityID") - +func CreateTestInputForMessage(t *testing.T) (ids.IdentityID, sdkTypes.AccAddress, sdkTypes.AccAddress, sdkTypes.Msg) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testIdentityID := baseIDs.NewIdentityID(testClassificationID, immutables) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) require.Nil(t, err) @@ -28,15 +36,244 @@ func Test_Unprovision_Message(t *testing.T) { require.Nil(t, err) testMessage := newMessage(fromAccAddress, toAccAddress, testIdentityID) - require.Equal(t, Message{From: fromAccAddress, To: toAccAddress, IdentityID: testIdentityID}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) + return testIdentityID, fromAccAddress, toAccAddress, testMessage +} + +func Test_messageFromInterface(t *testing.T) { + testIdentityID, fromAccAddress, toAccAddress, testMessage := CreateTestInputForMessage(t) + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{testMessage}, message{fromAccAddress, toAccAddress, testIdentityID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + testIdentityID, fromAccAddress, toAccAddress, testMessage := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + ids.IdentityID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testIdentityID}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(testMessage))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + testIdentityID, fromAccAddress, toAccAddress, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + ids.IdentityID + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testIdentityID}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + testIdentityID, fromAccAddress, toAccAddress, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + ids.IdentityID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testIdentityID}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + testIdentityID, fromAccAddress, toAccAddress, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + ids.IdentityID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testIdentityID}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + testIdentityID, fromAccAddress, toAccAddress, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + ids.IdentityID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testIdentityID}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + testIdentityID, fromAccAddress, toAccAddress, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + To sdkTypes.AccAddress + ids.IdentityID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, toAccAddress, testIdentityID}, false}, + {"-ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_newMessage(t *testing.T) { + testIdentityID, fromAccAddress, toAccAddress, _ := CreateTestInputForMessage(t) + + type args struct { + from sdkTypes.AccAddress + to sdkTypes.AccAddress + ids.IdentityID + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, toAccAddress, testIdentityID}, message{fromAccAddress, toAccAddress, testIdentityID}}, + {"-ve", args{}, message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.to, tt.args.IdentityID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/identities/internal/transactions/unprovision/msg_server.go b/modules/identities/internal/transactions/unprovision/msg_server.go deleted file mode 100644 index c11b903c1..000000000 --- a/modules/identities/internal/transactions/unprovision/msg_server.go +++ /dev/null @@ -1,64 +0,0 @@ -package unprovision - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -var _ MsgServer = msgServer{} - -func (msgServer msgServer) Unprovision(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - identityID := message.IdentityID - identities := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(&identityID)) - - identity := identities.Get(key.FromID(&identityID)) - if identity == nil { - return nil, errors.EntityNotFound - } - - if !identity.(mappables.InterIdentity).IsProvisioned(message.From.AsSDKTypesAccAddress()) { - return nil, errors.NotAuthorized - } - - if !identity.(mappables.InterIdentity).IsProvisioned(message.To.AsSDKTypesAccAddress()) { - return nil, errors.EntityNotFound - } - - identityAuthenticationProperty := identity.(mappables.InterIdentity).GetAuthentication() - metaProperties, Error := supplement.GetMetaPropertiesFromResponse(msgServer.transactionKeeper.supplementAuxiliary.GetKeeper().Help(ctx, supplement.NewAuxiliaryRequest(identityAuthenticationProperty))) - if Error != nil { - return nil, Error - } - listData, Error := metaProperties.GetList()[0].GetMetaFact().GetData().AsListData() - if Error != nil { - return nil, Error - } - listData.Remove(base.NewAccAddressData(message.To.AsSDKTypesAccAddress())) - authenticationProperty := base.NewMetaProperty(base.NewID(properties.Authentication), base.NewMetaFact(listData)) - mutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(authenticationProperty))) - if Error != nil { - return nil, Error - } - modifiedMutableProperties := identity.(mappables.InterIdentity).GetMutableProperties().Mutate(mutableMetaProperties.GetList()...) - identities.Mutate(mappable.NewIdentity(&identityID, identity.(mappables.InterIdentity).GetImmutableProperties(), modifiedMutableProperties)) - //identities.Mutate(identity.(mappables.InterIdentity).UnprovisionAddress(message.To.AsSDKTypesAccAddress())) - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} diff --git a/modules/identities/internal/transactions/unprovision/request.go b/modules/identities/internal/transactions/unprovision/request.go index 93d889cd1..4390cad64 100644 --- a/modules/identities/internal/transactions/unprovision/request.go +++ b/modules/identities/internal/transactions/unprovision/request.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package unprovision @@ -9,15 +7,15 @@ import ( "encoding/json" "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/identities/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -28,30 +26,30 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary unprovision identity transaction -// @Descrption unprovision identity transaction +// Validate godoc +// @Summary Unprovision identity transaction +// @Description Unprovision identity transaction // @Accept text/plain // @Produce json // @Tags Identities -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body body transactionRequest true "Request body to unprovision identity" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /identities/unprovision [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.To), - cliCommand.ReadString(flags.IdentityID), + cliCommand.ReadString(constants.To), + cliCommand.ReadString(constants.IdentityID), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -60,24 +58,29 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + to, err := sdkTypes.AccAddressFromBech32(transactionRequest.To) + if err != nil { + return nil, err } - to, Error := sdkTypes.AccAddressFromBech32(transactionRequest.To) - if Error != nil { - return nil, Error + identityID, err := baseIDs.ReadIdentityID(transactionRequest.IdentityID) + if err != nil { + return nil, err } return newMessage( from, to, - base.NewID(transactionRequest.IdentityID), + identityID, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/identities/internal/transactions/unprovision/request_test.go b/modules/identities/internal/transactions/unprovision/request_test.go index 1294bac2a..da9e3e5ea 100644 --- a/modules/identities/internal/transactions/unprovision/request_test.go +++ b/modules/identities/internal/transactions/unprovision/request_test.go @@ -1,81 +1,300 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package unprovision import ( "encoding/json" - "github.com/cosmos/cosmos-sdk/client" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" - "testing" -) -func Test_Unprovision_Request(t *testing.T) { + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" +) - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.IdentityID, flags.To}) - cliContext := context.NewCLIContext().WithCodec(Codec) +func createInputForMessage(t *testing.T) (ids.IdentityID, string, types.AccAddress, types.Msg, rest.BaseReq) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testIdentityID := baseIDs.NewIdentityID(testClassificationID, immutables) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) + require.Nil(t, err) toAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - toAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) + toAccAddress, err := types.AccAddressFromBech32(toAddress) + require.Nil(t, err) - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, toAddress, "identityID") + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} - require.Equal(t, transactionRequest{BaseReq: testBaseReq, To: toAddress, IdentityID: "identityID"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) + testMessage := newMessage(fromAccAddress, toAccAddress, testIdentityID) - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, To: "", IdentityID: ""}, requestFromCLI) + return testIdentityID, toAddress, toAccAddress, testMessage, testBaseReq +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_newTransactionRequest(t *testing.T) { + testIdentityID, toAddress, _, _, testBaseReq := createInputForMessage(t) + type args struct { + baseReq rest.BaseReq + to string + identityID string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve wit nil", args{}, transactionRequest{}}, + {"+ve", args{testBaseReq, toAddress, testIdentityID.String()}, transactionRequest{testBaseReq, toAddress, testIdentityID.String()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.to, tt.args.identityID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromCLI(t *testing.T) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.To, constants.IdentityID}) + cliContext := context.NewCLIContext().WithCodec(Codec) + testIdentityID, toAddress, _, _, testBaseReq := createInputForMessage(t) + type fields struct { + BaseReq rest.BaseReq + To string + IdentityID string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, toAddress, testIdentityID.String()}, args{cliCommand, cliContext}, transactionRequest{cliCommand.ReadBaseReq(cliContext), cliCommand.ReadString(constants.To), cliCommand.ReadString(constants.IdentityID)}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, toAccAddress, base.NewID("identityID")), msg) - require.Nil(t, Error) +func Test_transactionRequest_FromJSON(t *testing.T) { + testIdentityID, toAddress, toAccAddress, _, testBaseReq := createInputForMessage(t) + type fields struct { + BaseReq rest.BaseReq + To string + IdentityID string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseReq, toAddress, testIdentityID.String()}, args{types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{types.AccAddress("cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c"), toAccAddress, testIdentityID}))}, transactionRequest{testBaseReq, toAddress, testIdentityID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, toAddress, "identityID").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + testIdentityID, toAddress, _, _, testBaseReq := createInputForMessage(t) + type fields struct { + BaseReq rest.BaseReq + To string + IdentityID string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseReq, toAddress, testIdentityID.String()}, testBaseReq}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: fromAddress, ChainID: "test"}, "randomString", "identityID").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_MakeMsg(t *testing.T) { + testIdentityID, toAddress, toAccAddress, _, testBaseReq := createInputForMessage(t) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + type fields struct { + BaseReq rest.BaseReq + To string + IdentityID string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseReq, toAddress, testIdentityID.String()}, message{fromAccAddress, toAccAddress, testIdentityID}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionRequest_RegisterCodec(t *testing.T) { + testIdentityID, toAddress, _, _, testBaseReq := createInputForMessage(t) + type fields struct { + BaseReq rest.BaseReq + To string + IdentityID string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve wit nil", fields{}, args{codec.New()}}, + {"+ve", fields{testBaseReq, toAddress, testIdentityID.String()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + testIdentityID, toAddress, _, _, testBaseReq := createInputForMessage(t) + type fields struct { + BaseReq rest.BaseReq + To string + IdentityID string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve wit nil", fields{}, true}, + {"+ve", fields{testBaseReq, toAddress, testIdentityID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + To: tt.fields.To, + IdentityID: tt.fields.IdentityID, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/identities/internal/transactions/unprovision/response.go b/modules/identities/internal/transactions/unprovision/response.go new file mode 100644 index 000000000..585cbe0ab --- /dev/null +++ b/modules/identities/internal/transactions/unprovision/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package unprovision + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/identities/internal/transactions/unprovision/transaction.go b/modules/identities/internal/transactions/unprovision/transaction.go new file mode 100644 index 000000000..a0b56042f --- /dev/null +++ b/modules/identities/internal/transactions/unprovision/transaction.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package unprovision + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "unprovision", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.To, + constants.IdentityID, +) diff --git a/modules/identities/prototype.go b/modules/identities/prototype.go new file mode 100644 index 000000000..028220ab9 --- /dev/null +++ b/modules/identities/prototype.go @@ -0,0 +1,32 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package identities + +import ( + "github.com/AssetMantle/modules/modules/identities/auxiliaries" + "github.com/AssetMantle/modules/modules/identities/internal/block" + "github.com/AssetMantle/modules/modules/identities/internal/genesis" + "github.com/AssetMantle/modules/modules/identities/internal/mapper" + "github.com/AssetMantle/modules/modules/identities/internal/module" + "github.com/AssetMantle/modules/modules/identities/internal/parameters" + "github.com/AssetMantle/modules/modules/identities/internal/queries" + "github.com/AssetMantle/modules/modules/identities/internal/simulator" + "github.com/AssetMantle/modules/modules/identities/internal/transactions" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Module { + return baseHelpers.NewModule( + module.Name, + auxiliaries.Prototype, + genesis.Prototype, + mapper.Prototype, + parameters.Prototype, + queries.Prototype, + simulator.Prototype, + transactions.Prototype, + block.Prototype, + ) +} diff --git a/modules/identities/prototype_test.go b/modules/identities/prototype_test.go new file mode 100644 index 000000000..e09ec4e4b --- /dev/null +++ b/modules/identities/prototype_test.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package identities + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries" + "github.com/AssetMantle/modules/modules/identities/internal/block" + "github.com/AssetMantle/modules/modules/identities/internal/genesis" + "github.com/AssetMantle/modules/modules/identities/internal/mapper" + "github.com/AssetMantle/modules/modules/identities/internal/module" + "github.com/AssetMantle/modules/modules/identities/internal/parameters" + "github.com/AssetMantle/modules/modules/identities/internal/queries" + "github.com/AssetMantle/modules/modules/identities/internal/simulator" + "github.com/AssetMantle/modules/modules/identities/internal/transactions" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Name(), baseHelpers.NewModule( + module.Name, + auxiliaries.Prototype, + genesis.Prototype, + mapper.Prototype, + parameters.Prototype, + queries.Prototype, + simulator.Prototype, + transactions.Prototype, + block.Prototype, + ).Name()) +} diff --git a/modules/maintainers/auxiliaries/deputize/auxiliary.go b/modules/maintainers/auxiliaries/deputize/auxiliary.go new file mode 100644 index 000000000..d120bab55 --- /dev/null +++ b/modules/maintainers/auxiliaries/deputize/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "deputize", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "deputize", + keeperPrototypeMock, +) diff --git a/modules/maintainers/auxiliaries/deputize/keeper.go b/modules/maintainers/auxiliaries/deputize/keeper.go new file mode 100644 index 000000000..b557a3896 --- /dev/null +++ b/modules/maintainers/auxiliaries/deputize/keeper.go @@ -0,0 +1,117 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/member" + "github.com/AssetMantle/modules/modules/maintainers/internal/key" + "github.com/AssetMantle/modules/modules/maintainers/internal/mappable" + "github.com/AssetMantle/modules/modules/maintainers/internal/utilities" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/ids/constansts" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + constantProperties "github.com/AssetMantle/modules/schema/properties/constants" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper + memberAuxiliary helpers.Auxiliary +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + + fromMaintainerID := baseIDs.NewMaintainerID(constansts.MaintainerClassificationID, + baseQualified.NewImmutables(baseLists.NewPropertyList( + baseProperties.NewMetaProperty(constantProperties.MaintainedClassificationIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.MaintainedClassificationID)), + baseProperties.NewMetaProperty(constantProperties.IdentityIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.FromID)), + ))) + + maintainers := auxiliaryKeeper.mapper.NewCollection(context) + + Mappable := maintainers.Fetch(key.NewKey(fromMaintainerID)).Get(key.NewKey(fromMaintainerID)) + if Mappable == nil { + return newAuxiliaryResponse(constants.EntityNotFound) + } + fromMaintainer := Mappable.(documents.Maintainer) + + // TODO test + if !(fromMaintainer.CanAddMaintainer() || !auxiliaryRequest.CanAddMaintainer && fromMaintainer.CanMutateMaintainer() || !auxiliaryRequest.CanMutateMaintainer && fromMaintainer.CanRemoveMaintainer() || !auxiliaryRequest.CanRemoveMaintainer) { + return newAuxiliaryResponse(constants.NotAuthorized) + } + + // Checking if the fromMaintainer has access to maintain the requested properties + // ADD calculating the properties that the fromMaintainer is trying to REMOVE for existing maintainer + removeMaintainedPropertyList := fromMaintainer.GetMutables().GetMutablePropertyList() + + // TODO test + for _, maintainedProperty := range auxiliaryRequest.MaintainedProperties.GetList() { + if !fromMaintainer.MaintainsProperty(maintainedProperty.GetID()) { + return newAuxiliaryResponse(constants.NotAuthorized) + } + removeMaintainedPropertyList = removeMaintainedPropertyList.Remove(maintainedProperty) + } + + if auxiliaryResponse := auxiliaryKeeper.memberAuxiliary.GetKeeper().Help(context, member.NewAuxiliaryRequest(auxiliaryRequest.MaintainedClassificationID, nil, baseQualified.NewMutables(auxiliaryRequest.MaintainedProperties))); !auxiliaryResponse.IsSuccessful() { + return newAuxiliaryResponse(auxiliaryResponse.GetError()) + } + + toMaintainerID := baseIDs.NewMaintainerID(constansts.MaintainerClassificationID, + baseQualified.NewImmutables(baseLists.NewPropertyList( + baseProperties.NewMetaProperty(constantProperties.MaintainedClassificationIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.MaintainedClassificationID)), + baseProperties.NewMetaProperty(constantProperties.IdentityIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.ToID)), + ))) + + if Mappable = maintainers.Fetch(key.NewKey(toMaintainerID)).Get(key.NewKey(toMaintainerID)); Mappable == nil { + if !fromMaintainer.CanAddMaintainer() { + return newAuxiliaryResponse(constants.NotAuthorized) + } + + maintainers.Add(mappable.NewMappable(base.NewMaintainer(auxiliaryRequest.ToID, auxiliaryRequest.MaintainedClassificationID, auxiliaryRequest.MaintainedProperties.GetPropertyIDList(), utilities.SetPermissions(auxiliaryRequest.CanMintAsset, auxiliaryRequest.CanBurnAsset, auxiliaryRequest.CanRenumerateAsset, auxiliaryRequest.CanAddMaintainer, auxiliaryRequest.CanRemoveMaintainer, auxiliaryRequest.CanMutateMaintainer)))) + } else { + if !fromMaintainer.CanMutateMaintainer() { + return newAuxiliaryResponse(constants.NotAuthorized) + } + + maintainedProperties := Mappable.(documents.Maintainer).GetMutables().GetMutablePropertyList().Add(auxiliaryRequest.MaintainedProperties.GetList()...).Remove(removeMaintainedPropertyList.GetList()...) + maintainers.Mutate(mappable.NewMappable(base.NewMaintainer(auxiliaryRequest.ToID, auxiliaryRequest.MaintainedClassificationID, maintainedProperties.GetPropertyIDList(), utilities.SetPermissions(auxiliaryRequest.CanMintAsset, auxiliaryRequest.CanBurnAsset, auxiliaryRequest.CanRenumerateAsset, auxiliaryRequest.CanAddMaintainer, auxiliaryRequest.CanRemoveMaintainer, auxiliaryRequest.CanMutateMaintainer)))) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeper auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + auxiliaryKeeper.mapper = mapper + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case member.Auxiliary.GetName(): + auxiliaryKeeper.memberAuxiliary = value + default: + break + } + default: + panic(constants.UninitializedUsage) + } + } + + return auxiliaryKeeper +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/maintainers/auxiliaries/deputize/keeper_mock.go b/modules/maintainers/auxiliaries/deputize/keeper_mock.go new file mode 100644 index 000000000..622e24299 --- /dev/null +++ b/modules/maintainers/auxiliaries/deputize/keeper_mock.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/data/constants" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeperMock)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(_ sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + if auxiliaryRequest.MaintainedProperties.GetProperty(baseIDs.NewPropertyID(baseIDs.NewStringID("deputizeError"), constants.IDDataID)) != nil { + return newAuxiliaryResponse(errorConstants.MockError) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/maintainers/auxiliaries/deputize/keeper_test.go b/modules/maintainers/auxiliaries/deputize/keeper_test.go index 514aaba13..32cf5c4b8 100644 --- a/modules/maintainers/auxiliaries/deputize/keeper_test.go +++ b/modules/maintainers/auxiliaries/deputize/keeper_test.go @@ -5,6 +5,19 @@ package deputize import ( "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/member" "github.com/AssetMantle/modules/modules/maintainers/internal/key" "github.com/AssetMantle/modules/modules/maintainers/internal/mappable" @@ -20,17 +33,6 @@ import ( "github.com/AssetMantle/modules/schema/lists/utilities" baseProperties "github.com/AssetMantle/modules/schema/properties/base" baseQualified "github.com/AssetMantle/modules/schema/qualified/base" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/stretchr/testify/require" - abciTypes "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" ) type TestKeepers struct { diff --git a/modules/maintainers/auxiliaries/deputize/request.go b/modules/maintainers/auxiliaries/deputize/request.go new file mode 100644 index 000000000..f5020e91d --- /dev/null +++ b/modules/maintainers/auxiliaries/deputize/request.go @@ -0,0 +1,56 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + "github.com/asaskevich/govalidator" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" +) + +type auxiliaryRequest struct { + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ToID ids.IdentityID `json:"toID" valid:"required~required field toID missing"` + MaintainedClassificationID ids.ClassificationID `json:"maintainedClassificationID" valid:"required~required field maintainedClassificationID missing"` + MaintainedProperties lists.PropertyList `json:"maintainedProperties" valid:"required~required field maintainedProperties missing"` + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` +} + +var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) + +func (auxiliaryRequest auxiliaryRequest) Validate() error { + _, err := govalidator.ValidateStruct(auxiliaryRequest) + return err +} + +func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { + switch value := request.(type) { + case auxiliaryRequest: + return value + default: + return auxiliaryRequest{} + } +} + +func NewAuxiliaryRequest(fromID ids.IdentityID, toID ids.IdentityID, maintainedClassificationID ids.ClassificationID, maintainedProperties lists.PropertyList, canMintAsset bool, canBurnAsset bool, canRenumerateAsset bool, canAddMaintainer bool, canRemoveMaintainer bool, canMutateMaintainer bool) helpers.AuxiliaryRequest { + return auxiliaryRequest{ + FromID: fromID, + ToID: toID, + MaintainedClassificationID: maintainedClassificationID, + MaintainedProperties: maintainedProperties, + CanMintAsset: canMintAsset, + CanBurnAsset: canBurnAsset, + CanRenumerateAsset: canRenumerateAsset, + CanAddMaintainer: canAddMaintainer, + CanRemoveMaintainer: canRemoveMaintainer, + CanMutateMaintainer: canMutateMaintainer, + } +} diff --git a/modules/maintainers/auxiliaries/deputize/request_test.go b/modules/maintainers/auxiliaries/deputize/request_test.go index 8e67503a6..c608c78e0 100644 --- a/modules/maintainers/auxiliaries/deputize/request_test.go +++ b/modules/maintainers/auxiliaries/deputize/request_test.go @@ -1,28 +1,104 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( + "reflect" "testing" - "github.com/stretchr/testify/require" - - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" ) -func Test_Deputize_Request(t *testing.T) { - classificationID := base.NewID("classificationID") - identityID := base.NewID("identityID") - maintainedProperties := base.NewProperties(base.NewProperty(base.NewID("ID1"), base.NewStringData("Data1"))) - - testAuxiliaryRequest := NewAuxiliaryRequest(identityID, identityID, classificationID, maintainedProperties, false, false, false) +func TestNewAuxiliaryRequest(t *testing.T) { + type args struct { + fromID ids.IdentityID + toID ids.IdentityID + maintainedClassificationID ids.ClassificationID + maintainedProperties lists.PropertyList + canMintAsset bool + canBurnAsset bool + canRenumerateAsset bool + canAddMaintainer bool + canRemoveMaintainer bool + canMutateMaintainer bool + } + tests := []struct { + name string + args args + want helpers.AuxiliaryRequest + }{ + {"+ve", args{testFromID, testFromID, testClassificationID, maintainedProperties, true, true, true, true, true, true}, auxiliaryRequest{testFromID, testFromID, testClassificationID, maintainedProperties, true, true, true, true, true, true}}, + {"+ve with nil", args{}, auxiliaryRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewAuxiliaryRequest(tt.args.fromID, tt.args.toID, tt.args.maintainedClassificationID, tt.args.maintainedProperties, tt.args.canMintAsset, tt.args.canBurnAsset, tt.args.canRenumerateAsset, tt.args.canAddMaintainer, tt.args.canRemoveMaintainer, tt.args.canMutateMaintainer); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewAuxiliaryRequest() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testAuxiliaryRequest, auxiliaryRequest{FromID: identityID, ToID: identityID, ClassificationID: classificationID, MaintainedProperties: maintainedProperties}) - require.Equal(t, nil, testAuxiliaryRequest.Validate()) - require.Equal(t, testAuxiliaryRequest, auxiliaryRequestFromInterface(testAuxiliaryRequest)) - require.Equal(t, auxiliaryRequest{}, auxiliaryRequestFromInterface(nil)) +func Test_auxiliaryRequestFromInterface(t *testing.T) { + type args struct { + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + args args + want auxiliaryRequest + }{ + {"+ve", args{NewAuxiliaryRequest(testFromID, testFromID, testClassificationID, maintainedProperties, true, true, true, true, true, true)}, auxiliaryRequest{testFromID, testFromID, testClassificationID, maintainedProperties, true, true, true, true, true, true}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := auxiliaryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("auxiliaryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_auxiliaryRequest_Validate(t *testing.T) { + type fields struct { + FromID ids.IdentityID + ToID ids.IdentityID + MaintainedClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testFromID, testFromID, testClassificationID, maintainedProperties, true, true, true, true, true, true}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryRequest := auxiliaryRequest{ + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + MaintainedClassificationID: tt.fields.MaintainedClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if err := auxiliaryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/maintainers/auxiliaries/deputize/response.go b/modules/maintainers/auxiliaries/deputize/response.go new file mode 100644 index 000000000..e3690244d --- /dev/null +++ b/modules/maintainers/auxiliaries/deputize/response.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import "github.com/AssetMantle/modules/schema/helpers" + +type auxiliaryResponse struct { + Success bool `json:"success"` + Error error `json:"error"` +} + +var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) + +func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { + return auxiliaryResponse.Success +} +func (auxiliaryResponse auxiliaryResponse) GetError() error { + return auxiliaryResponse.Error +} +func newAuxiliaryResponse(error error) helpers.AuxiliaryResponse { + success := true + if error != nil { + success = false + } + + return auxiliaryResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/maintainers/auxiliaries/deputize/response_test.go b/modules/maintainers/auxiliaries/deputize/response_test.go new file mode 100644 index 000000000..38074e9c4 --- /dev/null +++ b/modules/maintainers/auxiliaries/deputize/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Deputize_Response(t *testing.T) { + testAuxiliaryResponse := newAuxiliaryResponse(nil) + require.Equal(t, auxiliaryResponse{Success: true, Error: nil}, testAuxiliaryResponse) + require.Equal(t, true, testAuxiliaryResponse.IsSuccessful()) + require.Equal(t, nil, testAuxiliaryResponse.GetError()) + + testAuxiliaryResponse2 := newAuxiliaryResponse(constants.IncorrectFormat) + require.Equal(t, auxiliaryResponse{Success: false, Error: constants.IncorrectFormat}, testAuxiliaryResponse2) + require.Equal(t, false, testAuxiliaryResponse2.IsSuccessful()) + require.Equal(t, constants.IncorrectFormat, testAuxiliaryResponse2.GetError()) +} diff --git a/modules/maintainers/auxiliaries/maintain/auxiliary.go b/modules/maintainers/auxiliaries/maintain/auxiliary.go new file mode 100644 index 000000000..6bed4e2ea --- /dev/null +++ b/modules/maintainers/auxiliaries/maintain/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package maintain + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "maintain", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "maintain", + keeperPrototypeMock, +) diff --git a/modules/maintainers/auxiliaries/maintain/keeper.go b/modules/maintainers/auxiliaries/maintain/keeper.go new file mode 100644 index 000000000..2a057e564 --- /dev/null +++ b/modules/maintainers/auxiliaries/maintain/keeper.go @@ -0,0 +1,59 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package maintain + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/maintainers/internal/key" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/ids/constansts" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + constantProperties "github.com/AssetMantle/modules/schema/properties/constants" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + + maintainerID := baseIDs.NewMaintainerID(constansts.MaintainerClassificationID, + baseQualified.NewImmutables(baseLists.NewPropertyList( + baseProperties.NewMetaProperty(constantProperties.MaintainedClassificationIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.MaintainedClassificationID)), + baseProperties.NewMetaProperty(constantProperties.IdentityIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.IdentityID)), + ))) + + maintainers := auxiliaryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(maintainerID)) + + maintainer := maintainers.Get(key.NewKey(maintainerID)) + if maintainer == nil { + return newAuxiliaryResponse(constants.EntityNotFound) + } + + for _, maintainedProperty := range auxiliaryRequest.MaintainedMutables.GetMutablePropertyList().GetList() { + if !maintainer.(documents.Maintainer).MaintainsProperty(maintainedProperty.GetID()) { + return newAuxiliaryResponse(constants.NotAuthorized) + } + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeper{mapper: mapper} +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/maintainers/auxiliaries/maintain/keeper_mock.go b/modules/maintainers/auxiliaries/maintain/keeper_mock.go new file mode 100644 index 000000000..34d0d1150 --- /dev/null +++ b/modules/maintainers/auxiliaries/maintain/keeper_mock.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package maintain + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeperMock)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(_ sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + if auxiliaryRequest.IdentityID.String() == "maintainError" { + return newAuxiliaryResponse(constants.MockError) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/maintainers/auxiliaries/maintain/keeper_test.go b/modules/maintainers/auxiliaries/maintain/keeper_test.go index 3311ded2d..6951db0b8 100644 --- a/modules/maintainers/auxiliaries/maintain/keeper_test.go +++ b/modules/maintainers/auxiliaries/maintain/keeper_test.go @@ -5,6 +5,19 @@ package maintain import ( "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + "github.com/AssetMantle/modules/modules/maintainers/internal/key" "github.com/AssetMantle/modules/modules/maintainers/internal/mappable" "github.com/AssetMantle/modules/modules/maintainers/internal/parameters" @@ -19,17 +32,6 @@ import ( "github.com/AssetMantle/modules/schema/lists/base" baseProperties "github.com/AssetMantle/modules/schema/properties/base" baseQualified "github.com/AssetMantle/modules/schema/qualified/base" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/stretchr/testify/require" - abciTypes "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" ) type TestKeepers struct { diff --git a/modules/maintainers/auxiliaries/maintain/request.go b/modules/maintainers/auxiliaries/maintain/request.go new file mode 100644 index 000000000..85956f4ef --- /dev/null +++ b/modules/maintainers/auxiliaries/maintain/request.go @@ -0,0 +1,42 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package maintain + +import ( + "github.com/asaskevich/govalidator" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/qualified" +) + +type auxiliaryRequest struct { + MaintainedClassificationID ids.ClassificationID `json:"maintainedClassificationID" valid:"required~required field maintainedClassificationID missing"` + ids.IdentityID `json:"identityID" valid:"required~required field identityID missing"` + MaintainedMutables qualified.Mutables `json:"maintainedMutables" valid:"required~required field maintainedProperties missing"` +} + +var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) + +func (auxiliaryRequest auxiliaryRequest) Validate() error { + _, err := govalidator.ValidateStruct(auxiliaryRequest) + return err +} + +func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { + switch value := request.(type) { + case auxiliaryRequest: + return value + default: + return auxiliaryRequest{} + } +} + +func NewAuxiliaryRequest(maintainedClassificationID ids.ClassificationID, identityID ids.IdentityID, maintainedMutables qualified.Mutables) helpers.AuxiliaryRequest { + return auxiliaryRequest{ + MaintainedClassificationID: maintainedClassificationID, + IdentityID: identityID, + MaintainedMutables: maintainedMutables, + } +} diff --git a/modules/maintainers/auxiliaries/maintain/request_test.go b/modules/maintainers/auxiliaries/maintain/request_test.go index 2ad29f61b..3bc5c2323 100644 --- a/modules/maintainers/auxiliaries/maintain/request_test.go +++ b/modules/maintainers/auxiliaries/maintain/request_test.go @@ -1,28 +1,84 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package maintain import ( + "reflect" "testing" - "github.com/stretchr/testify/require" - - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/qualified" ) -func Test_Maintain_Request(t *testing.T) { - classificationID := base.NewID("classificationID") - identityID := base.NewID("identityID") - mutableProperties := base.NewProperties(base.NewProperty(base.NewID("ID1"), base.NewStringData("Data1"))) - - testAuxiliaryRequest := NewAuxiliaryRequest(classificationID, identityID, mutableProperties) +func TestNewAuxiliaryRequest(t *testing.T) { + type args struct { + maintainedClassificationID ids.ClassificationID + identityID ids.IdentityID + maintainedMutables qualified.Mutables + } + tests := []struct { + name string + args args + want helpers.AuxiliaryRequest + }{ + {"+ve with nil", args{}, auxiliaryRequest{}}, + {"+ve", args{testClassificationID, testFromID, mutables}, auxiliaryRequest{testClassificationID, testFromID, mutables}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewAuxiliaryRequest(tt.args.maintainedClassificationID, tt.args.identityID, tt.args.maintainedMutables); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewAuxiliaryRequest() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, auxiliaryRequest{ClassificationID: classificationID, IdentityID: identityID, MaintainedProperties: mutableProperties}, testAuxiliaryRequest) - require.Equal(t, nil, testAuxiliaryRequest.Validate()) - require.Equal(t, testAuxiliaryRequest, auxiliaryRequestFromInterface(testAuxiliaryRequest)) - require.Equal(t, auxiliaryRequest{}, auxiliaryRequestFromInterface(nil)) +func Test_auxiliaryRequestFromInterface(t *testing.T) { + type args struct { + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + args args + want auxiliaryRequest + }{ + {"+ve", args{NewAuxiliaryRequest(testClassificationID, testFromID, mutables)}, auxiliaryRequest{testClassificationID, testFromID, mutables}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := auxiliaryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("auxiliaryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_auxiliaryRequest_Validate(t *testing.T) { + type fields struct { + MaintainedClassificationID ids.ClassificationID + IdentityID ids.IdentityID + MaintainedMutables qualified.Mutables + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve with nil", fields{}, false}, + {"+ve", fields{testClassificationID, testFromID, mutables}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryRequest := auxiliaryRequest{ + MaintainedClassificationID: tt.fields.MaintainedClassificationID, + IdentityID: tt.fields.IdentityID, + MaintainedMutables: tt.fields.MaintainedMutables, + } + if err := auxiliaryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/maintainers/auxiliaries/maintain/response.go b/modules/maintainers/auxiliaries/maintain/response.go new file mode 100644 index 000000000..827b429b0 --- /dev/null +++ b/modules/maintainers/auxiliaries/maintain/response.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package maintain + +import "github.com/AssetMantle/modules/schema/helpers" + +type auxiliaryResponse struct { + Success bool `json:"success"` + Error error `json:"error"` +} + +var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) + +func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { + return auxiliaryResponse.Success +} +func (auxiliaryResponse auxiliaryResponse) GetError() error { + return auxiliaryResponse.Error +} +func newAuxiliaryResponse(error error) helpers.AuxiliaryResponse { + success := true + if error != nil { + success = false + } + + return auxiliaryResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/maintainers/auxiliaries/maintain/response_test.go b/modules/maintainers/auxiliaries/maintain/response_test.go new file mode 100644 index 000000000..c93dbff23 --- /dev/null +++ b/modules/maintainers/auxiliaries/maintain/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package maintain + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Maintain_Response(t *testing.T) { + testAuxiliaryResponse := newAuxiliaryResponse(nil) + require.Equal(t, auxiliaryResponse{Success: true, Error: nil}, testAuxiliaryResponse) + require.Equal(t, true, testAuxiliaryResponse.IsSuccessful()) + require.Equal(t, nil, testAuxiliaryResponse.GetError()) + + testAuxiliaryResponse2 := newAuxiliaryResponse(constants.IncorrectFormat) + require.Equal(t, auxiliaryResponse{Success: false, Error: constants.IncorrectFormat}, testAuxiliaryResponse2) + require.Equal(t, false, testAuxiliaryResponse2.IsSuccessful()) + require.Equal(t, constants.IncorrectFormat, testAuxiliaryResponse2.GetError()) +} diff --git a/modules/maintainers/auxiliaries/prototype.go b/modules/maintainers/auxiliaries/prototype.go new file mode 100644 index 000000000..c6d46a179 --- /dev/null +++ b/modules/maintainers/auxiliaries/prototype.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/deputize" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/maintain" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/revoke" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/super" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/verify" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Auxiliaries { + return baseHelpers.NewAuxiliaries( + deputize.Auxiliary, + maintain.Auxiliary, + revoke.Auxiliary, + super.Auxiliary, + verify.Auxiliary, + ) +} diff --git a/modules/maintainers/auxiliaries/prototype_test.go b/modules/maintainers/auxiliaries/prototype_test.go new file mode 100644 index 000000000..cd4d88b5a --- /dev/null +++ b/modules/maintainers/auxiliaries/prototype_test.go @@ -0,0 +1,27 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/deputize" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/maintain" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/revoke" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/super" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/verify" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Get("super").GetName(), baseHelpers.NewAuxiliaries( + deputize.Auxiliary, + maintain.Auxiliary, + revoke.Auxiliary, + super.Auxiliary, + verify.Auxiliary, + ).Get("super").GetName()) +} diff --git a/modules/maintainers/auxiliaries/revoke/auxiliary.go b/modules/maintainers/auxiliaries/revoke/auxiliary.go new file mode 100644 index 000000000..5e54ee0a6 --- /dev/null +++ b/modules/maintainers/auxiliaries/revoke/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "revoke", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "revoke", + keeperPrototypeMock, +) diff --git a/modules/maintainers/auxiliaries/revoke/keeper.go b/modules/maintainers/auxiliaries/revoke/keeper.go new file mode 100644 index 000000000..b3669da32 --- /dev/null +++ b/modules/maintainers/auxiliaries/revoke/keeper.go @@ -0,0 +1,65 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/maintainers/internal/key" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/ids/constansts" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + constantProperties "github.com/AssetMantle/modules/schema/properties/constants" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + maintainers := auxiliaryKeeper.mapper.NewCollection(context) + + fromMaintainerID := baseIDs.NewMaintainerID(constansts.MaintainerClassificationID, + baseQualified.NewImmutables(baseLists.NewPropertyList( + baseProperties.NewMetaProperty(constantProperties.MaintainedClassificationIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.MaintainedClassificationID)), + baseProperties.NewMetaProperty(constantProperties.IdentityIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.FromID)), + ))) + + if Mappable := maintainers.Fetch(key.NewKey(fromMaintainerID)).Get(key.NewKey(fromMaintainerID)); Mappable == nil { + return newAuxiliaryResponse(errorConstants.EntityNotFound) + } else if !Mappable.(documents.Maintainer).CanRemoveMaintainer() { + return newAuxiliaryResponse(errorConstants.NotAuthorized) + } + + toMaintainerID := baseIDs.NewMaintainerID(constansts.MaintainerClassificationID, + baseQualified.NewImmutables(baseLists.NewPropertyList( + baseProperties.NewMetaProperty(constantProperties.MaintainedClassificationIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.MaintainedClassificationID)), + baseProperties.NewMetaProperty(constantProperties.IdentityIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.ToID)), + ))) + + if Mappable := maintainers.Fetch(key.NewKey(toMaintainerID)).Get(key.NewKey(toMaintainerID)); Mappable == nil { + return newAuxiliaryResponse(errorConstants.EntityNotFound) + } else { + maintainers.Remove(Mappable) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeper{mapper: mapper} +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/maintainers/auxiliaries/revoke/keeper_mock.go b/modules/maintainers/auxiliaries/revoke/keeper_mock.go new file mode 100644 index 000000000..fc0dc5e7d --- /dev/null +++ b/modules/maintainers/auxiliaries/revoke/keeper_mock.go @@ -0,0 +1,32 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeperMock)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(_ sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + if auxiliaryRequest.MaintainedClassificationID.String() == "revokeError" { + return newAuxiliaryResponse(constants.MockError) + } + + return newAuxiliaryResponse(nil) +} +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/maintainers/auxiliaries/revoke/keeper_test.go b/modules/maintainers/auxiliaries/revoke/keeper_test.go index 3d36b86fb..dcce451c9 100644 --- a/modules/maintainers/auxiliaries/revoke/keeper_test.go +++ b/modules/maintainers/auxiliaries/revoke/keeper_test.go @@ -5,6 +5,19 @@ package revoke import ( "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + "github.com/AssetMantle/modules/modules/maintainers/internal/key" "github.com/AssetMantle/modules/modules/maintainers/internal/mappable" "github.com/AssetMantle/modules/modules/maintainers/internal/parameters" @@ -20,17 +33,6 @@ import ( "github.com/AssetMantle/modules/schema/lists/utilities" baseProperties "github.com/AssetMantle/modules/schema/properties/base" baseQualified "github.com/AssetMantle/modules/schema/qualified/base" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/stretchr/testify/require" - abciTypes "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" ) type TestKeepers struct { diff --git a/modules/maintainers/auxiliaries/revoke/request.go b/modules/maintainers/auxiliaries/revoke/request.go new file mode 100644 index 000000000..81ce7ff87 --- /dev/null +++ b/modules/maintainers/auxiliaries/revoke/request.go @@ -0,0 +1,40 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + "github.com/asaskevich/govalidator" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" +) + +type auxiliaryRequest struct { + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ToID ids.IdentityID `json:"toID" valid:"required~required field toID missing"` + MaintainedClassificationID ids.ClassificationID `json:"maintainedClassificationID" valid:"required~required field maintainedClassificationID missing"` +} + +var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) + +func (auxiliaryRequest auxiliaryRequest) Validate() error { + _, err := govalidator.ValidateStruct(auxiliaryRequest) + return err +} +func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { + switch value := request.(type) { + case auxiliaryRequest: + return value + default: + return auxiliaryRequest{} + } +} + +func NewAuxiliaryRequest(fromID ids.IdentityID, toID ids.IdentityID, maintainedClassificationID ids.ClassificationID) helpers.AuxiliaryRequest { + return auxiliaryRequest{ + FromID: fromID, + ToID: toID, + MaintainedClassificationID: maintainedClassificationID, + } +} diff --git a/modules/maintainers/auxiliaries/revoke/request_test.go b/modules/maintainers/auxiliaries/revoke/request_test.go index d04e28d29..e65073146 100644 --- a/modules/maintainers/auxiliaries/revoke/request_test.go +++ b/modules/maintainers/auxiliaries/revoke/request_test.go @@ -4,10 +4,11 @@ package revoke import ( - "github.com/AssetMantle/modules/schema/helpers" - "github.com/AssetMantle/modules/schema/ids" "reflect" "testing" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" ) func TestNewAuxiliaryRequest(t *testing.T) { diff --git a/modules/maintainers/auxiliaries/revoke/response.go b/modules/maintainers/auxiliaries/revoke/response.go new file mode 100644 index 000000000..8b6c2cdd0 --- /dev/null +++ b/modules/maintainers/auxiliaries/revoke/response.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import "github.com/AssetMantle/modules/schema/helpers" + +type auxiliaryResponse struct { + Success bool `json:"success"` + Error error `json:"error"` +} + +var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) + +func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { + return auxiliaryResponse.Success +} +func (auxiliaryResponse auxiliaryResponse) GetError() error { + return auxiliaryResponse.Error +} +func newAuxiliaryResponse(error error) helpers.AuxiliaryResponse { + success := true + if error != nil { + success = false + } + + return auxiliaryResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/maintainers/auxiliaries/revoke/response_test.go b/modules/maintainers/auxiliaries/revoke/response_test.go new file mode 100644 index 000000000..d90bc2564 --- /dev/null +++ b/modules/maintainers/auxiliaries/revoke/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Revoke_Response(t *testing.T) { + testAuxiliaryResponse := newAuxiliaryResponse(nil) + require.Equal(t, auxiliaryResponse{Success: true, Error: nil}, testAuxiliaryResponse) + require.Equal(t, true, testAuxiliaryResponse.IsSuccessful()) + require.Equal(t, nil, testAuxiliaryResponse.GetError()) + + testAuxiliaryResponse2 := newAuxiliaryResponse(constants.IncorrectFormat) + require.Equal(t, auxiliaryResponse{Success: false, Error: constants.IncorrectFormat}, testAuxiliaryResponse2) + require.Equal(t, false, testAuxiliaryResponse2.IsSuccessful()) + require.Equal(t, constants.IncorrectFormat, testAuxiliaryResponse2.GetError()) +} diff --git a/modules/maintainers/auxiliaries/super/auxiliary.go b/modules/maintainers/auxiliaries/super/auxiliary.go new file mode 100644 index 000000000..f01ff210a --- /dev/null +++ b/modules/maintainers/auxiliaries/super/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package super + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "super", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "super", + keeperPrototypeMock, +) diff --git a/modules/maintainers/auxiliaries/super/keeper.go b/modules/maintainers/auxiliaries/super/keeper.go new file mode 100644 index 000000000..9f96ae490 --- /dev/null +++ b/modules/maintainers/auxiliaries/super/keeper.go @@ -0,0 +1,54 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package super + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/maintainers/internal/key" + "github.com/AssetMantle/modules/modules/maintainers/internal/mappable" + "github.com/AssetMantle/modules/modules/maintainers/internal/utilities" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/ids/constansts" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + constantProperties "github.com/AssetMantle/modules/schema/properties/constants" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + maintainerID := baseIDs.NewMaintainerID(constansts.MaintainerClassificationID, + baseQualified.NewImmutables(baseLists.NewPropertyList( + baseProperties.NewMetaProperty(constantProperties.MaintainedClassificationIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.MaintainedClassificationID)), + baseProperties.NewMetaProperty(constantProperties.IdentityIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.ToIdentityID)), + ))) + + maintainers := auxiliaryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(maintainerID)) + if maintainers.Get(key.NewKey(maintainerID)) != nil { + return newAuxiliaryResponse(constants.EntityAlreadyExists) + } + + maintainers.Add(mappable.NewMappable(base.NewMaintainer(auxiliaryRequest.ToIdentityID, auxiliaryRequest.MaintainedClassificationID, auxiliaryRequest.MaintainedMutables.GetMutablePropertyList().GetPropertyIDList(), utilities.SetPermissions(true, true, true, true, true, true)))) + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeper{mapper: mapper} +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/maintainers/auxiliaries/super/keeper_mock.go b/modules/maintainers/auxiliaries/super/keeper_mock.go new file mode 100644 index 000000000..ba1953b3e --- /dev/null +++ b/modules/maintainers/auxiliaries/super/keeper_mock.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package super + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/data/constants" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeperMock)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(_ sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + if auxiliaryRequest.MaintainedMutables.GetMutablePropertyList().GetProperty(baseIDs.NewPropertyID(baseIDs.NewStringID("superError"), constants.IDDataID)) != nil { + return newAuxiliaryResponse(errorConstants.MockError) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/maintainers/auxiliaries/super/keeper_test.go b/modules/maintainers/auxiliaries/super/keeper_test.go index ce8289242..04ae4effc 100644 --- a/modules/maintainers/auxiliaries/super/keeper_test.go +++ b/modules/maintainers/auxiliaries/super/keeper_test.go @@ -5,6 +5,19 @@ package super import ( "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + "github.com/AssetMantle/modules/modules/maintainers/internal/key" "github.com/AssetMantle/modules/modules/maintainers/internal/mappable" "github.com/AssetMantle/modules/modules/maintainers/internal/parameters" @@ -17,17 +30,6 @@ import ( "github.com/AssetMantle/modules/schema/lists/base" baseProperties "github.com/AssetMantle/modules/schema/properties/base" baseQualified "github.com/AssetMantle/modules/schema/qualified/base" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/stretchr/testify/require" - abciTypes "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" ) type TestKeepers struct { diff --git a/modules/maintainers/auxiliaries/super/request.go b/modules/maintainers/auxiliaries/super/request.go new file mode 100644 index 000000000..37fe2e820 --- /dev/null +++ b/modules/maintainers/auxiliaries/super/request.go @@ -0,0 +1,42 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package super + +import ( + "github.com/asaskevich/govalidator" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/qualified" +) + +type auxiliaryRequest struct { + MaintainedClassificationID ids.ClassificationID `json:"maintainedClassificationID" valid:"required~required field maintainedClassificationID missing"` + ToIdentityID ids.IdentityID `json:"toIdentityID" valid:"required~required field identityID missing"` + MaintainedMutables qualified.Mutables `json:"maintainedMutables" valid:"required~required field maintainedMutables missing"` +} + +var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) + +func (auxiliaryRequest auxiliaryRequest) Validate() error { + _, err := govalidator.ValidateStruct(auxiliaryRequest) + return err +} + +func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { + switch value := request.(type) { + case auxiliaryRequest: + return value + default: + return auxiliaryRequest{} + } +} + +func NewAuxiliaryRequest(maintainedClassificationID ids.ClassificationID, toIdentityID ids.IdentityID, maintainedMutables qualified.Mutables) helpers.AuxiliaryRequest { + return auxiliaryRequest{ + MaintainedClassificationID: maintainedClassificationID, + ToIdentityID: toIdentityID, + MaintainedMutables: maintainedMutables, + } +} diff --git a/modules/maintainers/auxiliaries/super/request_test.go b/modules/maintainers/auxiliaries/super/request_test.go index 93320de6d..7b896123f 100644 --- a/modules/maintainers/auxiliaries/super/request_test.go +++ b/modules/maintainers/auxiliaries/super/request_test.go @@ -1,28 +1,83 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package super import ( + "reflect" "testing" - "github.com/stretchr/testify/require" - - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/qualified" ) -func Test_Super_Request(t *testing.T) { - classificationID := base.NewID("classificationID") - identityID := base.NewID("identityID") - mutableProperties := base.NewProperties(base.NewProperty(base.NewID("ID1"), base.NewStringData("Data1"))) - - testAuxiliaryRequest := NewAuxiliaryRequest(classificationID, identityID, mutableProperties) +func TestNewAuxiliaryRequest(t *testing.T) { + type args struct { + maintainedClassificationID ids.ClassificationID + toIdentityID ids.IdentityID + maintainedMutables qualified.Mutables + } + tests := []struct { + name string + args args + want helpers.AuxiliaryRequest + }{ + {"+ve", args{testClassificationID, testFromID, mutables}, auxiliaryRequest{testClassificationID, testFromID, mutables}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewAuxiliaryRequest(tt.args.maintainedClassificationID, tt.args.toIdentityID, tt.args.maintainedMutables); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewAuxiliaryRequest() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, auxiliaryRequest{ClassificationID: classificationID, IdentityID: identityID, MutableProperties: mutableProperties}, testAuxiliaryRequest) - require.Equal(t, nil, testAuxiliaryRequest.Validate()) - require.Equal(t, testAuxiliaryRequest, auxiliaryRequestFromInterface(testAuxiliaryRequest)) - require.Equal(t, auxiliaryRequest{}, auxiliaryRequestFromInterface(nil)) +func Test_auxiliaryRequestFromInterface(t *testing.T) { + type args struct { + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + args args + want auxiliaryRequest + }{ + {"+ve", args{NewAuxiliaryRequest(testClassificationID, testFromID, mutables)}, auxiliaryRequest{testClassificationID, testFromID, mutables}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := auxiliaryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("auxiliaryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_auxiliaryRequest_Validate(t *testing.T) { + type fields struct { + MaintainedClassificationID ids.ClassificationID + ToIdentityID ids.IdentityID + MaintainedMutables qualified.Mutables + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve with nil", fields{}, false}, + {"+ve", fields{testClassificationID, testFromID, mutables}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryRequest := auxiliaryRequest{ + MaintainedClassificationID: tt.fields.MaintainedClassificationID, + ToIdentityID: tt.fields.ToIdentityID, + MaintainedMutables: tt.fields.MaintainedMutables, + } + if err := auxiliaryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/maintainers/auxiliaries/super/response.go b/modules/maintainers/auxiliaries/super/response.go new file mode 100644 index 000000000..596e9bd74 --- /dev/null +++ b/modules/maintainers/auxiliaries/super/response.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package super + +import "github.com/AssetMantle/modules/schema/helpers" + +type auxiliaryResponse struct { + Success bool `json:"success"` + Error error `json:"error"` +} + +var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) + +func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { + return auxiliaryResponse.Success +} +func (auxiliaryResponse auxiliaryResponse) GetError() error { + return auxiliaryResponse.Error +} +func newAuxiliaryResponse(error error) helpers.AuxiliaryResponse { + success := true + if error != nil { + success = false + } + + return auxiliaryResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/maintainers/auxiliaries/super/response_test.go b/modules/maintainers/auxiliaries/super/response_test.go new file mode 100644 index 000000000..8e1289a16 --- /dev/null +++ b/modules/maintainers/auxiliaries/super/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package super + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Super_Response(t *testing.T) { + testAuxiliaryResponse := newAuxiliaryResponse(nil) + require.Equal(t, auxiliaryResponse{Success: true, Error: nil}, testAuxiliaryResponse) + require.Equal(t, true, testAuxiliaryResponse.IsSuccessful()) + require.Equal(t, nil, testAuxiliaryResponse.GetError()) + + testAuxiliaryResponse2 := newAuxiliaryResponse(constants.IncorrectFormat) + require.Equal(t, auxiliaryResponse{Success: false, Error: constants.IncorrectFormat}, testAuxiliaryResponse2) + require.Equal(t, false, testAuxiliaryResponse2.IsSuccessful()) + require.Equal(t, constants.IncorrectFormat, testAuxiliaryResponse2.GetError()) +} diff --git a/modules/maintainers/auxiliaries/verify/auxiliary.go b/modules/maintainers/auxiliaries/verify/auxiliary.go new file mode 100644 index 000000000..4e576e780 --- /dev/null +++ b/modules/maintainers/auxiliaries/verify/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package verify + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "maintainersVerify", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "maintainersVerify", + keeperPrototypeMock, +) diff --git a/modules/maintainers/auxiliaries/verify/keeper.go b/modules/maintainers/auxiliaries/verify/keeper.go new file mode 100644 index 000000000..4a316b8bd --- /dev/null +++ b/modules/maintainers/auxiliaries/verify/keeper.go @@ -0,0 +1,51 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package verify + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/maintainers/internal/key" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/ids/constansts" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + constantProperties "github.com/AssetMantle/modules/schema/properties/constants" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + maintainerID := base.NewMaintainerID(constansts.MaintainerClassificationID, + baseQualified.NewImmutables(baseLists.NewPropertyList( + baseProperties.NewMetaProperty(constantProperties.MaintainedClassificationIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.MaintainedClassificationID)), + baseProperties.NewMetaProperty(constantProperties.IdentityIDProperty.GetKey(), baseData.NewIDData(auxiliaryRequest.MaintainerIdentityID)), + ))) + + maintainers := auxiliaryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(maintainerID)) + + maintainer := maintainers.Get(key.NewKey(maintainerID)) + if maintainer == nil { + return newAuxiliaryResponse(constants.EntityNotFound) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeper{mapper: mapper} +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/maintainers/auxiliaries/verify/keeper_mock.go b/modules/maintainers/auxiliaries/verify/keeper_mock.go new file mode 100644 index 000000000..942f86bff --- /dev/null +++ b/modules/maintainers/auxiliaries/verify/keeper_mock.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package verify + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeperMock)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(_ sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + if auxiliaryRequest.MaintainerIdentityID.String() == "verifyError" { + return newAuxiliaryResponse(constants.MockError) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/maintainers/auxiliaries/verify/request.go b/modules/maintainers/auxiliaries/verify/request.go new file mode 100644 index 000000000..d5dcfc440 --- /dev/null +++ b/modules/maintainers/auxiliaries/verify/request.go @@ -0,0 +1,39 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package verify + +import ( + "github.com/asaskevich/govalidator" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" +) + +type auxiliaryRequest struct { + MaintainedClassificationID ids.ClassificationID `json:"maintainedClassificationID" valid:"required~required field maintainedClassificationID missing"` + MaintainerIdentityID ids.IdentityID `json:"maintainerIdentityID" valid:"required~required field maintainerIdentityID missing"` +} + +var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) + +func (auxiliaryRequest auxiliaryRequest) Validate() error { + _, err := govalidator.ValidateStruct(auxiliaryRequest) + return err +} + +func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { + switch value := request.(type) { + case auxiliaryRequest: + return value + default: + return auxiliaryRequest{} + } +} + +func NewAuxiliaryRequest(maintainedClassificationID ids.ClassificationID, maintainedIdentityID ids.IdentityID) helpers.AuxiliaryRequest { + return auxiliaryRequest{ + MaintainedClassificationID: maintainedClassificationID, + MaintainerIdentityID: maintainedIdentityID, + } +} diff --git a/modules/maintainers/auxiliaries/verify/request_test.go b/modules/maintainers/auxiliaries/verify/request_test.go index eba90f266..2610fea60 100644 --- a/modules/maintainers/auxiliaries/verify/request_test.go +++ b/modules/maintainers/auxiliaries/verify/request_test.go @@ -4,6 +4,9 @@ package verify import ( + "reflect" + "testing" + baseData "github.com/AssetMantle/modules/schema/data/base" "github.com/AssetMantle/modules/schema/helpers" "github.com/AssetMantle/modules/schema/ids" @@ -11,8 +14,6 @@ import ( baseLists "github.com/AssetMantle/modules/schema/lists/base" baseProperties "github.com/AssetMantle/modules/schema/properties/base" baseQualified "github.com/AssetMantle/modules/schema/qualified/base" - "reflect" - "testing" ) var ( diff --git a/modules/maintainers/auxiliaries/verify/response.go b/modules/maintainers/auxiliaries/verify/response.go new file mode 100644 index 000000000..e2ad18f6d --- /dev/null +++ b/modules/maintainers/auxiliaries/verify/response.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package verify + +import "github.com/AssetMantle/modules/schema/helpers" + +type auxiliaryResponse struct { + Success bool `json:"success"` + Error error `json:"error"` +} + +var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) + +func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { + return auxiliaryResponse.Success +} +func (auxiliaryResponse auxiliaryResponse) GetError() error { + return auxiliaryResponse.Error +} +func newAuxiliaryResponse(error error) helpers.AuxiliaryResponse { + success := true + if error != nil { + success = false + } + + return auxiliaryResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/maintainers/auxiliaries/verify/response_test.go b/modules/maintainers/auxiliaries/verify/response_test.go new file mode 100644 index 000000000..9cd5cf1a9 --- /dev/null +++ b/modules/maintainers/auxiliaries/verify/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package verify + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Maintain_Response(t *testing.T) { + testAuxiliaryResponse := newAuxiliaryResponse(nil) + require.Equal(t, auxiliaryResponse{Success: true, Error: nil}, testAuxiliaryResponse) + require.Equal(t, true, testAuxiliaryResponse.IsSuccessful()) + require.Equal(t, nil, testAuxiliaryResponse.GetError()) + + testAuxiliaryResponse2 := newAuxiliaryResponse(constants.IncorrectFormat) + require.Equal(t, auxiliaryResponse{Success: false, Error: constants.IncorrectFormat}, testAuxiliaryResponse2) + require.Equal(t, false, testAuxiliaryResponse2.IsSuccessful()) + require.Equal(t, constants.IncorrectFormat, testAuxiliaryResponse2.GetError()) +} diff --git a/modules/maintainers/doc.go b/modules/maintainers/doc.go new file mode 100644 index 000000000..36c15766b --- /dev/null +++ b/modules/maintainers/doc.go @@ -0,0 +1,5 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +// Package maintainers defines the maintainers module. +package maintainers diff --git a/modules/maintainers/internal/block/block.go b/modules/maintainers/internal/block/block.go new file mode 100644 index 000000000..2b406cdb0 --- /dev/null +++ b/modules/maintainers/internal/block/block.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package block + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + abciTypes "github.com/tendermint/tendermint/abci/types" + + "github.com/AssetMantle/modules/schema/helpers" +) + +type block struct { + mapper helpers.Mapper + parameters helpers.Parameters +} + +var _ helpers.Block = (*block)(nil) + +func (block block) Begin(_ sdkTypes.Context, _ abciTypes.RequestBeginBlock) { + +} + +func (block block) End(_ sdkTypes.Context, _ abciTypes.RequestEndBlock) { + +} + +func Prototype() helpers.Block { + return block{} +} + +func (block block) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, _ ...interface{}) helpers.Block { + block.mapper, block.parameters = mapper, parameters + return block +} diff --git a/modules/maintainers/internal/block/block_test.go b/modules/maintainers/internal/block/block_test.go new file mode 100644 index 000000000..18db9ffb7 --- /dev/null +++ b/modules/maintainers/internal/block/block_test.go @@ -0,0 +1,57 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package block + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/maintainers/internal/mapper" + "github.com/AssetMantle/modules/modules/maintainers/internal/parameters" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" +) + +func CreateTestInput(t *testing.T) sdkTypes.Context { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + return context +} + +func Test_Block_Methods(t *testing.T) { + block := Prototype() + block.Initialize(mapper.Prototype(), parameters.Prototype(), []helpers.Auxiliary{}) + context := CreateTestInput(t) + block.Begin(context, abciTypes.RequestBeginBlock{}) + block.End(context, abciTypes.RequestEndBlock{}) +} diff --git a/modules/maintainers/internal/common/codec.go b/modules/maintainers/internal/common/codec.go new file mode 100644 index 000000000..3a4425bf3 --- /dev/null +++ b/modules/maintainers/internal/common/codec.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package common + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/maintainers/internal/key" + "github.com/AssetMantle/modules/modules/maintainers/internal/mappable" + "github.com/AssetMantle/modules/utilities/module" +) + +var Codec *codec.Codec + +func init() { + Codec = module.RegisterCodec(key.Prototype, mappable.Prototype) +} diff --git a/modules/maintainers/internal/genesis/genesis.go b/modules/maintainers/internal/genesis/genesis.go deleted file mode 100644 index 5da1acc52..000000000 --- a/modules/maintainers/internal/genesis/genesis.go +++ /dev/null @@ -1,188 +0,0 @@ -package genesis - -import ( - "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ helpers.Genesis = (*Genesis)(nil) - -func (genesis Genesis) Default() helpers.Genesis { - return genesis.Initialize(genesis.GetMappableList(), genesis.GetParameterList()) -} - -func (genesis Genesis) Validate() error { - if len(genesis.ParameterList) != len(genesis.DefaultParameterList) { - return errors.InvalidParameter - } - - for _, parameter := range genesis.ParameterList { - var isPresent bool - for _, defaultParameter := range genesis.DefaultParameterList { - isPresent = false - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - isPresent = true - break - } - } - - if !isPresent { - return errors.InvalidParameter - } - - if Error := parameter.Validate(); Error != nil { - return Error - } - } - - _, Error := govalidator.ValidateStruct(genesis) - - return Error -} - -func (genesis Genesis) Import(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) { - for _, mappableValue := range genesis.MappableList { - mapper.Create(context, &mappableValue) - } - - for _, parameter := range genesis.ParameterList { - parameters.Mutate(context, ¶meter) - } -} - -func (genesis Genesis) Export(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) helpers.Genesis { - var mappableList []helpers.Mappable - - appendMappableList := func(mappable helpers.Mappable) bool { - mappableList = append(mappableList, mappable) - return false - } - mapper.Iterate(context, key.Prototype(), appendMappableList) - - for _, defaultParameter := range genesis.DefaultParameterList { - parameters = parameters.Fetch(context, defaultParameter.GetID()) - } - - return genesis.Initialize(mappableList, parameters.GetList()) -} - -func (genesis Genesis) LegacyAminoEncode() []byte { - legacyAminoCodec := codec.NewLegacyAmino() - bytes, Error := legacyAminoCodec.MarshalJSON(genesis) - if Error != nil { - panic(Error) - } - - return bytes -} -func (genesis Genesis) LegacyAminoDecode(byte []byte) helpers.Genesis { - var newGenesis Genesis - legacyAminoCodec := codec.NewLegacyAmino() - if Error := legacyAminoCodec.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(genesis.DefaultMappableList, genesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Encode(cdc codec.JSONMarshaler) []byte { - bytes, Error := cdc.MarshalJSON(&genesis) - if Error != nil { - panic(Error) - } - - return bytes -} - -func (genesis Genesis) Decode(cdc codec.JSONMarshaler, byte []byte) helpers.Genesis { - var newGenesis Genesis - if Error := cdc.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(genesis.DefaultMappableList, genesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Initialize(mappableList []helpers.Mappable, parameterList []types.Parameter) helpers.Genesis { - newParametersList := make([]dummy.DummyParameter, len(parameterList)) - for i, _ := range parameterList { - newParametersList[i] = *dummy.NewParameter(parameterList[i].GetID(), parameterList[i].GetData()) - } - newMappableList := make([]mappable.Maintainer, len(mappableList)) - for i, _ := range mappableList { - newMappableList[i] = *mappableList[i].(*mappable.Maintainer) - } - newParameter := dummy.Parameter.Mutate(dummy.Parameter.GetData()) - genesis.DefaultParameterList = []dummy.DummyParameter{*dummy.NewParameter(newParameter.GetID(), newParameter.GetData())} - if len(newMappableList) == 0 { - genesis.MappableList = genesis.DefaultMappableList - } else { - genesis.MappableList = newMappableList - } - - if len(newParametersList) == 0 { - genesis.ParameterList = genesis.DefaultParameterList - } else { - for _, defaultParameter := range genesis.DefaultParameterList { - for i, parameter := range newParametersList { - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - newParametersList[i] = *dummy.NewParameter(defaultParameter.Mutate(parameter.GetData()).GetID(), defaultParameter.Mutate(parameter.GetData()).GetData()) - } - } - } - genesis.ParameterList = newParametersList - } - - if Error := genesis.Validate(); Error != nil { - panic(Error) - } - - return &genesis -} - -func (genesis Genesis) GetParameterList() []types.Parameter { - newParameterList := make([]types.Parameter, len(genesis.ParameterList)) - for i, _ := range genesis.ParameterList { - newParameterList[i] = &genesis.ParameterList[i] - } - return newParameterList -} -func (genesis Genesis) GetMappableList() []helpers.Mappable { - newMappableList := make([]helpers.Mappable, len(genesis.MappableList)) - for i, _ := range genesis.MappableList { - newMappableList[i] = &genesis.MappableList[i] - } - return newMappableList -} - -func (genesis Genesis) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*helpers.Key)(nil), - &key.MaintainerID{}, - ) - registry.RegisterImplementations((*helpers.Mappable)(nil), - &mappable.Maintainer{}, - ) - registry.RegisterImplementations((*types.Parameter)(nil), - &dummy.DummyParameter{}, - ) - registry.RegisterImplementations((*helpers.Genesis)(nil), - &Genesis{}, - ) -} - -func NewGenesis(defaultMappableList []mappable.Maintainer, defaultParameterList []dummy.DummyParameter) *Genesis { - return &Genesis{ - DefaultMappableList: defaultMappableList, - DefaultParameterList: defaultParameterList, - MappableList: []mappable.Maintainer{}, - ParameterList: []dummy.DummyParameter{}, - } -} diff --git a/modules/maintainers/internal/genesis/genesis.pb.go b/modules/maintainers/internal/genesis/genesis.pb.go deleted file mode 100644 index 54dae44f2..000000000 --- a/modules/maintainers/internal/genesis/genesis.pb.go +++ /dev/null @@ -1,499 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/maintainers/internal/genesis/genesis.proto - -package genesis - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - mappable "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/mappable" - dummy "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/parameters/dummy" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Genesis struct { - DefaultMappableList []mappable.Maintainer `protobuf:"bytes,1,rep,name=defaultMappableList,proto3" json:"defaultMappableList"` - DefaultParameterList []dummy.DummyParameter `protobuf:"bytes,2,rep,name=defaultParameterList,proto3" json:"defaultParameterList"` - MappableList []mappable.Maintainer `protobuf:"bytes,3,rep,name=MappableList,proto3" json:"MappableList"` - ParameterList []dummy.DummyParameter `protobuf:"bytes,4,rep,name=ParameterList,proto3" json:"ParameterList"` -} - -func (m *Genesis) Reset() { *m = Genesis{} } -func (m *Genesis) String() string { return proto.CompactTextString(m) } -func (*Genesis) ProtoMessage() {} -func (*Genesis) Descriptor() ([]byte, []int) { - return fileDescriptor_eed0d80855c0cf8c, []int{0} -} -func (m *Genesis) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Genesis) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Genesis.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Genesis) XXX_Merge(src proto.Message) { - xxx_messageInfo_Genesis.Merge(m, src) -} -func (m *Genesis) XXX_Size() int { - return m.Size() -} -func (m *Genesis) XXX_DiscardUnknown() { - xxx_messageInfo_Genesis.DiscardUnknown(m) -} - -var xxx_messageInfo_Genesis proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Genesis)(nil), "persistence_sdk.modules.maintainers.internal.genesis.Genesis") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/maintainers/internal/genesis/genesis.proto", fileDescriptor_eed0d80855c0cf8c) -} - -var fileDescriptor_eed0d80855c0cf8c = []byte{ - // 332 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x72, 0x2a, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4d, 0xcc, 0xcc, 0x2b, 0x49, 0xcc, 0xcc, 0x4b, 0x2d, 0x2a, 0xd6, - 0xcf, 0xcc, 0x2b, 0x49, 0x2d, 0xca, 0x4b, 0xcc, 0xd1, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, - 0x86, 0xd1, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x26, 0x68, 0x66, 0xe8, 0x41, 0xcd, 0xd0, - 0x43, 0x32, 0x43, 0x0f, 0x66, 0x86, 0x1e, 0x54, 0xaf, 0x94, 0x48, 0x7a, 0x7e, 0x7a, 0x3e, 0xd8, - 0x00, 0x7d, 0x10, 0x0b, 0x62, 0x96, 0x94, 0x2f, 0x49, 0xee, 0x29, 0x48, 0x2c, 0x4a, 0xcc, 0x4d, - 0x2d, 0x01, 0x89, 0xa5, 0x94, 0xe6, 0xe6, 0x56, 0x22, 0x04, 0xa0, 0xc6, 0xb9, 0x91, 0x64, 0x5c, - 0x6e, 0x62, 0x41, 0x41, 0x62, 0x52, 0x4e, 0x2a, 0x92, 0x2c, 0xc4, 0x1c, 0xa5, 0x3f, 0xcc, 0x5c, - 0xec, 0xee, 0x10, 0x87, 0x0b, 0x55, 0x72, 0x09, 0xa7, 0xa4, 0xa6, 0x25, 0x96, 0xe6, 0x94, 0xf8, - 0x42, 0xd5, 0xfb, 0x64, 0x16, 0x97, 0x48, 0x30, 0x2a, 0x30, 0x6b, 0x70, 0x1b, 0x39, 0xea, 0x91, - 0x14, 0x18, 0x30, 0x1b, 0xf5, 0x7c, 0xe1, 0xb2, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, 0x04, 0x61, - 0xb3, 0x43, 0xa8, 0x9d, 0x91, 0x4b, 0x04, 0x2a, 0x1e, 0x00, 0xf3, 0x29, 0xd8, 0x72, 0x26, 0xb0, - 0xe5, 0xbe, 0xa4, 0x59, 0x8e, 0x08, 0x3d, 0x3d, 0x70, 0xe8, 0xe9, 0xb9, 0x80, 0x48, 0xb8, 0xc1, - 0x50, 0x87, 0x60, 0xb5, 0x50, 0x28, 0x9b, 0x8b, 0x07, 0xc5, 0xf7, 0xcc, 0xd4, 0xf5, 0x3d, 0x8a, - 0xe1, 0x42, 0x95, 0x5c, 0xbc, 0xa8, 0xde, 0x65, 0xa1, 0x9d, 0x77, 0x51, 0x6d, 0xb2, 0x62, 0xe9, - 0x58, 0x20, 0xcf, 0xe0, 0x94, 0x7e, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, - 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, - 0xbe, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x48, 0xae, 0xf1, 0xcf, - 0x4b, 0x45, 0xe6, 0x06, 0xbb, 0x78, 0x13, 0x95, 0xb1, 0x92, 0xd8, 0xc0, 0xc9, 0xcd, 0x18, 0x10, - 0x00, 0x00, 0xff, 0xff, 0x8a, 0xf4, 0x88, 0xd2, 0x97, 0x03, 0x00, 0x00, -} - -func (m *Genesis) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Genesis) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Genesis) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ParameterList) > 0 { - for iNdEx := len(m.ParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.MappableList) > 0 { - for iNdEx := len(m.MappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.DefaultParameterList) > 0 { - for iNdEx := len(m.DefaultParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.DefaultMappableList) > 0 { - for iNdEx := len(m.DefaultMappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultMappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Genesis) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.DefaultMappableList) > 0 { - for _, e := range m.DefaultMappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.DefaultParameterList) > 0 { - for _, e := range m.DefaultParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.MappableList) > 0 { - for _, e := range m.MappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ParameterList) > 0 { - for _, e := range m.ParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Genesis) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Genesis: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Genesis: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultMappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultMappableList = append(m.DefaultMappableList, mappable.Maintainer{}) - if err := m.DefaultMappableList[len(m.DefaultMappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultParameterList = append(m.DefaultParameterList, dummy.DummyParameter{}) - if err := m.DefaultParameterList[len(m.DefaultParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MappableList = append(m.MappableList, mappable.Maintainer{}) - if err := m.MappableList[len(m.MappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ParameterList = append(m.ParameterList, dummy.DummyParameter{}) - if err := m.ParameterList[len(m.ParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/maintainers/internal/genesis/prototype.go b/modules/maintainers/internal/genesis/prototype.go index 7fc9e14be..b987ca37f 100644 --- a/modules/maintainers/internal/genesis/prototype.go +++ b/modules/maintainers/internal/genesis/prototype.go @@ -1,16 +1,16 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package genesis import ( - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/maintainers/internal/key" + "github.com/AssetMantle/modules/modules/maintainers/internal/mappable" + "github.com/AssetMantle/modules/modules/maintainers/internal/parameters" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" ) func Prototype() helpers.Genesis { - return NewGenesis([]mappable.Maintainer{}, []dummy.DummyParameter{}) + return baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{}, parameters.Prototype().GetList()) } diff --git a/modules/maintainers/internal/genesis/prototype_test.go b/modules/maintainers/internal/genesis/prototype_test.go new file mode 100644 index 000000000..057d880b8 --- /dev/null +++ b/modules/maintainers/internal/genesis/prototype_test.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package genesis + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/maintainers/internal/key" + "github.com/AssetMantle/modules/modules/maintainers/internal/mappable" + "github.com/AssetMantle/modules/modules/maintainers/internal/parameters" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Panics(t, func() { + require.Equal(t, Prototype(), baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{}, parameters.Prototype().GetList())) + }) +} diff --git a/modules/maintainers/internal/key/key.go b/modules/maintainers/internal/key/key.go new file mode 100644 index 000000000..d06d6d8c6 --- /dev/null +++ b/modules/maintainers/internal/key/key.go @@ -0,0 +1,55 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package key + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/maintainers/internal/module" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +type key struct { + ids.MaintainerID +} + +var _ helpers.Key = (*key)(nil) + +func (key key) GenerateStoreKeyBytes() []byte { + return module.StoreKeyPrefix.GenerateStoreKey(key.Bytes()) +} +func (key) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, key{}) +} +func (key key) IsPartial() bool { + return len(key.MaintainerID.Bytes()) == 0 +} +func (key key) Equals(compareKey helpers.Key) bool { + if CompareKey, err := keyFromInterface(compareKey); err != nil { + return false + } else { + return key.MaintainerID.Compare(CompareKey.MaintainerID) == 0 + } +} +func keyFromInterface(i interface{}) (key, error) { + switch value := i.(type) { + case key: + return value, nil + default: + return key{}, constants.MetaDataError + } +} + +func NewKey(maintainerID ids.MaintainerID) helpers.Key { + return key{ + MaintainerID: maintainerID, + } +} + +func Prototype() helpers.Key { + return key{} +} diff --git a/modules/maintainers/internal/key/key_test.go b/modules/maintainers/internal/key/key_test.go new file mode 100644 index 000000000..218d2d602 --- /dev/null +++ b/modules/maintainers/internal/key/key_test.go @@ -0,0 +1,193 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package key + +import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/maintainers/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +func createTestData() ids.MaintainerID { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + // testIdentityID := baseIDs.NewIdentityID(testClassificationID, immutables) + testMaintainerID := baseIDs.NewMaintainerID(testClassificationID, immutables) + return testMaintainerID +} + +func TestNewKey(t *testing.T) { + type args struct { + maintainerID ids.MaintainerID + } + tests := []struct { + name string + args args + want helpers.Key + }{ + {"+ve with nil", args{}, key{}}, + {"+ve", args{createTestData()}, key{createTestData()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewKey(tt.args.maintainerID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewKey() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Key + }{ + {"+ve", key{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_keyFromInterface(t *testing.T) { + type args struct { + i interface{} + } + tests := []struct { + name string + args args + want key + wantErr bool + }{ + {"+ve", args{NewKey(createTestData())}, key{createTestData()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := keyFromInterface(tt.args.i) + if (err != nil) != tt.wantErr { + t.Errorf("keyFromInterface() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("keyFromInterface() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_Equals(t *testing.T) { + type fields struct { + MaintainerID ids.MaintainerID + } + type args struct { + compareKey helpers.Key + } + tests := []struct { + name string + fields fields + args args + want bool + }{ + {"+ve", fields{createTestData()}, args{NewKey(createTestData())}, true}, + {"-ve", fields{createTestData()}, args{NewKey(baseIDs.PrototypeMaintainerID())}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key := key{ + MaintainerID: tt.fields.MaintainerID, + } + if got := key.Equals(tt.args.compareKey); got != tt.want { + t.Errorf("Equals() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_GenerateStoreKeyBytes(t *testing.T) { + type fields struct { + MaintainerID ids.MaintainerID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{createTestData()}, module.StoreKeyPrefix.GenerateStoreKey(key{createTestData()}.Bytes())}, + {"-ve", fields{baseIDs.PrototypeMaintainerID()}, module.StoreKeyPrefix.GenerateStoreKey(key{baseIDs.PrototypeMaintainerID()}.Bytes())}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key := key{ + MaintainerID: tt.fields.MaintainerID, + } + if got := key.GenerateStoreKeyBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GenerateStoreKeyBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_IsPartial(t *testing.T) { + type fields struct { + MaintainerID ids.MaintainerID + } + tests := []struct { + name string + fields fields + want bool + }{ + {"+ve", fields{createTestData()}, false}, + {"-ve", fields{baseIDs.PrototypeMaintainerID()}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key := key{ + MaintainerID: tt.fields.MaintainerID, + } + if got := key.IsPartial(); got != tt.want { + t.Errorf("IsPartial() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_RegisterCodec(t *testing.T) { + type fields struct { + MaintainerID ids.MaintainerID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{createTestData()}, args{codec.New()}}, + {"-ve", fields{createTestData()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ke := key{ + MaintainerID: tt.fields.MaintainerID, + } + ke.RegisterCodec(tt.args.codec) + }) + } +} diff --git a/modules/maintainers/internal/key/maintainerID.go b/modules/maintainers/internal/key/maintainerID.go deleted file mode 100644 index cc0f74f95..000000000 --- a/modules/maintainers/internal/key/maintainerID.go +++ /dev/null @@ -1,61 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - "bytes" - "strings" - - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" -) - -var _ types.ID = (*MaintainerID)(nil) -var _ helpers.Key = (*MaintainerID)(nil) - -func (maintainerID MaintainerID) GetStructReference() codec.ProtoMarshaler { - return &maintainerID -} -func (maintainerID MaintainerID) Bytes() []byte { - return append( - maintainerID.ClassificationID.Bytes(), - maintainerID.IdentityID.Bytes()...) -} -func (maintainerID MaintainerID) String() string { - var values []string - values = append(values, maintainerID.ClassificationID.String()) - values = append(values, maintainerID.IdentityID.String()) - - return strings.Join(values, constants.SecondOrderCompositeIDSeparator) -} -func (maintainerID MaintainerID) Compare(id types.ID) int { - return bytes.Compare(maintainerID.Bytes(), id.Bytes()) -} -func (maintainerID MaintainerID) GenerateStoreKeyBytes() []byte { - return module.StoreKeyPrefix.GenerateStoreKey(maintainerID.Bytes()) -} -func (MaintainerID) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, MaintainerID{}) -} -func (maintainerID MaintainerID) IsPartial() bool { - return len(maintainerID.IdentityID.Bytes()) == 0 -} -func (maintainerID MaintainerID) Equals(key helpers.Key) bool { - a := maintainerIDFromInterface(key) - return maintainerID.Compare(&a) == 0 -} - -func NewMaintainerID(classificationID types.ID, identityID types.ID) types.ID { - return &MaintainerID{ - ClassificationID: classificationID, - IdentityID: identityID, - } -} diff --git a/modules/maintainers/internal/key/maintainerID.pb.go b/modules/maintainers/internal/key/maintainerID.pb.go deleted file mode 100644 index 9a5bf4c27..000000000 --- a/modules/maintainers/internal/key/maintainerID.pb.go +++ /dev/null @@ -1,368 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/maintainers/internal/key/maintainerID.proto - -package key - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - github_com_persistenceOne_persistenceSDK_schema_types "github.com/persistenceOne/persistenceSDK/schema/types" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type MaintainerID struct { - ClassificationID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,1,opt,name=classification_i_d,json=classificationID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"classification_i_d"` - IdentityID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,2,opt,name=identity_i_d,json=identityID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"identity_i_d"` -} - -func (m *MaintainerID) Reset() { *m = MaintainerID{} } -func (*MaintainerID) ProtoMessage() {} -func (*MaintainerID) Descriptor() ([]byte, []int) { - return fileDescriptor_9fcf415f593eaa69, []int{0} -} -func (m *MaintainerID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MaintainerID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MaintainerID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MaintainerID) XXX_Merge(src proto.Message) { - xxx_messageInfo_MaintainerID.Merge(m, src) -} -func (m *MaintainerID) XXX_Size() int { - return m.Size() -} -func (m *MaintainerID) XXX_DiscardUnknown() { - xxx_messageInfo_MaintainerID.DiscardUnknown(m) -} - -var xxx_messageInfo_MaintainerID proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MaintainerID)(nil), "persistence_sdk.modules.maintainers.internal.key.MaintainerID") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/maintainers/internal/key/maintainerID.proto", fileDescriptor_9fcf415f593eaa69) -} - -var fileDescriptor_9fcf415f593eaa69 = []byte{ - // 274 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x72, 0x2e, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4d, 0xcc, 0xcc, 0x2b, 0x49, 0xcc, 0xcc, 0x4b, 0x2d, 0x2a, 0xd6, - 0xcf, 0xcc, 0x2b, 0x49, 0x2d, 0xca, 0x4b, 0xcc, 0xd1, 0xcf, 0x4e, 0xad, 0x44, 0x92, 0xf0, 0x74, - 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x32, 0x40, 0x33, 0x44, 0x0f, 0x6a, 0x88, 0x1e, 0x92, - 0x21, 0x7a, 0x30, 0x43, 0xf4, 0xb2, 0x53, 0x2b, 0xa5, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x9a, - 0xf5, 0x41, 0x2c, 0x88, 0x39, 0x4a, 0x2f, 0x18, 0xb9, 0x78, 0x7c, 0x91, 0x8c, 0x17, 0xca, 0xe3, - 0x12, 0x4a, 0xce, 0x49, 0x2c, 0x2e, 0xce, 0x4c, 0xcb, 0x4c, 0x4e, 0x2c, 0xc9, 0xcc, 0xcf, 0x8b, - 0xcf, 0x8c, 0x4f, 0x91, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x74, 0x72, 0x38, 0x71, 0x4f, 0x9e, 0xe1, - 0xd6, 0x3d, 0x79, 0x8b, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0x24, - 0x77, 0xf8, 0xe7, 0xa5, 0x22, 0x73, 0x83, 0x5d, 0xbc, 0xf5, 0x8b, 0x93, 0x33, 0x52, 0x73, 0x13, - 0xf5, 0x4b, 0x2a, 0x0b, 0x52, 0x8b, 0xf5, 0x3c, 0x5d, 0x82, 0x04, 0x50, 0xcd, 0xf6, 0x74, 0x11, - 0x4a, 0xe2, 0xe2, 0xc9, 0x4c, 0x49, 0xcd, 0x2b, 0xc9, 0x2c, 0xa9, 0x04, 0xdb, 0xc4, 0x44, 0x25, - 0x9b, 0xb8, 0x60, 0xa6, 0x7a, 0xba, 0x58, 0xb1, 0xcc, 0x58, 0x20, 0xcf, 0xe0, 0x94, 0x7c, 0xe2, - 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, - 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x9e, 0x44, 0xdb, 0x42, 0x28, 0xaa, 0x92, - 0xd8, 0xc0, 0xc1, 0x6a, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x0d, 0x79, 0x9e, 0xd7, 0xe5, 0x01, - 0x00, 0x00, -} - -func (m *MaintainerID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MaintainerID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MaintainerID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.IdentityID.Size() - i -= size - if _, err := m.IdentityID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMaintainerID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.ClassificationID.Size() - i -= size - if _, err := m.ClassificationID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMaintainerID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintMaintainerID(dAtA []byte, offset int, v uint64) int { - offset -= sovMaintainerID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MaintainerID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ClassificationID.Size() - n += 1 + l + sovMaintainerID(uint64(l)) - l = m.IdentityID.Size() - n += 1 + l + sovMaintainerID(uint64(l)) - return n -} - -func sovMaintainerID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMaintainerID(x uint64) (n int) { - return sovMaintainerID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MaintainerID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMaintainerID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MaintainerID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MaintainerID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMaintainerID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMaintainerID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMaintainerID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IdentityID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMaintainerID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMaintainerID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMaintainerID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.IdentityID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMaintainerID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMaintainerID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMaintainerID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMaintainerID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMaintainerID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMaintainerID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMaintainerID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMaintainerID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMaintainerID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMaintainerID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMaintainerID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMaintainerID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/maintainers/internal/key/maintainerID_test.go b/modules/maintainers/internal/key/maintainerID_test.go deleted file mode 100644 index 555dfb8a9..000000000 --- a/modules/maintainers/internal/key/maintainerID_test.go +++ /dev/null @@ -1,38 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - "strings" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -func Test_MaintainerID_Methods(t *testing.T) { - classificationID := base.NewID("classificationID") - identityID := base.NewID("identityID") - - testMaintainerID := NewMaintainerID(classificationID, identityID).(MaintainerID) - require.NotPanics(t, func() { - require.Equal(t, MaintainerID{ClassificationID: classificationID, IdentityID: identityID}, testMaintainerID) - require.Equal(t, strings.Join([]string{classificationID.String(), identityID.String()}, constants.SecondOrderCompositeIDSeparator), testMaintainerID.String()) - require.Equal(t, false, testMaintainerID.IsPartial()) - require.Equal(t, true, MaintainerID{ClassificationID: base.NewID(""), IdentityID: base.NewID("")}.IsPartial()) - require.Equal(t, true, testMaintainerID.Equals(testMaintainerID)) - require.Equal(t, false, testMaintainerID.Equals(MaintainerID{ClassificationID: base.NewID(""), IdentityID: base.NewID("")})) - require.Equal(t, true, testMaintainerID.Equals(testMaintainerID)) - require.Equal(t, false, testMaintainerID.Equals(MaintainerID{ClassificationID: base.NewID(""), IdentityID: base.NewID("")})) - require.Equal(t, false, testMaintainerID.Equals(nil)) - require.Equal(t, testMaintainerID, FromID(&testMaintainerID)) - require.Equal(t, MaintainerID{ClassificationID: base.NewID(""), IdentityID: base.NewID("")}, FromID(base.NewID(""))) - require.Equal(t, testMaintainerID, readMaintainerID(testMaintainerID.String())) - }) - -} diff --git a/modules/maintainers/internal/key/utilities.go b/modules/maintainers/internal/key/utilities.go deleted file mode 100644 index 128e80e48..000000000 --- a/modules/maintainers/internal/key/utilities.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - "strings" - - "github.com/persistenceOne/persistenceSDK/schema/helpers" - - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -func readMaintainerID(maintainerIDString string) MaintainerID { - idList := strings.Split(maintainerIDString, constants.SecondOrderCompositeIDSeparator) - if len(idList) == 2 { - return MaintainerID{ - ClassificationID: base.NewID(idList[0]), - IdentityID: base.NewID(idList[1]), - } - } - - return MaintainerID{IdentityID: base.NewID(""), ClassificationID: base.NewID("")} -} -func maintainerIDFromInterface(i interface{}) MaintainerID { - switch value := i.(type) { - case MaintainerID: - return value - case types.ID: - return maintainerIDFromInterface(readMaintainerID(value.String())) - default: - panic(i) - } -} - -func ReadClassificationID(assetID types.ID) types.ID { - return maintainerIDFromInterface(assetID).ClassificationID -} - -func ReadIdentityID(assetID types.ID) types.ID { - return maintainerIDFromInterface(assetID).IdentityID -} - -func FromID(id types.ID) helpers.Key { - return maintainerIDFromInterface(id) -} diff --git a/modules/maintainers/internal/mappable/maintainer.go b/modules/maintainers/internal/mappable/maintainer.go deleted file mode 100644 index d1fc8b492..000000000 --- a/modules/maintainers/internal/mappable/maintainer.go +++ /dev/null @@ -1,61 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/mappables" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" -) - -var _ mappables.Maintainer = (*Maintainer)(nil) - -func (maintainer Maintainer) GetStructReference() codec.ProtoMarshaler { - return &maintainer -} -func (maintainer Maintainer) GetID() types.ID { return &maintainer.ID } -func (maintainer Maintainer) GetClassificationID() types.ID { - return key.ReadClassificationID(&maintainer.ID) -} -func (maintainer Maintainer) GetIdentityID() types.ID { - return key.ReadIdentityID(&maintainer.ID) -} -func (maintainer Maintainer) GetMaintainedProperties() types.Properties { - return &maintainer.MaintainedProperties -} -func (maintainer Maintainer) CanAddMaintainer() bool { return maintainer.AddMaintainer } -func (maintainer Maintainer) CanRemoveMaintainer() bool { return maintainer.RemoveMaintainer } -func (maintainer Maintainer) CanMutateMaintainer() bool { return maintainer.MutateMaintainer } -func (maintainer Maintainer) MaintainsProperty(id types.ID) bool { - for _, property := range maintainer.MaintainedProperties.GetList() { - if property.GetID().Compare(id) == 0 { - return true - } - } - - return false -} -func (maintainer Maintainer) GetKey() helpers.Key { - return key.FromID(&maintainer.ID) -} - -func (Maintainer) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Maintainer{}) -} -func NewMaintainer(id types.ID, maintainedProperties types.Properties, addMaintainer bool, removeMaintainer bool, mutateMaintainer bool) mappables.Maintainer { - return &Maintainer{ - ID: *base.NewID(id.String()), - MaintainedProperties: *base.NewProperties(maintainedProperties.GetList()...), - AddMaintainer: addMaintainer, - RemoveMaintainer: removeMaintainer, - MutateMaintainer: mutateMaintainer, - } -} diff --git a/modules/maintainers/internal/mappable/maintainer.pb.go b/modules/maintainers/internal/mappable/maintainer.pb.go deleted file mode 100644 index 6317a9754..000000000 --- a/modules/maintainers/internal/mappable/maintainer.pb.go +++ /dev/null @@ -1,476 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/maintainers/internal/mappable/maintainer.proto - -package mappable - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - _ "github.com/persistenceOne/persistenceSDK/schema/traits/base" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Maintainer struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - MaintainedProperties base.Properties `protobuf:"bytes,2,opt,name=maintained_properties,json=maintainedProperties,proto3" json:"maintained_properties"` - AddMaintainer bool `protobuf:"varint,3,opt,name=add_maintainer,json=addMaintainer,proto3" json:"add_maintainer,omitempty"` - RemoveMaintainer bool `protobuf:"varint,4,opt,name=remove_maintainer,json=removeMaintainer,proto3" json:"remove_maintainer,omitempty"` - MutateMaintainer bool `protobuf:"varint,5,opt,name=mutate_maintainer,json=mutateMaintainer,proto3" json:"mutate_maintainer,omitempty"` -} - -func (m *Maintainer) Reset() { *m = Maintainer{} } -func (m *Maintainer) String() string { return proto.CompactTextString(m) } -func (*Maintainer) ProtoMessage() {} -func (*Maintainer) Descriptor() ([]byte, []int) { - return fileDescriptor_162e2aebee016dce, []int{0} -} -func (m *Maintainer) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Maintainer) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Maintainer.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Maintainer) XXX_Merge(src proto.Message) { - xxx_messageInfo_Maintainer.Merge(m, src) -} -func (m *Maintainer) XXX_Size() int { - return m.Size() -} -func (m *Maintainer) XXX_DiscardUnknown() { - xxx_messageInfo_Maintainer.DiscardUnknown(m) -} - -var xxx_messageInfo_Maintainer proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Maintainer)(nil), "persistence_sdk.modules.maintainers.internal.mappable.Maintainer") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/maintainers/internal/mappable/maintainer.proto", fileDescriptor_162e2aebee016dce) -} - -var fileDescriptor_162e2aebee016dce = []byte{ - // 377 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x92, 0xcd, 0x4a, 0xf3, 0x40, - 0x14, 0x86, 0x93, 0xb6, 0xdf, 0x87, 0x44, 0x14, 0x0d, 0x15, 0x4a, 0x17, 0x69, 0x11, 0x0a, 0x45, - 0x71, 0x06, 0xea, 0xcf, 0x42, 0x5c, 0x95, 0x22, 0x14, 0xa9, 0x4a, 0xdd, 0xb9, 0x09, 0x93, 0xce, - 0xa1, 0x19, 0xec, 0x64, 0xc2, 0xcc, 0x54, 0xf0, 0x0e, 0x5c, 0x7a, 0x09, 0xde, 0x87, 0x37, 0xd0, - 0x65, 0x97, 0xae, 0x44, 0xda, 0x1b, 0x91, 0xfc, 0xb4, 0x49, 0x0b, 0x62, 0x77, 0x09, 0xef, 0xf3, - 0x3e, 0xc9, 0x9c, 0x33, 0xd6, 0x75, 0x08, 0x52, 0x31, 0xa5, 0x21, 0x18, 0x80, 0xab, 0xe8, 0x13, - 0xe6, 0x82, 0x8e, 0x47, 0xa0, 0x30, 0x27, 0x2c, 0xd0, 0x84, 0x05, 0x20, 0x15, 0x66, 0x81, 0x06, - 0x19, 0x90, 0x11, 0xe6, 0x24, 0x0c, 0x89, 0x37, 0x82, 0x5c, 0x8a, 0x42, 0x29, 0xb4, 0xb0, 0xcf, - 0xd7, 0x3c, 0x28, 0xf5, 0xa0, 0x9c, 0x07, 0x2d, 0x3c, 0x68, 0xe1, 0xa9, 0x96, 0x87, 0x62, 0x28, - 0x62, 0x03, 0x8e, 0x9e, 0x12, 0x59, 0xf5, 0x62, 0xfd, 0xa7, 0xd4, 0xc0, 0x07, 0x4e, 0xb0, 0x96, - 0x84, 0x69, 0x85, 0x3d, 0xa2, 0x00, 0xfb, 0x44, 0x75, 0x39, 0x1f, 0xeb, 0x48, 0xa3, 0xd2, 0xde, - 0xd9, 0x66, 0xbd, 0xde, 0x6a, 0xeb, 0xe8, 0xb7, 0xd6, 0x4b, 0x08, 0x69, 0x89, 0xd1, 0x94, 0x6d, - 0xfd, 0xcd, 0x86, 0x52, 0x84, 0x20, 0x35, 0x5b, 0xf8, 0x0f, 0x3f, 0x0a, 0x96, 0xd5, 0x5b, 0x4e, - 0xc1, 0xbe, 0xb2, 0x8a, 0xcc, 0xa5, 0x15, 0xb3, 0x6e, 0x36, 0xb7, 0x5b, 0x0d, 0xb4, 0x3e, 0xb7, - 0x44, 0x88, 0x62, 0x21, 0x8a, 0x84, 0xa8, 0xdb, 0x69, 0x97, 0x26, 0x5f, 0x35, 0xa3, 0x5f, 0x60, - 0x1d, 0xdb, 0xb7, 0x0e, 0x96, 0x13, 0xa5, 0x6e, 0xf6, 0xad, 0x4a, 0x21, 0xf6, 0x9d, 0x6c, 0xe0, - 0xbb, 0x5f, 0x96, 0x52, 0x6f, 0x39, 0x33, 0x66, 0x99, 0xdd, 0xb0, 0x76, 0x09, 0xa5, 0x6e, 0xb6, - 0xbf, 0x4a, 0xb1, 0x6e, 0x36, 0xb7, 0xfa, 0x3b, 0x84, 0xd2, 0xdc, 0x71, 0x8e, 0xad, 0x7d, 0x09, - 0x5c, 0x3c, 0x43, 0x9e, 0x2c, 0xc5, 0xe4, 0x5e, 0x12, 0xac, 0xc2, 0xd1, 0xca, 0xf4, 0x0a, 0xfc, - 0x2f, 0x81, 0x93, 0x20, 0x83, 0x2f, 0x4b, 0xaf, 0xef, 0x35, 0xa3, 0xed, 0x4f, 0x66, 0x8e, 0x39, - 0x9d, 0x39, 0xe6, 0xf7, 0xcc, 0x31, 0xdf, 0xe6, 0x8e, 0x31, 0x9d, 0x3b, 0xc6, 0xe7, 0xdc, 0x31, - 0x1e, 0x6f, 0x87, 0x4c, 0xfb, 0x63, 0x0f, 0x0d, 0x04, 0xc7, 0xb9, 0x53, 0xdf, 0x05, 0x90, 0x7f, - 0x7d, 0xe8, 0xdc, 0x6c, 0x76, 0xa7, 0xbd, 0xff, 0xf1, 0xba, 0x4e, 0x7f, 0x02, 0x00, 0x00, 0xff, - 0xff, 0x31, 0x17, 0x1b, 0x3d, 0x13, 0x03, 0x00, 0x00, -} - -func (m *Maintainer) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Maintainer) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Maintainer) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.MutateMaintainer { - i-- - if m.MutateMaintainer { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x28 - } - if m.RemoveMaintainer { - i-- - if m.RemoveMaintainer { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x20 - } - if m.AddMaintainer { - i-- - if m.AddMaintainer { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x18 - } - { - size, err := m.MaintainedProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMaintainer(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMaintainer(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintMaintainer(dAtA []byte, offset int, v uint64) int { - offset -= sovMaintainer(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Maintainer) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovMaintainer(uint64(l)) - l = m.MaintainedProperties.Size() - n += 1 + l + sovMaintainer(uint64(l)) - if m.AddMaintainer { - n += 2 - } - if m.RemoveMaintainer { - n += 2 - } - if m.MutateMaintainer { - n += 2 - } - return n -} - -func sovMaintainer(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMaintainer(x uint64) (n int) { - return sovMaintainer(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Maintainer) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMaintainer - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Maintainer: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Maintainer: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMaintainer - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMaintainer - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMaintainer - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaintainedProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMaintainer - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMaintainer - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMaintainer - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MaintainedProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AddMaintainer", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMaintainer - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.AddMaintainer = bool(v != 0) - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field RemoveMaintainer", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMaintainer - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.RemoveMaintainer = bool(v != 0) - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MutateMaintainer", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMaintainer - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.MutateMaintainer = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipMaintainer(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMaintainer - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMaintainer(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMaintainer - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMaintainer - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMaintainer - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMaintainer - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMaintainer - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMaintainer - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMaintainer = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMaintainer = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMaintainer = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/maintainers/internal/mappable/maintainer_test.go b/modules/maintainers/internal/mappable/maintainer_test.go deleted file mode 100644 index fe1b9dd46..000000000 --- a/modules/maintainers/internal/mappable/maintainer_test.go +++ /dev/null @@ -1,35 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import ( - "testing" - - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/key" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" -) - -func Test_Maintainer_Methods(t *testing.T) { - classificationID := base.NewID("classificationID") - identityID := base.NewID("identityID") - properties := base.NewProperties(base.NewProperty(base.NewID("ID"), base.NewFact(base.NewStringData("MutableData")))) - - testMaintainerID := key.NewMaintainerID(classificationID, identityID) - - testMaintainer := NewMaintainer(testMaintainerID, properties, true, true, true).(Maintainer) - - require.Equal(t, Maintainer{ID: testMaintainerID, MaintainedProperties: properties, AddMaintainer: true, RemoveMaintainer: true, MutateMaintainer: true}, testMaintainer) - require.Equal(t, testMaintainerID, testMaintainer.GetID()) - require.Equal(t, classificationID, testMaintainer.GetClassificationID()) - require.Equal(t, identityID, testMaintainer.GetIdentityID()) - require.Equal(t, true, testMaintainer.CanAddMaintainer()) - require.Equal(t, true, testMaintainer.CanMutateMaintainer()) - require.Equal(t, true, testMaintainer.CanRemoveMaintainer()) - require.Equal(t, true, testMaintainer.MaintainsProperty(base.NewID("ID"))) - require.Equal(t, false, testMaintainer.MaintainsProperty(base.NewID("ID2"))) - require.Equal(t, testMaintainerID, testMaintainer.GetKey()) -} diff --git a/modules/maintainers/internal/mappable/mappable.go b/modules/maintainers/internal/mappable/mappable.go new file mode 100644 index 000000000..8249bec5d --- /dev/null +++ b/modules/maintainers/internal/mappable/mappable.go @@ -0,0 +1,45 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mappable + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/maintainers/internal/key" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/ids/constansts" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + constantProperties "github.com/AssetMantle/modules/schema/properties/constants" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +type mappable struct { + documents.Maintainer +} + +var _ helpers.Mappable = (*mappable)(nil) + +func (mappable mappable) GetKey() helpers.Key { + return key.NewKey(base.NewMaintainerID(constansts.MaintainerClassificationID, + baseQualified.NewImmutables(baseLists.NewPropertyList( + baseProperties.NewMetaProperty(constantProperties.MaintainedClassificationIDProperty.GetKey(), baseData.NewIDData(mappable.Maintainer.GetMaintainedClassificationID())), + baseProperties.NewMetaProperty(constantProperties.IdentityIDProperty.GetKey(), baseData.NewIDData(mappable.Maintainer.GetIdentityID())), + )))) +} +func (mappable) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, mappable{}) +} + +func NewMappable(maintainer documents.Maintainer) helpers.Mappable { + return mappable{Maintainer: maintainer} +} + +func Prototype() helpers.Mappable { + return mappable{} +} diff --git a/modules/maintainers/internal/mappable/mappable_test.go b/modules/maintainers/internal/mappable/mappable_test.go index 1d8614289..b59565958 100644 --- a/modules/maintainers/internal/mappable/mappable_test.go +++ b/modules/maintainers/internal/mappable/mappable_test.go @@ -4,11 +4,12 @@ package mappable import ( - "github.com/AssetMantle/modules/schema/ids/constansts" - constantProperties "github.com/AssetMantle/modules/schema/properties/constants" "reflect" "testing" + "github.com/AssetMantle/modules/schema/ids/constansts" + constantProperties "github.com/AssetMantle/modules/schema/properties/constants" + "github.com/cosmos/cosmos-sdk/codec" "github.com/AssetMantle/modules/modules/maintainers/internal/key" diff --git a/modules/maintainers/internal/mappable/prototype.go b/modules/maintainers/internal/mappable/prototype.go deleted file mode 100644 index 8a03b03d5..000000000 --- a/modules/maintainers/internal/mappable/prototype.go +++ /dev/null @@ -1,12 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import "github.com/persistenceOne/persistenceSDK/schema/helpers" - -func Prototype() helpers.Mappable { - return &Maintainer{} -} diff --git a/modules/maintainers/internal/mapper/prototype.go b/modules/maintainers/internal/mapper/prototype.go new file mode 100644 index 000000000..7e715f128 --- /dev/null +++ b/modules/maintainers/internal/mapper/prototype.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mapper + +import ( + "github.com/AssetMantle/modules/modules/maintainers/internal/key" + "github.com/AssetMantle/modules/modules/maintainers/internal/mappable" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Mapper { + return baseHelpers.NewMapper(key.Prototype, mappable.Prototype) +} diff --git a/modules/maintainers/internal/module/constants.go b/modules/maintainers/internal/module/constants.go new file mode 100644 index 000000000..13d65843d --- /dev/null +++ b/modules/maintainers/internal/module/constants.go @@ -0,0 +1,12 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package module + +import ( + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +const Name = "maintainers" + +var StoreKeyPrefix = constants.MaintainersStoreKeyPrefix diff --git a/modules/maintainers/internal/parameters/dummy/constants.go b/modules/maintainers/internal/parameters/dummy/constants.go new file mode 100644 index 000000000..770f437dc --- /dev/null +++ b/modules/maintainers/internal/parameters/dummy/constants.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package dummy + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +var ID = baseIDs.NewStringID("dummy") + +var DefaultData = baseData.NewDecData(sdkTypes.SmallestDec()) diff --git a/modules/maintainers/internal/parameters/dummy/parameter.go b/modules/maintainers/internal/parameters/dummy/parameter.go index e78fdc8d0..5ffc0eaf5 100644 --- a/modules/maintainers/internal/parameters/dummy/parameter.go +++ b/modules/maintainers/internal/parameters/dummy/parameter.go @@ -1,59 +1,10 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "encoding/json" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" ) -var _ types.Parameter = (*DummyParameter)(nil) - -func (dummyParameter DummyParameter) String() string { - bytes, Error := json.Marshal(dummyParameter) - if Error != nil { - return Error.Error() - } - return string(bytes) -} - -func (dummyParameter DummyParameter) Equal(compareParameter types.Parameter) bool { - if compareParameter == nil { - return false - } - return dummyParameter.Data.Compare(compareParameter.GetData()) == 0 -} - -func (dummyParameter DummyParameter) Validate() error { - return validator(dummyParameter) -} - -func (dummyParameter DummyParameter) GetID() types.ID { - return &dummyParameter.ID -} - -func (dummyParameter DummyParameter) GetData() types.Data { - return &dummyParameter.Data -} - -func (dummyParameter DummyParameter) GetValidator() func(interface{}) error { - return validator -} - -func (dummyParameter DummyParameter) Mutate(data types.Data) types.Parameter { - decData, _ := data.AsDec() - dummyParameter.Data = *base.NewDummyDecData(decData) - return &dummyParameter -} - -func NewParameter(id types.ID, data types.Data) *DummyParameter { - decData, _ := data.AsDec() - return &DummyParameter{ - ID: *base.NewID(id.String()), - Data: *base.NewDummyDecData(decData), - } -} +var Parameter = baseTypes.NewParameter(ID, DefaultData, validator) diff --git a/modules/maintainers/internal/parameters/dummy/parameter.pb.go b/modules/maintainers/internal/parameters/dummy/parameter.pb.go deleted file mode 100644 index 9db2bfc32..000000000 --- a/modules/maintainers/internal/parameters/dummy/parameter.pb.go +++ /dev/null @@ -1,368 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/maintainers/internal/parameters/dummy/parameter.proto - -package dummy - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type DummyParameter struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - Data base.DecData `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` -} - -func (m *DummyParameter) Reset() { *m = DummyParameter{} } -func (*DummyParameter) ProtoMessage() {} -func (*DummyParameter) Descriptor() ([]byte, []int) { - return fileDescriptor_b2c2b1a3ba5352f7, []int{0} -} -func (m *DummyParameter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DummyParameter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DummyParameter.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DummyParameter) XXX_Merge(src proto.Message) { - xxx_messageInfo_DummyParameter.Merge(m, src) -} -func (m *DummyParameter) XXX_Size() int { - return m.Size() -} -func (m *DummyParameter) XXX_DiscardUnknown() { - xxx_messageInfo_DummyParameter.DiscardUnknown(m) -} - -var xxx_messageInfo_DummyParameter proto.InternalMessageInfo - -func init() { - proto.RegisterType((*DummyParameter)(nil), "persistence_sdk.modules.maintainers.internal.parameters.dummy.DummyParameter") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/maintainers/internal/parameters/dummy/parameter.proto", fileDescriptor_b2c2b1a3ba5352f7) -} - -var fileDescriptor_b2c2b1a3ba5352f7 = []byte{ - // 306 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0xd1, 0x31, 0x4b, 0x03, 0x31, - 0x14, 0x07, 0xf0, 0xa4, 0x16, 0x91, 0x13, 0x1c, 0x8a, 0x43, 0xe9, 0x90, 0x8a, 0x20, 0x48, 0x87, - 0x04, 0x74, 0x13, 0x5d, 0x4a, 0x16, 0x11, 0x51, 0x14, 0x1c, 0x5c, 0x4a, 0x7a, 0x79, 0xb4, 0xc1, - 0x26, 0x39, 0x2e, 0xe9, 0xd0, 0x6f, 0xe0, 0xe8, 0xe8, 0x24, 0xfd, 0x38, 0x1d, 0x3b, 0x3a, 0x89, - 0xdc, 0x7d, 0x11, 0xb9, 0xdc, 0x95, 0x1e, 0xb7, 0xa8, 0x5b, 0xf2, 0xc8, 0xff, 0x97, 0x97, 0x97, - 0xe8, 0x36, 0x81, 0xd4, 0x29, 0xe7, 0xc1, 0xc4, 0x30, 0x72, 0xf2, 0x85, 0x69, 0x2b, 0xe7, 0x33, - 0x70, 0x4c, 0x0b, 0x65, 0xbc, 0x50, 0x06, 0x52, 0xc7, 0x94, 0xf1, 0x90, 0x1a, 0x31, 0x63, 0x89, - 0x48, 0x85, 0x06, 0x5f, 0xd4, 0xe4, 0x5c, 0xeb, 0xc5, 0xb6, 0x40, 0x93, 0xd4, 0x7a, 0xdb, 0xb9, - 0x6a, 0x70, 0xb4, 0xe2, 0x68, 0x8d, 0xa3, 0x1b, 0x8e, 0x6e, 0x39, 0x1a, 0xb8, 0xde, 0xe1, 0xc4, - 0x4e, 0x6c, 0x90, 0x58, 0xb1, 0x2a, 0xd1, 0x1e, 0x6b, 0xf6, 0xe8, 0xe2, 0x29, 0x68, 0xc1, 0xfc, - 0x22, 0x01, 0xc7, 0xc6, 0xc2, 0x01, 0x93, 0x10, 0x73, 0xe1, 0x45, 0x15, 0x18, 0xfc, 0x1e, 0x50, - 0xb2, 0x3c, 0x7b, 0xfc, 0x81, 0xa3, 0x03, 0x5e, 0x5c, 0x7e, 0xbf, 0x69, 0xa6, 0x73, 0x19, 0xed, - 0xa8, 0x91, 0xec, 0xe2, 0x23, 0x7c, 0xba, 0x7f, 0x76, 0x42, 0x9b, 0x4f, 0x2a, 0x31, 0x1a, 0x30, - 0x5a, 0x60, 0xf4, 0x9a, 0x0f, 0xdb, 0xab, 0xaf, 0x3e, 0x7a, 0x68, 0x29, 0xde, 0xe1, 0x51, 0x5b, - 0x0a, 0x2f, 0xba, 0xad, 0x10, 0x1f, 0xfc, 0x21, 0xce, 0xcb, 0xe6, 0x2b, 0x23, 0xa4, 0x2f, 0xf6, - 0x5e, 0x97, 0x7d, 0xf4, 0xbe, 0xec, 0xa3, 0x61, 0xb2, 0xca, 0x08, 0x5e, 0x67, 0x04, 0x7f, 0x67, - 0x04, 0xbf, 0xe5, 0x04, 0xad, 0x73, 0x82, 0x3e, 0x73, 0x82, 0x9e, 0x9f, 0x26, 0xca, 0x4f, 0xe7, - 0x63, 0x1a, 0x5b, 0x5d, 0x1f, 0xd1, 0x9d, 0x81, 0xfa, 0xf6, 0x91, 0xdf, 0xfc, 0xef, 0x53, 0xc7, - 0xbb, 0x61, 0x32, 0xe7, 0x3f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x70, 0x70, 0x6b, 0xf5, 0x1c, 0x02, - 0x00, 0x00, -} - -func (m *DummyParameter) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DummyParameter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DummyParameter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Data.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintParameter(dAtA []byte, offset int, v uint64) int { - offset -= sovParameter(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *DummyParameter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovParameter(uint64(l)) - l = m.Data.Size() - n += 1 + l + sovParameter(uint64(l)) - return n -} - -func sovParameter(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParameter(x uint64) (n int) { - return sovParameter(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *DummyParameter) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DummyParameter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DummyParameter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParameter(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParameter - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParameter(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParameter - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParameter - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParameter - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParameter = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParameter = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParameter = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/maintainers/internal/parameters/dummy/prototype.go b/modules/maintainers/internal/parameters/dummy/prototype.go deleted file mode 100644 index b390a673e..000000000 --- a/modules/maintainers/internal/parameters/dummy/prototype.go +++ /dev/null @@ -1,3 +0,0 @@ -package dummy - -var Parameter = NewParameter(ID, DefaultData) diff --git a/modules/maintainers/internal/parameters/dummy/validator.go b/modules/maintainers/internal/parameters/dummy/validator.go index cc0d80a52..2bb100018 100644 --- a/modules/maintainers/internal/parameters/dummy/validator.go +++ b/modules/maintainers/internal/parameters/dummy/validator.go @@ -1,32 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/parameters" ) func validator(i interface{}) error { switch value := i.(type) { - case DummyParameter: - data, Error := value.GetData().AsDec() - if Error != nil || value.GetID().Compare(ID) != 0 || data.IsNegative() { - return errors.InvalidParameter + case parameters.Parameter: + if value.GetID().Compare(ID) != 0 || value.GetData().(data.DecData).Get().IsNegative() { + return constants.InvalidParameter } return nil - case types.Data: - data, Error := value.AsDec() - if Error != nil || data.IsNegative() { - return errors.InvalidParameter + case data.DecData: + if value.Get().IsNegative() { + return constants.InvalidParameter } return nil default: - return errors.IncorrectFormat + return constants.IncorrectFormat } } diff --git a/modules/maintainers/internal/parameters/dummy/validator_test.go b/modules/maintainers/internal/parameters/dummy/validator_test.go new file mode 100644 index 000000000..6915a0b78 --- /dev/null +++ b/modules/maintainers/internal/parameters/dummy/validator_test.go @@ -0,0 +1,21 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package dummy + +import ( + "testing" + + "github.com/stretchr/testify/require" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/errors/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" +) + +func Test_Validator(t *testing.T) { + require.Equal(t, constants.IncorrectFormat, validator(baseIDs.NewStringID(""))) + require.Equal(t, nil, validator(Parameter)) + require.Equal(t, constants.InvalidParameter, validator(baseTypes.NewParameter(baseIDs.NewStringID(""), baseData.NewStringData(""), validator))) +} diff --git a/modules/maintainers/internal/parameters/prototype.go b/modules/maintainers/internal/parameters/prototype.go new file mode 100644 index 000000000..94c7194cb --- /dev/null +++ b/modules/maintainers/internal/parameters/prototype.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package parameters + +import ( + "github.com/AssetMantle/modules/modules/maintainers/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Parameters { + return baseHelpers.NewParameters(dummy.Parameter) +} diff --git a/modules/maintainers/internal/parameters/prototype_test.go b/modules/maintainers/internal/parameters/prototype_test.go new file mode 100644 index 000000000..4ee248e27 --- /dev/null +++ b/modules/maintainers/internal/parameters/prototype_test.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package parameters + +import ( + "fmt" + "reflect" + "testing" + + "github.com/AssetMantle/modules/modules/maintainers/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Parameters + }{ + {"+ve", baseHelpers.NewParameters(dummy.Parameter)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype(); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/maintainers/internal/queries/maintainer/grpc_query.go b/modules/maintainers/internal/queries/maintainer/grpc_query.go deleted file mode 100644 index 54bee9d69..000000000 --- a/modules/maintainers/internal/queries/maintainer/grpc_query.go +++ /dev/null @@ -1,29 +0,0 @@ -package maintainer - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/key" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type queryServer struct { - queryKeeper -} - -var _ QueryServer = queryServer{} - -func (queryServer queryServer) Enquire(ctx context.Context, queryRequest *QueryRequest) (*QueryResponse, error) { - cntx := sdkTypes.UnwrapSDKContext(ctx) - - keyr := key.FromID(base.NewID(queryRequest.MaintainerID.String())) - - collection := queryServer.queryKeeper.mapper.NewCollection(cntx) - response := newQueryResponse(collection.Fetch(keyr), nil) - return &response, response.GetError() - -} - -func NewQueryServerImpl(keeper queryKeeper) QueryServer { - return &queryServer{keeper} -} diff --git a/modules/maintainers/internal/queries/maintainer/keeper.go b/modules/maintainers/internal/queries/maintainer/keeper.go new file mode 100644 index 000000000..3b6bc6dc7 --- /dev/null +++ b/modules/maintainers/internal/queries/maintainer/keeper.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package maintainer + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/maintainers/internal/key" + "github.com/AssetMantle/modules/schema/helpers" +) + +type queryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.QueryKeeper = (*queryKeeper)(nil) + +func (queryKeeper queryKeeper) Enquire(context sdkTypes.Context, queryRequest helpers.QueryRequest) helpers.QueryResponse { + return newQueryResponse(queryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(queryRequestFromInterface(queryRequest).MaintainerID)), nil) +} + +func (queryKeeper queryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + queryKeeper.mapper = mapper + return queryKeeper +} + +func keeperPrototype() helpers.QueryKeeper { + return queryKeeper{} +} diff --git a/modules/maintainers/internal/queries/maintainer/keeper_test.go b/modules/maintainers/internal/queries/maintainer/keeper_test.go new file mode 100644 index 000000000..331855fb7 --- /dev/null +++ b/modules/maintainers/internal/queries/maintainer/keeper_test.go @@ -0,0 +1,166 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package maintainer + +import ( + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/maintainers/internal/key" + "github.com/AssetMantle/modules/modules/maintainers/internal/mappable" + "github.com/AssetMantle/modules/modules/maintainers/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type TestKeepers struct { + MaintainerKeeper helpers.QueryKeeper +} + +func createTestData() (ids.MaintainerID, documents.Maintainer) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testIdentityID := baseIDs.NewIdentityID(testClassificationID, immutables) + testMaintainerID := baseIDs.NewMaintainerID(testClassificationID, immutables) + testMaintainedPropertyID := baseLists.NewIDList(baseIDs.NewStringID("maintainer")) + testMaintainer := base.NewMaintainer(testIdentityID, testClassificationID, testMaintainedPropertyID, testMaintainedPropertyID) + return testMaintainerID, testMaintainer +} + +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + keepers := TestKeepers{ + MaintainerKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.QueryKeeper), + } + + return context, keepers, Mapper, Parameters +} + +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryKeeper + }{ + {"+ve", queryKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryKeeper_Enquire(t *testing.T) { + context, keepers, Mapper, _ := createTestInput(t) + testMaintainerID, testMaintainer := createTestData() + keepers.MaintainerKeeper.(queryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testMaintainer)) + type fields struct { + mapper helpers.Mapper + } + type args struct { + context sdkTypes.Context + queryRequest helpers.QueryRequest + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryResponse + }{ + {"+ve", fields{Mapper}, args{context, newQueryRequest(testMaintainerID)}, newQueryResponse(keepers.MaintainerKeeper.(queryKeeper).mapper.NewCollection(context).Fetch(key.NewKey(testMaintainerID)), nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryKeeper := queryKeeper{ + mapper: tt.fields.mapper, + } + if got := queryKeeper.Enquire(tt.args.context, tt.args.queryRequest); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Enquire() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + in2 []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper}, args{Mapper, Parameters, []interface{}{}}, queryKeeper{Mapper}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryKeeper := queryKeeper{ + mapper: tt.fields.mapper, + } + if got := queryKeeper.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/maintainers/internal/queries/maintainer/query.go b/modules/maintainers/internal/queries/maintainer/query.go new file mode 100644 index 000000000..12f8e7ae7 --- /dev/null +++ b/modules/maintainers/internal/queries/maintainer/query.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package maintainer + +import ( + "github.com/AssetMantle/modules/modules/maintainers/internal/module" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Query = baseHelpers.NewQuery( + "maintainers", + "", + "", + + module.Name, + + requestPrototype, + responsePrototype, + keeperPrototype, + + constants.MaintainerID, +) diff --git a/modules/maintainers/internal/queries/maintainer/query.pb.go b/modules/maintainers/internal/queries/maintainer/query.pb.go deleted file mode 100644 index 04f4aea33..000000000 --- a/modules/maintainers/internal/queries/maintainer/query.pb.go +++ /dev/null @@ -1,674 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/maintainers/internal/queries/maintainer/query.proto - -package maintainer - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - github_com_persistenceOne_persistenceSDK_schema_helpers "github.com/persistenceOne/persistenceSDK/schema/helpers" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type QueryRequest struct { - MaintainerID base.ID `protobuf:"bytes,1,opt,name=maintainer_i_d,json=maintainerID,proto3" json:"maintainer_i_d" valid:"required~required MaintainerID missing"` -} - -func (m *QueryRequest) Reset() { *m = QueryRequest{} } -func (m *QueryRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRequest) ProtoMessage() {} -func (*QueryRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_39d25d2876f851a0, []int{0} -} -func (m *QueryRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRequest.Merge(m, src) -} -func (m *QueryRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRequest proto.InternalMessageInfo - -type QueryResponse struct { - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` - List []github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable `protobuf:"bytes,3,rep,name=list,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable" json:"list"` -} - -func (m *QueryResponse) Reset() { *m = QueryResponse{} } -func (m *QueryResponse) String() string { return proto.CompactTextString(m) } -func (*QueryResponse) ProtoMessage() {} -func (*QueryResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_39d25d2876f851a0, []int{1} -} -func (m *QueryResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryResponse.Merge(m, src) -} -func (m *QueryResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryRequest)(nil), "persistence_sdk.modules.maintainers.internal.queries.maintainer.QueryRequest") - proto.RegisterType((*QueryResponse)(nil), "persistence_sdk.modules.maintainers.internal.queries.maintainer.QueryResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/maintainers/internal/queries/maintainer/query.proto", fileDescriptor_39d25d2876f851a0) -} - -var fileDescriptor_39d25d2876f851a0 = []byte{ - // 470 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x93, 0xc1, 0x6b, 0xd4, 0x40, - 0x14, 0xc6, 0x33, 0xad, 0xb5, 0x6d, 0xac, 0x1e, 0x42, 0x0f, 0xcb, 0x22, 0x49, 0x88, 0x14, 0x16, - 0x85, 0x19, 0xa8, 0xe0, 0xa1, 0x17, 0x65, 0x59, 0xc1, 0x52, 0x56, 0x31, 0x5e, 0x44, 0x84, 0x65, - 0x36, 0x79, 0x64, 0x07, 0x93, 0x99, 0xec, 0xbc, 0x89, 0xd0, 0x8b, 0x07, 0xbd, 0x78, 0x14, 0xbc, - 0x4b, 0x6f, 0xfe, 0x2b, 0x3d, 0x16, 0x44, 0x10, 0x0f, 0xab, 0xec, 0x7a, 0xf0, 0xec, 0x5f, 0x20, - 0x49, 0x76, 0xdd, 0x74, 0x4f, 0x8a, 0xbd, 0xbd, 0xf7, 0xbe, 0xf0, 0xcb, 0xf7, 0xbd, 0xbc, 0xd8, - 0x47, 0x39, 0x68, 0x14, 0x68, 0x40, 0x46, 0x30, 0xc0, 0xf8, 0x05, 0xcb, 0x54, 0x5c, 0xa4, 0x80, - 0x2c, 0xe3, 0x42, 0x1a, 0x2e, 0x24, 0x68, 0x64, 0x42, 0x1a, 0xd0, 0x92, 0xa7, 0x6c, 0x5c, 0x80, - 0x16, 0xe7, 0xc4, 0x6a, 0x74, 0x4c, 0x73, 0xad, 0x8c, 0x72, 0xee, 0xae, 0xc0, 0xe8, 0x1c, 0x46, - 0x1b, 0x30, 0xba, 0x80, 0xd1, 0x39, 0xac, 0x21, 0xb6, 0x77, 0x13, 0x95, 0xa8, 0x8a, 0xc5, 0xca, - 0xaa, 0xc6, 0xb6, 0xaf, 0x27, 0x4a, 0x25, 0x29, 0x30, 0x9e, 0x0b, 0xc6, 0xa5, 0x54, 0x86, 0x1b, - 0xa1, 0x24, 0xce, 0xd5, 0x9b, 0xab, 0x09, 0x30, 0x1a, 0x41, 0xc6, 0x99, 0x39, 0xce, 0x01, 0xd9, - 0x90, 0x23, 0x30, 0x11, 0xd7, 0xcf, 0x06, 0x1f, 0x88, 0xbd, 0xf3, 0xb8, 0x34, 0x1c, 0xc2, 0xb8, - 0x00, 0x34, 0xce, 0x1b, 0x62, 0x5f, 0x5b, 0xbe, 0x7f, 0x20, 0x06, 0x71, 0x8b, 0xf8, 0xa4, 0x73, - 0x65, 0x7f, 0x8f, 0xae, 0x66, 0xa9, 0xb1, 0xb4, 0xc2, 0xd2, 0x12, 0x4b, 0x0f, 0x7b, 0xdd, 0x3b, - 0xa7, 0x13, 0xcf, 0xfa, 0x35, 0xf1, 0xe8, 0x4b, 0x9e, 0x8a, 0xf8, 0x20, 0xd0, 0x30, 0x2e, 0x84, - 0x86, 0xf8, 0xd5, 0xa2, 0xf0, 0xfb, 0x7f, 0xe8, 0x87, 0x3d, 0x3f, 0x13, 0x88, 0x42, 0x26, 0x41, - 0xb8, 0x93, 0x35, 0xc6, 0x07, 0x5b, 0x6f, 0x4f, 0x3c, 0xeb, 0xe7, 0x89, 0x67, 0x05, 0x1f, 0x89, - 0x7d, 0x75, 0x6e, 0x10, 0x73, 0x25, 0x11, 0x9c, 0x96, 0xbd, 0x89, 0x45, 0x14, 0x01, 0x62, 0xe5, - 0x6c, 0x2b, 0x5c, 0xb4, 0xce, 0xae, 0xbd, 0x01, 0x5a, 0x2b, 0xdd, 0x5a, 0xf3, 0x49, 0x67, 0x3b, - 0xac, 0x1b, 0xe7, 0xb9, 0x7d, 0x29, 0x15, 0x68, 0x5a, 0xeb, 0xfe, 0x7a, 0x67, 0xbb, 0xfb, 0xa0, - 0xf4, 0xf7, 0x75, 0xe2, 0xdd, 0x4b, 0x84, 0x19, 0x15, 0x43, 0x1a, 0xa9, 0x8c, 0x35, 0x82, 0x3d, - 0x92, 0xd0, 0x6c, 0x9f, 0xf4, 0x8e, 0x16, 0xdb, 0x1b, 0x41, 0x5a, 0x0a, 0xb4, 0xcf, 0xf3, 0x9c, - 0x0f, 0x53, 0x08, 0x2b, 0xea, 0xd2, 0xe9, 0xfe, 0x37, 0x62, 0x6f, 0x54, 0x4e, 0x9d, 0xcf, 0xc4, - 0xde, 0xbc, 0x2f, 0xab, 0xb8, 0x4e, 0x9f, 0xfe, 0xe7, 0x09, 0xd0, 0xe6, 0xe7, 0x69, 0x3f, 0xbc, - 0x28, 0x5c, 0xbd, 0xcc, 0xe0, 0xd6, 0xeb, 0x4f, 0x3f, 0xde, 0xaf, 0xed, 0x39, 0x37, 0x9a, 0xa9, - 0xcf, 0x9d, 0xfa, 0xb2, 0xee, 0xea, 0xd3, 0xa9, 0x4b, 0xce, 0xa6, 0x2e, 0xf9, 0x3e, 0x75, 0xc9, - 0xbb, 0x99, 0x6b, 0x9d, 0xcd, 0x5c, 0xeb, 0xcb, 0xcc, 0xb5, 0x9e, 0x3d, 0xfd, 0xeb, 0x6d, 0xfe, - 0xe3, 0xdf, 0x34, 0xbc, 0x5c, 0xdd, 0xe9, 0xed, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xe8, 0xec, - 0xb1, 0x84, 0x97, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) { - out := new(QueryResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.maintainers.internal.queries.maintainer.Query/Enquire", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - Enquire(context.Context, *QueryRequest) (*QueryResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Enquire(ctx context.Context, req *QueryRequest) (*QueryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Enquire not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Enquire_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Enquire(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.maintainers.internal.queries.maintainer.Query/Enquire", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Enquire(ctx, req.(*QueryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.maintainers.internal.queries.maintainer.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Enquire", - Handler: _Query_Enquire_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/maintainers/internal/queries/maintainer/query.proto", -} - -func (m *QueryRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MaintainerID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.List) > 0 { - for iNdEx := len(m.List) - 1; iNdEx >= 0; iNdEx-- { - { - size := m.List[iNdEx].Size() - i -= size - if _, err := m.List[iNdEx].MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Error) > 0 { - i -= len(m.Error) - copy(dAtA[i:], m.Error) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Error))) - i-- - dAtA[i] = 0x12 - } - if m.Success { - i-- - if m.Success { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.MaintainerID.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Success { - n += 2 - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.List) > 0 { - for _, e := range m.List { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaintainerID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MaintainerID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Success = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field List", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var v github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable - m.List = append(m.List, v) - if err := m.List[len(m.List)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/maintainers/internal/queries/maintainer/query.pb.gw.go b/modules/maintainers/internal/queries/maintainer/query.pb.gw.go deleted file mode 100644 index 4c18c0bab..000000000 --- a/modules/maintainers/internal/queries/maintainer/query.pb.gw.go +++ /dev/null @@ -1,166 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: persistence_sdk/modules/maintainers/internal/queries/maintainer/query.proto - -/* -Package maintainer is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package maintainer - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage - -var ( - filter_Query_Enquire_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Enquire(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Enquire(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features (such as grpc.SendHeader, etc) to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Enquire_0(rctx, inboundMarshaler, server, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Enquire_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Enquire_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"persistence", "maintainers", "maintainer"}, "", runtime.AssumeColonVerbOpt(true))) -) - -var ( - forward_Query_Enquire_0 = runtime.ForwardResponseMessage -) diff --git a/modules/maintainers/internal/queries/maintainer/request.go b/modules/maintainers/internal/queries/maintainer/request.go index 6ddc15b72..6ff1a145d 100644 --- a/modules/maintainers/internal/queries/maintainer/request.go +++ b/modules/maintainers/internal/queries/maintainer/request.go @@ -1,81 +1,80 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package maintainer import ( "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/cosmos/cosmos-sdk/client/context" + + "github.com/AssetMantle/modules/modules/maintainers/internal/common" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" ) -var _ helpers.QueryRequest = (*QueryRequest)(nil) +type queryRequest struct { + ids.MaintainerID `json:"maintainerID" valid:"required~required field maintainerID missing"` +} + +var _ helpers.QueryRequest = (*queryRequest)(nil) -// QueryRequest godoc -// @Summary Query maintainers using maintainer id -// @Descrption Able to query the maintainers details +// Validate godoc +// @Summary Search for a maintainer by maintainer ID +// @Description Able to query the maintainers details // @Accept json // @Produce json // @Tags Maintainers -// @Param maintainerID path string true "maintainer ID" -// @Success 200 {object} queryResponse "A successful query response" -// @Failure default {object} queryResponse "An unexpected error response." +// @Param maintainerID path string true "Unique identifier of a maintainer." +// @Success 200 {object} queryResponse "Message for a successful query response" +// @Failure default {object} queryResponse "Message for an unexpected error response." // @Router /maintainers/maintainers/{maintainerID} [get] -func (queryRequest QueryRequest) Validate() error { - _, Error := govalidator.ValidateStruct(queryRequest) - return Error -} - -func (queryRequest QueryRequest) FromCLI(cliCommand helpers.CLICommand, _ client.Context) helpers.QueryRequest { - return newQueryRequest(base.NewID(cliCommand.ReadString(flags.MaintainerID))) +func (queryRequest queryRequest) Validate() error { + _, err := govalidator.ValidateStruct(queryRequest) + return err } -func (queryRequest QueryRequest) FromMap(vars map[string]string) helpers.QueryRequest { - return newQueryRequest(base.NewID(vars[Query.GetName()])) -} -func (queryRequest QueryRequest) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryRequest) +func (queryRequest) FromCLI(cliCommand helpers.CLICommand, _ context.CLIContext) (helpers.QueryRequest, error) { + if maintainerID, err := baseIDs.ReadMaintainerID(cliCommand.ReadString(constants.MaintainerID)); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(maintainerID), nil + } } -func (queryRequest QueryRequest) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryRequest, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest) FromMap(vars map[string]string) (helpers.QueryRequest, error) { + if maintainerID, err := baseIDs.ReadMaintainerID(vars[Query.GetName()]); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(maintainerID), nil } - - return queryRequest, nil } -func (queryRequest QueryRequest) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryRequest) +func (queryRequest queryRequest) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryRequest) } -func (queryRequest QueryRequest) LegacyAminoDecode(bytes []byte) (helpers.QueryRequest, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest queryRequest) Decode(bytes []byte) (helpers.QueryRequest, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryRequest); err != nil { + return nil, err } return queryRequest, nil } func requestPrototype() helpers.QueryRequest { - return QueryRequest{} + return queryRequest{} } -func queryRequestFromInterface(request helpers.QueryRequest) QueryRequest { +func queryRequestFromInterface(request helpers.QueryRequest) queryRequest { switch value := request.(type) { - case QueryRequest: + case queryRequest: return value default: - return QueryRequest{} + return queryRequest{} } } -func newQueryRequest(maintainerID types.ID) helpers.QueryRequest { - return QueryRequest{MaintainerID: *base.NewID(maintainerID.String())} +func newQueryRequest(maintainerID ids.MaintainerID) helpers.QueryRequest { + return queryRequest{MaintainerID: maintainerID} } diff --git a/modules/maintainers/internal/queries/maintainer/request_test.go b/modules/maintainers/internal/queries/maintainer/request_test.go index b3f5c8a1b..c2fa69d02 100644 --- a/modules/maintainers/internal/queries/maintainer/request_test.go +++ b/modules/maintainers/internal/queries/maintainer/request_test.go @@ -1,59 +1,254 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package maintainer import ( - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/common" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/spf13/viper" + + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/maintainers/internal/common" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIds "github.com/AssetMantle/modules/schema/ids/base" +) + +var ( + testMaintainerID, _ = createTestData() + testMaintainerID1 = baseIds.PrototypeMaintainerID() ) -func Test_Maintainer_Request(t *testing.T) { +func Test_newQueryRequest(t *testing.T) { + type args struct { + maintainerID ids.MaintainerID + } + tests := []struct { + name string + args args + want helpers.QueryRequest + }{ + {"+ve", args{testMaintainerID}, queryRequest{testMaintainerID}}, + {"+ve with nil", args{testMaintainerID1}, queryRequest{testMaintainerID1}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newQueryRequest(tt.args.maintainerID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newQueryRequest() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequestFromInterface(t *testing.T) { + type args struct { + request helpers.QueryRequest + } + tests := []struct { + name string + args args + want queryRequest + }{ + {"+ve", args{newQueryRequest(testMaintainerID)}, queryRequest{testMaintainerID}}, + {"+ve with nil", args{newQueryRequest(testMaintainerID1)}, queryRequest{testMaintainerID1}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := queryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("queryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() +func Test_queryRequest_Decode(t *testing.T) { + encodedQuery, err := queryRequest{testMaintainerID}.Encode() + require.NoError(t, err) + encodedQuery1, err := queryRequest{testMaintainerID1}.Encode() + require.NoError(t, err) + type fields struct { + MaintainerID ids.MaintainerID + } + type args struct { + bytes []byte + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testMaintainerID}, args{encodedQuery}, queryRequest{testMaintainerID}, false}, + {"+ve", fields{testMaintainerID1}, args{encodedQuery1}, queryRequest{testMaintainerID1}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + MaintainerID: tt.fields.MaintainerID, + } + got, err := queryRequest.Decode(tt.args.bytes) + if (err != nil) != tt.wantErr { + t.Errorf("Decode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Decode() got = %v, want %v", got, tt.want) + } + }) + } +} - testMaintainerID := base.NewID("MaintainerID") - testQueryRequest := newQueryRequest(testMaintainerID) - require.Equal(t, nil, testQueryRequest.Validate()) - require.Equal(t, queryRequest{}, requestPrototype()) +func Test_queryRequest_Encode(t *testing.T) { + encodedQuery, err := common.Codec.MarshalJSON(queryRequest{testMaintainerID}) + require.NoError(t, err) + encodedQuery1, err := common.Codec.MarshalJSON(queryRequest{testMaintainerID1}) + require.NoError(t, err) + type fields struct { + MaintainerID ids.MaintainerID + } + tests := []struct { + name string + fields fields + want []byte + wantErr bool + }{ + {"+ve", fields{testMaintainerID}, encodedQuery, false}, + {"+ve with nil", fields{testMaintainerID1}, encodedQuery1, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + MaintainerID: tt.fields.MaintainerID, + } + got, err := queryRequest.Encode() + if (err != nil) != tt.wantErr { + t.Errorf("Encode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Encode() got = %v, want %v", got, tt.want) + } + }) + } +} - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.MaintainerID}) - cliContext := context.NewCLIContext().WithCodec(Codec) - require.Equal(t, newQueryRequest(base.NewID("")), queryRequest{}.FromCLI(cliCommand, cliContext)) +func Test_queryRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.MaintainerID}) + viper.Set(constants.MaintainerID.GetName(), testMaintainerID.String()) + type fields struct { + MaintainerID ids.MaintainerID + } + type args struct { + cliCommand helpers.CLICommand + in1 context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testMaintainerID}, args{cliCommand, context.NewCLIContext()}, queryRequest{testMaintainerID}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + MaintainerID: tt.fields.MaintainerID, + } + got, err := qu.FromCLI(tt.args.cliCommand, tt.args.in1) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} +func Test_queryRequest_FromMap(t *testing.T) { vars := make(map[string]string) - vars["maintainers"] = "randomString" - require.Equal(t, newQueryRequest(base.NewID("randomString")), queryRequest{}.FromMap(vars)) - - encodedRequest, Error := testQueryRequest.LegacyAminoEncode() - encodedResult, _ := common.LegacyAminoCodec.MarshalJSON(testQueryRequest) - require.Equal(t, encodedResult, encodedRequest) - require.Nil(t, Error) - - decodedRequest, Error := queryRequest{}.LegacyAminoDecode(encodedRequest) - require.Equal(t, testQueryRequest, decodedRequest) - require.Equal(t, nil, Error) - - randomDecode, _ := queryRequest{}.LegacyAminoDecode(base.NewID("").Bytes()) - require.Equal(t, nil, randomDecode) - require.Equal(t, testQueryRequest, queryRequestFromInterface(testQueryRequest)) - require.Equal(t, queryRequest{}, queryRequestFromInterface(nil)) + vars[Query.GetName()] = testMaintainerID.String() + vars1 := make(map[string]string) + vars1[Query.GetName()] = testMaintainerID.String() + type fields struct { + MaintainerID ids.MaintainerID + } + type args struct { + vars map[string]string + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testMaintainerID}, args{vars}, newQueryRequest(testMaintainerID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + MaintainerID: tt.fields.MaintainerID, + } + got, err := qu.FromMap(tt.args.vars) + if (err != nil) != tt.wantErr { + t.Errorf("FromMap() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromMap() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequest_Validate(t *testing.T) { + type fields struct { + MaintainerID ids.MaintainerID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testMaintainerID}, false}, + {"+ve with nil", fields{testMaintainerID1}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + MaintainerID: tt.fields.MaintainerID, + } + if err := queryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryRequest + }{ + {"+ve", queryRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/maintainers/internal/queries/maintainer/response.go b/modules/maintainers/internal/queries/maintainer/response.go index 372b511cb..5caa28283 100644 --- a/modules/maintainers/internal/queries/maintainer/response.go +++ b/modules/maintainers/internal/queries/maintainer/response.go @@ -1,64 +1,49 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package maintainer import ( - "errors" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/maintainers/internal/common" + "github.com/AssetMantle/modules/schema/helpers" ) -var _ helpers.QueryResponse = (*QueryResponse)(nil) +type queryResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` + List []helpers.Mappable `json:"list"` +} + +var _ helpers.QueryResponse = (*queryResponse)(nil) -func (queryResponse QueryResponse) IsSuccessful() bool { +func (queryResponse queryResponse) IsSuccessful() bool { return queryResponse.Success } -func (queryResponse QueryResponse) GetError() error { - return errors.New(queryResponse.Error) +func (queryResponse queryResponse) GetError() error { + return queryResponse.Error } -func (queryResponse QueryResponse) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryResponse) +func (queryResponse queryResponse) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryResponse) } -func (queryResponse QueryResponse) LegacyAminoDecode(bytes []byte) (helpers.QueryResponse, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error +func (queryResponse queryResponse) Decode(bytes []byte) (helpers.QueryResponse, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryResponse); err != nil { + return nil, err } - return &queryResponse, nil -} -func (queryResponse QueryResponse) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryResponse) -} - -func (queryResponse QueryResponse) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryResponse, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error - } - return &queryResponse, nil + return queryResponse, nil } - func responsePrototype() helpers.QueryResponse { - return &QueryResponse{} + return queryResponse{} } - -func newQueryResponse(collection helpers.Collection, error error) QueryResponse { +func newQueryResponse(collection helpers.Collection, error error) helpers.QueryResponse { success := true if error != nil { success = false - return QueryResponse{ - Success: success, - Error: "yes", - List: collection.GetList(), - } } - return QueryResponse{ + + return queryResponse{ Success: success, - Error: "no", + Error: error, List: collection.GetList(), } - } diff --git a/modules/maintainers/internal/queries/maintainer/response_test.go b/modules/maintainers/internal/queries/maintainer/response_test.go index 822773c1b..abdd00f33 100644 --- a/modules/maintainers/internal/queries/maintainer/response_test.go +++ b/modules/maintainers/internal/queries/maintainer/response_test.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package maintainer @@ -17,17 +15,17 @@ import ( "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/mapper" - "github.com/persistenceOne/persistenceSDK/schema" + "github.com/AssetMantle/modules/modules/maintainers/internal/common" + "github.com/AssetMantle/modules/modules/maintainers/internal/mapper" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/errors/constants" ) func CreateTestInput(t *testing.T) sdkTypes.Context { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() @@ -56,21 +54,21 @@ func Test_Maintainer_Response(t *testing.T) { collection := mapper.Prototype().NewCollection(context) testQueryResponse := newQueryResponse(collection, nil) - testQueryResponseWithError := newQueryResponse(collection, errors.IncorrectFormat) + testQueryResponseWithError := newQueryResponse(collection, constants.IncorrectFormat) require.Equal(t, true, testQueryResponse.IsSuccessful()) require.Equal(t, false, testQueryResponseWithError.IsSuccessful()) require.Equal(t, nil, testQueryResponse.GetError()) - require.Equal(t, errors.IncorrectFormat, testQueryResponseWithError.GetError()) + require.Equal(t, constants.IncorrectFormat, testQueryResponseWithError.GetError()) - encodedResponse, _ := testQueryResponse.LegacyAminoEncode() - bytes, _ := common.LegacyAminoCodec.MarshalJSON(testQueryResponse) + encodedResponse, _ := testQueryResponse.Encode() + bytes, _ := common.Codec.MarshalJSON(testQueryResponse) require.Equal(t, bytes, encodedResponse) - decodedResponse, _ := queryResponse{}.LegacyAminoDecode(bytes) + decodedResponse, _ := queryResponse{}.Decode(bytes) require.Equal(t, testQueryResponse, decodedResponse) - decodedResponse2, _ := queryResponse{}.LegacyAminoDecode([]byte{}) + decodedResponse2, _ := queryResponse{}.Decode([]byte{}) require.Equal(t, nil, decodedResponse2) require.Equal(t, queryResponse{}, responsePrototype()) diff --git a/modules/maintainers/internal/queries/prototype.go b/modules/maintainers/internal/queries/prototype.go new file mode 100644 index 000000000..8ab3b5c53 --- /dev/null +++ b/modules/maintainers/internal/queries/prototype.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queries + +import ( + "github.com/AssetMantle/modules/modules/maintainers/internal/queries/maintainer" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Queries { + return baseHelpers.NewQueries( + maintainer.Query, + ) +} diff --git a/modules/maintainers/internal/queries/prototype_test.go b/modules/maintainers/internal/queries/prototype_test.go new file mode 100644 index 000000000..0c2fc0fb6 --- /dev/null +++ b/modules/maintainers/internal/queries/prototype_test.go @@ -0,0 +1,21 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queries + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/maintainers/internal/queries/maintainer" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Panics(t, func() { + require.Equal(t, Prototype().Get("maintainer").GetName(), baseHelpers.NewQueries( + maintainer.Query, + ).Get("maintainer").GetName()) + }) +} diff --git a/modules/maintainers/internal/simulator/constants.go b/modules/maintainers/internal/simulator/constants.go new file mode 100644 index 000000000..0e23f0a61 --- /dev/null +++ b/modules/maintainers/internal/simulator/constants.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +const OpWeightSubmitTextProposal = "op_weight_submit_text_proposal" +const DefaultWeightTextProposal = 1 + +const OpWeightMsg = "OpWeightMsg" +const DefaultWeightMsg = 1 diff --git a/modules/maintainers/internal/simulator/genesis.go b/modules/maintainers/internal/simulator/genesis.go new file mode 100644 index 000000000..ee1a46ada --- /dev/null +++ b/modules/maintainers/internal/simulator/genesis.go @@ -0,0 +1,58 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "math/rand" + + "github.com/AssetMantle/modules/modules/maintainers/internal/utilities" + "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseSimulation "github.com/AssetMantle/modules/simulation/schema/types/base" + + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + + "github.com/AssetMantle/modules/utilities/random" + + "github.com/AssetMantle/modules/modules/maintainers/internal/common" + "github.com/AssetMantle/modules/modules/maintainers/internal/key" + "github.com/AssetMantle/modules/modules/maintainers/internal/mappable" + maintainersModule "github.com/AssetMantle/modules/modules/maintainers/internal/module" + "github.com/AssetMantle/modules/modules/maintainers/internal/parameters" + "github.com/AssetMantle/modules/modules/maintainers/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/data" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + parametersSchema "github.com/AssetMantle/modules/schema/parameters" +) + +func (simulator) RandomizedGenesisState(simulationState *module.SimulationState) { + var Data data.Data + + simulationState.AppParams.GetOrGenerate( + simulationState.Cdc, + dummy.ID.String(), + &Data, + simulationState.Rand, + func(rand *rand.Rand) { Data = baseData.NewDecData(sdkTypes.NewDecWithPrec(int64(rand.Intn(99)), 2)) }, + ) + + mappableList := make([]helpers.Mappable, simulationState.Rand.Intn(99)) + + var classificationID ids.ClassificationID + for i := range mappableList { + immutables := baseQualified.NewImmutables(baseSimulation.GenerateRandomPropertyList(simulationState.Rand)) + mutables := baseQualified.NewMutables(baseSimulation.GenerateRandomPropertyList(simulationState.Rand)) + classificationID = baseIDs.NewClassificationID(immutables, mutables) + mappableList[i] = mappable.NewMappable(base.NewMaintainer(baseIDs.NewIdentityID(classificationID, immutables), classificationID, mutables.GetMutablePropertyList().GetPropertyIDList(), utilities.SetPermissions(random.GenerateRandomBool(), random.GenerateRandomBool(), random.GenerateRandomBool(), random.GenerateRandomBool(), random.GenerateRandomBool(), random.GenerateRandomBool()))) + } + + genesisState := baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, nil, parameters.Prototype().GetList()).Initialize(mappableList, []parametersSchema.Parameter{dummy.Parameter.Mutate(Data)}) + + simulationState.GenState[maintainersModule.Name] = common.Codec.MustMarshalJSON(genesisState) +} diff --git a/modules/maintainers/internal/simulator/operations.go b/modules/maintainers/internal/simulator/operations.go index d5dfcf59e..3c3884187 100644 --- a/modules/maintainers/internal/simulator/operations.go +++ b/modules/maintainers/internal/simulator/operations.go @@ -1,21 +1,18 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( - sdkModuleSimulation "github.com/cosmos/cosmos-sdk/x/simulation" "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" ) -func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec.JSONMarshaler) simulation.WeightedOperation { +func (simulator) WeightedOperations(appParams simulation.AppParams, codec *codec.Codec) simulation.WeightedOperations { var weightMsg int appParams.GetOrGenerate(codec, OpWeightMsg, &weightMsg, nil, @@ -24,10 +21,12 @@ func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec. }, ) - return sdkModuleSimulation.NewWeightedOperation( - weightMsg, - simulateMsg(), - ) + return simulation.WeightedOperations{ + simulation.NewWeightedOperation( + weightMsg, + simulateMsg(), + ), + } } func simulateMsg() simulation.Operation { diff --git a/modules/maintainers/internal/simulator/params.go b/modules/maintainers/internal/simulator/params.go index 432809200..04d3f3cf9 100644 --- a/modules/maintainers/internal/simulator/params.go +++ b/modules/maintainers/internal/simulator/params.go @@ -1,30 +1,28 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" "math/rand" - simTypes "github.com/cosmos/cosmos-sdk/types/simulation" + sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + + "github.com/AssetMantle/modules/modules/maintainers/internal/common" + "github.com/AssetMantle/modules/modules/maintainers/internal/module" + "github.com/AssetMantle/modules/modules/maintainers/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/data/base" ) -func (simulator) ParamChangeList(_ *rand.Rand) []simTypes.ParamChange { - return []simTypes.ParamChange{ +func (simulator) ParamChangeList(_ *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange(module.Name, dummy.ID.String(), func(r *rand.Rand) string { - bytes, Error := common.LegacyAminoCodec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdkTypes.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) - if Error != nil { - panic(Error) + bytes, err := common.Codec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdkTypes.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) + if err != nil { + panic(err) } return string(bytes) }), diff --git a/modules/maintainers/internal/simulator/proposals.go b/modules/maintainers/internal/simulator/proposals.go index c85fdfbd1..ce4efd54f 100644 --- a/modules/maintainers/internal/simulator/proposals.go +++ b/modules/maintainers/internal/simulator/proposals.go @@ -1,34 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( - simulation2 "github.com/cosmos/cosmos-sdk/x/simulation" "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/simulation" ) func (simulator) WeightedProposalContentList() []simulation.WeightedProposalContent { return []simulation.WeightedProposalContent{ - simulation2.NewWeightedProposalContent( - OpWeightSubmitTextProposal, - DefaultWeightTextProposal, - contentSimulatorFunc(), - ), + { + AppParamsKey: OpWeightSubmitTextProposal, + DefaultWeight: DefaultWeightTextProposal, + ContentSimulatorFn: simulateTextProposalContent, + }, } } -func contentSimulatorFunc() simulation.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) simulation.Content { - return types.NewTextProposal( - simulation.RandStringOfLength(r, 140), - simulation.RandStringOfLength(r, 5000), - ) - } +func simulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Account) types.Content { + return types.NewTextProposal( + simulation.RandStringOfLength(r, 140), + simulation.RandStringOfLength(r, 5000), + ) } diff --git a/modules/maintainers/internal/simulator/prototype.go b/modules/maintainers/internal/simulator/prototype.go new file mode 100644 index 000000000..3da39d69f --- /dev/null +++ b/modules/maintainers/internal/simulator/prototype.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +func Prototype() helpers.Simulator { + return newSimulator() +} diff --git a/modules/maintainers/internal/simulator/prototype_test.go b/modules/maintainers/internal/simulator/prototype_test.go new file mode 100644 index 000000000..4352a8d45 --- /dev/null +++ b/modules/maintainers/internal/simulator/prototype_test.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype(), newSimulator()) +} diff --git a/modules/maintainers/internal/simulator/simulator.go b/modules/maintainers/internal/simulator/simulator.go new file mode 100644 index 000000000..d963561c2 --- /dev/null +++ b/modules/maintainers/internal/simulator/simulator.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +type simulator struct{} + +var _ helpers.Simulator = (*simulator)(nil) + +func newSimulator() helpers.Simulator { + return simulator{} +} diff --git a/modules/maintainers/internal/transactions/prototype.go b/modules/maintainers/internal/transactions/prototype.go new file mode 100644 index 000000000..576f90402 --- /dev/null +++ b/modules/maintainers/internal/transactions/prototype.go @@ -0,0 +1,13 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transactions + +import ( + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Transactions { + return baseHelpers.NewTransactions() +} diff --git a/modules/maintainers/internal/transactions/prototype_test.go b/modules/maintainers/internal/transactions/prototype_test.go new file mode 100644 index 000000000..87a575a9c --- /dev/null +++ b/modules/maintainers/internal/transactions/prototype_test.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transactions + +import ( + "testing" + + "github.com/stretchr/testify/require" + + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype(), baseHelpers.NewTransactions()) +} diff --git a/modules/maintainers/internal/utilities/permissions.go b/modules/maintainers/internal/utilities/permissions.go new file mode 100644 index 000000000..7674a2790 --- /dev/null +++ b/modules/maintainers/internal/utilities/permissions.go @@ -0,0 +1,32 @@ +package utilities + +import ( + "github.com/AssetMantle/modules/schema/ids/constansts" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" +) + +func SetPermissions(mint bool, burn bool, renumerate bool, add bool, remove bool, mutate bool) lists.IDList { + permissions := base.NewIDList() + + if mint { + permissions = permissions.Add(constansts.Mint) + } + if burn { + permissions = permissions.Add(constansts.Burn) + } + if renumerate { + permissions = permissions.Add(constansts.Renumerate) + } + if add { + permissions = permissions.Add(constansts.Add) + } + if remove { + permissions = permissions.Add(constansts.Remove) + } + if mutate { + permissions = permissions.Add(constansts.Mutate) + } + + return permissions +} diff --git a/modules/maintainers/internal/utilities/permissions_test.go b/modules/maintainers/internal/utilities/permissions_test.go new file mode 100644 index 000000000..8e3859a85 --- /dev/null +++ b/modules/maintainers/internal/utilities/permissions_test.go @@ -0,0 +1,46 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package utilities + +import ( + "reflect" + "testing" + + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/ids/constansts" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" +) + +func TestSetPermissions(t *testing.T) { + idList := base.NewIDList() + type args struct { + mint bool + burn bool + renumerate bool + add bool + remove bool + mutate bool + } + tests := []struct { + name string + args args + want lists.IDList + }{ + {"+ve for can Mint", args{true, false, false, false, false, false}, idList.Add(constansts.Mint)}, + {"+ve for can Burn", args{false, true, false, false, false, false}, idList.Add(constansts.Burn)}, + {"+ve for can Remunerate", args{false, false, true, false, false, false}, idList.Add(constansts.Renumerate)}, + {"+ve for can Add", args{false, false, false, true, false, false}, idList.Add(constansts.Add)}, + {"+ve for can remove", args{false, false, false, false, true, false}, idList.Add(constansts.Remove)}, + {"+ve for can mutate", args{false, false, false, false, false, true}, idList.Add(constansts.Mutate)}, + {"+ve", args{true, true, true, true, true, true}, idList.Add([]ids.ID{constansts.Mint, constansts.Burn, constansts.Renumerate, constansts.Add, constansts.Remove, constansts.Mutate}...)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := SetPermissions(tt.args.mint, tt.args.burn, tt.args.renumerate, tt.args.add, tt.args.remove, tt.args.mutate); !reflect.DeepEqual(got, tt.want) { + t.Errorf("SetPermissions() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/maintainers/prototype.go b/modules/maintainers/prototype.go new file mode 100644 index 000000000..701ebedbb --- /dev/null +++ b/modules/maintainers/prototype.go @@ -0,0 +1,32 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package maintainers + +import ( + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries" + "github.com/AssetMantle/modules/modules/maintainers/internal/block" + "github.com/AssetMantle/modules/modules/maintainers/internal/genesis" + "github.com/AssetMantle/modules/modules/maintainers/internal/mapper" + "github.com/AssetMantle/modules/modules/maintainers/internal/module" + "github.com/AssetMantle/modules/modules/maintainers/internal/parameters" + "github.com/AssetMantle/modules/modules/maintainers/internal/queries" + "github.com/AssetMantle/modules/modules/maintainers/internal/simulator" + "github.com/AssetMantle/modules/modules/maintainers/internal/transactions" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Module { + return baseHelpers.NewModule( + module.Name, + auxiliaries.Prototype, + genesis.Prototype, + mapper.Prototype, + parameters.Prototype, + queries.Prototype, + simulator.Prototype, + transactions.Prototype, + block.Prototype, + ) +} diff --git a/modules/maintainers/prototype_test.go b/modules/maintainers/prototype_test.go new file mode 100644 index 000000000..7f18ad1fa --- /dev/null +++ b/modules/maintainers/prototype_test.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package maintainers + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries" + "github.com/AssetMantle/modules/modules/maintainers/internal/block" + "github.com/AssetMantle/modules/modules/maintainers/internal/genesis" + "github.com/AssetMantle/modules/modules/maintainers/internal/mapper" + "github.com/AssetMantle/modules/modules/maintainers/internal/module" + "github.com/AssetMantle/modules/modules/maintainers/internal/parameters" + "github.com/AssetMantle/modules/modules/maintainers/internal/queries" + "github.com/AssetMantle/modules/modules/maintainers/internal/simulator" + "github.com/AssetMantle/modules/modules/maintainers/internal/transactions" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Name(), baseHelpers.NewModule( + module.Name, + auxiliaries.Prototype, + genesis.Prototype, + mapper.Prototype, + parameters.Prototype, + queries.Prototype, + simulator.Prototype, + transactions.Prototype, + block.Prototype, + ).Name()) +} diff --git a/modules/metas/auxiliaries/auxiliaries.go b/modules/metas/auxiliaries/auxiliaries.go new file mode 100644 index 000000000..dca336343 --- /dev/null +++ b/modules/metas/auxiliaries/auxiliaries.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "github.com/AssetMantle/modules/modules/metas/auxiliaries/scrub" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Auxiliaries { + return baseHelpers.NewAuxiliaries( + scrub.Auxiliary, + supplement.Auxiliary, + ) +} diff --git a/modules/metas/auxiliaries/auxiliaries_test.go b/modules/metas/auxiliaries/auxiliaries_test.go new file mode 100644 index 000000000..e564ece4a --- /dev/null +++ b/modules/metas/auxiliaries/auxiliaries_test.go @@ -0,0 +1,21 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/metas/auxiliaries/scrub" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Get("supplement").GetName(), baseHelpers.NewAuxiliaries( + scrub.Auxiliary, + supplement.Auxiliary, + ).Get("supplement").GetName()) +} diff --git a/modules/metas/auxiliaries/scrub/auxiliary.go b/modules/metas/auxiliaries/scrub/auxiliary.go new file mode 100644 index 000000000..89390a34d --- /dev/null +++ b/modules/metas/auxiliaries/scrub/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package scrub + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "scrub", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "scrub", + keeperPrototypeMock, +) diff --git a/modules/metas/auxiliaries/scrub/keeper.go b/modules/metas/auxiliaries/scrub/keeper.go new file mode 100644 index 000000000..17f733526 --- /dev/null +++ b/modules/metas/auxiliaries/scrub/keeper.go @@ -0,0 +1,49 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package scrub + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/metas/internal/mappable" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + + scrubbedPropertyList := make([]properties.Property, len(auxiliaryRequest.PropertyList.GetList())) + metas := auxiliaryKeeper.mapper.NewCollection(context) + + for i, property := range auxiliaryRequest.PropertyList.GetList() { + if property.IsMeta() { + metaProperty := property.(properties.MetaProperty) + if metaProperty.GetData().GenerateHashID().Compare(baseIDs.GenerateHashID()) != 0 { + metas.Add(mappable.NewMappable(metaProperty.GetData())) + } + scrubbedPropertyList[i] = metaProperty.ScrubData() + } else { + scrubbedPropertyList[i] = property + } + } + + return newAuxiliaryResponse(baseLists.NewPropertyList(scrubbedPropertyList...), nil) +} + +func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeper{mapper: mapper} +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/metas/auxiliaries/scrub/keeper_mock.go b/modules/metas/auxiliaries/scrub/keeper_mock.go new file mode 100644 index 000000000..fbbc2f7fd --- /dev/null +++ b/modules/metas/auxiliaries/scrub/keeper_mock.go @@ -0,0 +1,46 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package scrub + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeperMock)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(_ sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + + scrubbedPropertyList := make([]properties.Property, len(auxiliaryRequest.PropertyList.GetList())) + + for i, property := range auxiliaryRequest.PropertyList.GetList() { + if property.IsMeta() { + scrubbedPropertyList[i] = property.(properties.MetaProperty).ScrubData() + } else { + scrubbedPropertyList[i] = property + } + + if property.GetID().String() == "scrubError" { + return newAuxiliaryResponse(nil, constants.MockError) + } + } + + return newAuxiliaryResponse(baseLists.NewPropertyList(scrubbedPropertyList...), nil) +} + +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/metas/auxiliaries/scrub/keeper_test.go b/modules/metas/auxiliaries/scrub/keeper_test.go new file mode 100644 index 000000000..c3cf8c5bc --- /dev/null +++ b/modules/metas/auxiliaries/scrub/keeper_test.go @@ -0,0 +1,90 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package scrub + +import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/metas/internal/key" + "github.com/AssetMantle/modules/modules/metas/internal/mappable" + "github.com/AssetMantle/modules/modules/metas/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" +) + +type TestKeepers struct { + MetasKeeper helpers.AuxiliaryKeeper +} + +func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + keepers := TestKeepers{ + MetasKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.AuxiliaryKeeper), + } + + return context, keepers + +} + +func Test_Auxiliary_Keeper_Help(t *testing.T) { + context, keepers := CreateTestInput(t) + + metaProperty := baseProperties.NewMetaProperty(baseIDs.NewStringID("id"), baseData.NewStringData("Data")) + metaPropertyList := base.NewPropertyList([]properties.Property{metaProperty}...) + + t.Run("PositiveCase - ", func(t *testing.T) { + want := newAuxiliaryResponse(metaPropertyList.ScrubData(), nil) + if got := keepers.MetasKeeper.Help(context, NewAuxiliaryRequest(metaPropertyList)); !reflect.DeepEqual(got, want) { + t.Errorf("Transact() = %v, want %v", got, want) + } + }) + +} diff --git a/modules/metas/auxiliaries/scrub/request.go b/modules/metas/auxiliaries/scrub/request.go new file mode 100644 index 000000000..9e9be0613 --- /dev/null +++ b/modules/metas/auxiliaries/scrub/request.go @@ -0,0 +1,37 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package scrub + +import ( + "github.com/asaskevich/govalidator" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/lists" +) + +type auxiliaryRequest struct { + lists.PropertyList +} + +var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) + +func (auxiliaryRequest auxiliaryRequest) Validate() error { + _, err := govalidator.ValidateStruct(auxiliaryRequest) + return err +} + +func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { + switch value := request.(type) { + case auxiliaryRequest: + return value + default: + return auxiliaryRequest{} + } +} + +func NewAuxiliaryRequest(propertyList lists.PropertyList) helpers.AuxiliaryRequest { + return auxiliaryRequest{ + PropertyList: propertyList, + } +} diff --git a/modules/metas/auxiliaries/scrub/request_test.go b/modules/metas/auxiliaries/scrub/request_test.go new file mode 100644 index 000000000..7391380f8 --- /dev/null +++ b/modules/metas/auxiliaries/scrub/request_test.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package scrub + +import ( + "testing" + + "github.com/AssetMantle/modules/schema/lists/base" + + "github.com/stretchr/testify/require" + + baseData "github.com/AssetMantle/modules/schema/data/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/properties" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" +) + +func Test_Scrub_Request(t *testing.T) { + + metaProperty := baseProperties.NewMetaProperty(baseIDs.NewStringID("id"), baseData.NewStringData("Data")) + metaPropertyList := base.NewPropertyList([]properties.Property{metaProperty}...) + + testAuxiliaryRequest := NewAuxiliaryRequest(metaPropertyList) + + require.Equal(t, auxiliaryRequest{PropertyList: metaPropertyList}, testAuxiliaryRequest) + require.Equal(t, nil, testAuxiliaryRequest.Validate()) + require.Equal(t, testAuxiliaryRequest, auxiliaryRequestFromInterface(testAuxiliaryRequest)) + require.Equal(t, auxiliaryRequest{}, auxiliaryRequestFromInterface(nil)) + +} diff --git a/modules/metas/auxiliaries/scrub/response.go b/modules/metas/auxiliaries/scrub/response.go index ca3c7662d..b26b1e29b 100644 --- a/modules/metas/auxiliaries/scrub/response.go +++ b/modules/metas/auxiliaries/scrub/response.go @@ -1,20 +1,18 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package scrub import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/lists" ) type auxiliaryResponse struct { - Success bool `json:"success"` - Error error `json:"error"` - Properties types.Properties `json:"properties"` + Success bool `json:"success"` + Error error `json:"error"` + lists.PropertyList `json:"propertyList"` } var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) @@ -25,7 +23,7 @@ func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { func (auxiliaryResponse auxiliaryResponse) GetError() error { return auxiliaryResponse.Error } -func newAuxiliaryResponse(properties types.Properties, error error) helpers.AuxiliaryResponse { +func newAuxiliaryResponse(properties lists.PropertyList, error error) helpers.AuxiliaryResponse { if error != nil { return auxiliaryResponse{ Success: false, @@ -34,20 +32,20 @@ func newAuxiliaryResponse(properties types.Properties, error error) helpers.Auxi } return auxiliaryResponse{ - Success: true, - Properties: properties, + Success: true, + PropertyList: properties, } } -func GetPropertiesFromResponse(response helpers.AuxiliaryResponse) (types.Properties, error) { +func GetPropertiesFromResponse(response helpers.AuxiliaryResponse) (lists.PropertyList, error) { switch value := response.(type) { case auxiliaryResponse: if value.IsSuccessful() { - return value.Properties, nil + return value.PropertyList, nil } return nil, value.GetError() default: - return nil, errors.NotAuthorized + return nil, constants.NotAuthorized } } diff --git a/modules/metas/auxiliaries/scrub/response_test.go b/modules/metas/auxiliaries/scrub/response_test.go index b16470a36..cc3e3d9b7 100644 --- a/modules/metas/auxiliaries/scrub/response_test.go +++ b/modules/metas/auxiliaries/scrub/response_test.go @@ -1,44 +1,48 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package scrub import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" "testing" + + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + + "github.com/stretchr/testify/require" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/errors/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties" ) func Test_Super_Response(t *testing.T) { - metaProperty := base.NewMetaProperty(base.NewID("id"), base.NewMetaFact(base.NewStringData("Data"))) - metaPropertyList := base.NewMetaProperties([]types.MetaProperty{metaProperty}...) - property := base.NewProperty(base.NewID("id"), base.NewFact(base.NewStringData("Data"))) - propertyList := base.NewProperties([]types.Property{property}...) + metaProperty := baseProperties.NewMetaProperty(baseIDs.NewStringID("id"), baseData.NewStringData("Data")) + metaPropertyList := base.NewPropertyList([]properties.Property{metaProperty}...) + property := baseProperties.NewMesaProperty(baseIDs.NewStringID("id"), baseData.NewStringData("Data")) + propertyList := base.NewPropertyList([]properties.Property{property}...) - testAuxiliaryResponse := newAuxiliaryResponse(metaPropertyList.RemoveData(), nil) - require.Equal(t, auxiliaryResponse{Success: true, Error: nil, Properties: metaPropertyList.RemoveData()}, testAuxiliaryResponse) + testAuxiliaryResponse := newAuxiliaryResponse(metaPropertyList.ScrubData(), nil) + require.Equal(t, auxiliaryResponse{Success: true, Error: nil, PropertyList: metaPropertyList.ScrubData()}, testAuxiliaryResponse) require.Equal(t, true, testAuxiliaryResponse.IsSuccessful()) require.Equal(t, nil, testAuxiliaryResponse.GetError()) - testAuxiliaryResponse2 := newAuxiliaryResponse(metaPropertyList.RemoveData(), errors.IncorrectFormat) - require.Equal(t, auxiliaryResponse{Success: false, Error: errors.IncorrectFormat, Properties: nil}, testAuxiliaryResponse2) + testAuxiliaryResponse2 := newAuxiliaryResponse(metaPropertyList.ScrubData(), constants.IncorrectFormat) + require.Equal(t, auxiliaryResponse{Success: false, Error: constants.IncorrectFormat, PropertyList: nil}, testAuxiliaryResponse2) require.Equal(t, false, testAuxiliaryResponse2.IsSuccessful()) - require.Equal(t, errors.IncorrectFormat, testAuxiliaryResponse2.GetError()) + require.Equal(t, constants.IncorrectFormat, testAuxiliaryResponse2.GetError()) - propertiesFromResponse, Error := GetPropertiesFromResponse(testAuxiliaryResponse) + propertiesFromResponse, err := GetPropertiesFromResponse(testAuxiliaryResponse) require.Equal(t, propertyList, propertiesFromResponse) - require.Equal(t, nil, Error) + require.Equal(t, nil, err) - propertiesFromResponse2, Error := GetPropertiesFromResponse(testAuxiliaryResponse2) + propertiesFromResponse2, err := GetPropertiesFromResponse(testAuxiliaryResponse2) require.Equal(t, nil, propertiesFromResponse2) - require.Equal(t, errors.IncorrectFormat, Error) + require.Equal(t, constants.IncorrectFormat, err) - propertiesFromResponse3, Error := GetPropertiesFromResponse(nil) + propertiesFromResponse3, err := GetPropertiesFromResponse(nil) require.Equal(t, nil, propertiesFromResponse3) - require.Equal(t, errors.NotAuthorized, Error) + require.Equal(t, constants.NotAuthorized, err) } diff --git a/modules/metas/auxiliaries/supplement/auxiliary.go b/modules/metas/auxiliaries/supplement/auxiliary.go new file mode 100644 index 000000000..ea4d50a97 --- /dev/null +++ b/modules/metas/auxiliaries/supplement/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package supplement + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "supplement", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "supplement", + keeperPrototypeMock, +) diff --git a/modules/metas/auxiliaries/supplement/keeper.go b/modules/metas/auxiliaries/supplement/keeper.go new file mode 100644 index 000000000..86b20b425 --- /dev/null +++ b/modules/metas/auxiliaries/supplement/keeper.go @@ -0,0 +1,51 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package supplement + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/metas/internal/key" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/data/utilities" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + + propertyList := baseLists.NewPropertyList() + + for _, property := range auxiliaryRequest.PropertyList { + if property.IsMeta() { + propertyList = propertyList.Add(property) + } else if property.GetDataID().GetHashID().Compare(baseIDs.GenerateHashID()) == 0 { + propertyList = propertyList.Add(baseProperties.NewMetaProperty(property.GetKey(), utilities.GetZeroValueDataFromID(property.GetType()))) + } else { + metas := auxiliaryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(property.GetDataID())) + if Mappable := metas.Get(key.NewKey(property.GetDataID())); Mappable != nil { + propertyList = propertyList.Add(baseProperties.NewMetaProperty(property.GetKey(), Mappable.(data.Data))) + } + } + } + + return newAuxiliaryResponse(propertyList, nil) +} + +func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeper{mapper: mapper} +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/metas/auxiliaries/supplement/keeper_mock.go b/modules/metas/auxiliaries/supplement/keeper_mock.go index 680866b5e..4b51e168a 100644 --- a/modules/metas/auxiliaries/supplement/keeper_mock.go +++ b/modules/metas/auxiliaries/supplement/keeper_mock.go @@ -4,13 +4,14 @@ package supplement import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/AssetMantle/modules/schema/data/utilities" errorConstants "github.com/AssetMantle/modules/schema/errors/constants" "github.com/AssetMantle/modules/schema/helpers" baseIDs "github.com/AssetMantle/modules/schema/ids/base" baseLists "github.com/AssetMantle/modules/schema/lists/base" baseProperties "github.com/AssetMantle/modules/schema/properties/base" - sdkTypes "github.com/cosmos/cosmos-sdk/types" ) type auxiliaryKeeperMock struct { diff --git a/modules/metas/auxiliaries/supplement/keeper_test.go b/modules/metas/auxiliaries/supplement/keeper_test.go index 7b1d56cac..a003608f0 100644 --- a/modules/metas/auxiliaries/supplement/keeper_test.go +++ b/modules/metas/auxiliaries/supplement/keeper_test.go @@ -5,6 +5,19 @@ package supplement import ( "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + "github.com/AssetMantle/modules/modules/metas/internal/key" "github.com/AssetMantle/modules/modules/metas/internal/mappable" "github.com/AssetMantle/modules/modules/metas/internal/parameters" @@ -15,17 +28,6 @@ import ( baseIDs "github.com/AssetMantle/modules/schema/ids/base" baseLists "github.com/AssetMantle/modules/schema/lists/base" baseProperties "github.com/AssetMantle/modules/schema/properties/base" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/stretchr/testify/require" - abciTypes "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" ) var ( diff --git a/modules/metas/auxiliaries/supplement/request.go b/modules/metas/auxiliaries/supplement/request.go new file mode 100644 index 000000000..73431244e --- /dev/null +++ b/modules/metas/auxiliaries/supplement/request.go @@ -0,0 +1,37 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package supplement + +import ( + "github.com/asaskevich/govalidator" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/properties" +) + +type auxiliaryRequest struct { + PropertyList []properties.Property `json:"propertyList"` +} + +var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) + +func (auxiliaryRequest auxiliaryRequest) Validate() error { + _, err := govalidator.ValidateStruct(auxiliaryRequest) + return err +} + +func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { + switch value := request.(type) { + case auxiliaryRequest: + return value + default: + return auxiliaryRequest{} + } +} + +func NewAuxiliaryRequest(propertyList ...properties.Property) helpers.AuxiliaryRequest { + return auxiliaryRequest{ + PropertyList: propertyList, + } +} diff --git a/modules/metas/auxiliaries/supplement/request_test.go b/modules/metas/auxiliaries/supplement/request_test.go new file mode 100644 index 000000000..29b0c2204 --- /dev/null +++ b/modules/metas/auxiliaries/supplement/request_test.go @@ -0,0 +1,27 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package supplement + +import ( + "testing" + + "github.com/stretchr/testify/require" + + baseData "github.com/AssetMantle/modules/schema/data/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/properties" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" +) + +func Test_Supplement_Request(t *testing.T) { + + property := baseProperties.NewMesaProperty(baseIDs.NewStringID("id"), baseData.NewStringData("Data")) + testAuxiliaryRequest := NewAuxiliaryRequest(property) + + require.Equal(t, auxiliaryRequest{PropertyList: []properties.Property{property}}, testAuxiliaryRequest) + require.Equal(t, nil, testAuxiliaryRequest.Validate()) + require.Equal(t, testAuxiliaryRequest, auxiliaryRequestFromInterface(testAuxiliaryRequest)) + require.Equal(t, auxiliaryRequest{}, auxiliaryRequestFromInterface(nil)) + +} diff --git a/modules/metas/auxiliaries/supplement/response.go b/modules/metas/auxiliaries/supplement/response.go index 45d702377..9de6ff5fd 100644 --- a/modules/metas/auxiliaries/supplement/response.go +++ b/modules/metas/auxiliaries/supplement/response.go @@ -1,20 +1,18 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package supplement import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/lists" ) type auxiliaryResponse struct { - Success bool `json:"success"` - Error error `json:"error"` - MetaProperties types.MetaProperties `json:"metaProperties"` + Success bool `json:"success"` + Error error `json:"error"` + lists.PropertyList `json:"propertyList"` } var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) @@ -25,7 +23,7 @@ func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { func (auxiliaryResponse auxiliaryResponse) GetError() error { return auxiliaryResponse.Error } -func newAuxiliaryResponse(metaProperties types.MetaProperties, error error) helpers.AuxiliaryResponse { +func newAuxiliaryResponse(metaProperties lists.PropertyList, error error) helpers.AuxiliaryResponse { if error != nil { return auxiliaryResponse{ Success: false, @@ -34,20 +32,20 @@ func newAuxiliaryResponse(metaProperties types.MetaProperties, error error) help } return auxiliaryResponse{ - Success: true, - MetaProperties: metaProperties, + Success: true, + PropertyList: metaProperties, } } -func GetMetaPropertiesFromResponse(response helpers.AuxiliaryResponse) (types.MetaProperties, error) { +func GetMetaPropertiesFromResponse(response helpers.AuxiliaryResponse) (lists.PropertyList, error) { switch value := response.(type) { case auxiliaryResponse: if value.IsSuccessful() { - return value.MetaProperties, nil + return value.PropertyList, nil } return nil, value.GetError() default: - return nil, errors.InvalidRequest + return nil, constants.InvalidRequest } } diff --git a/modules/metas/auxiliaries/supplement/response_test.go b/modules/metas/auxiliaries/supplement/response_test.go index 1e34b197d..c2c320d42 100644 --- a/modules/metas/auxiliaries/supplement/response_test.go +++ b/modules/metas/auxiliaries/supplement/response_test.go @@ -1,38 +1,41 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package supplement import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" "testing" + + "github.com/stretchr/testify/require" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/errors/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" ) func Test_Super_Response(t *testing.T) { - metaProperty := base.NewMetaProperty(base.NewID("id"), base.NewMetaFact(base.NewStringData("Data"))) - metaPropertyList := base.NewMetaProperties([]types.MetaProperty{metaProperty}...) + metaProperty := baseProperties.NewMetaProperty(baseIDs.NewStringID("id"), baseData.NewStringData("Data")) + metaPropertyList := base.NewPropertyList([]properties.Property{metaProperty}...) testAuxiliaryResponse := newAuxiliaryResponse(metaPropertyList, nil) - require.Equal(t, auxiliaryResponse{Success: true, Error: nil, MetaProperties: metaPropertyList}, testAuxiliaryResponse) + require.Equal(t, auxiliaryResponse{Success: true, Error: nil, PropertyList: metaPropertyList}, testAuxiliaryResponse) require.Equal(t, true, testAuxiliaryResponse.IsSuccessful()) require.Equal(t, nil, testAuxiliaryResponse.GetError()) - testAuxiliaryResponse2 := newAuxiliaryResponse(metaPropertyList, errors.IncorrectFormat) - require.Equal(t, auxiliaryResponse{Success: false, Error: errors.IncorrectFormat, MetaProperties: nil}, testAuxiliaryResponse2) + testAuxiliaryResponse2 := newAuxiliaryResponse(metaPropertyList, constants.IncorrectFormat) + require.Equal(t, auxiliaryResponse{Success: false, Error: constants.IncorrectFormat, PropertyList: nil}, testAuxiliaryResponse2) require.Equal(t, false, testAuxiliaryResponse2.IsSuccessful()) - require.Equal(t, errors.IncorrectFormat, testAuxiliaryResponse2.GetError()) + require.Equal(t, constants.IncorrectFormat, testAuxiliaryResponse2.GetError()) - properties, Error := GetMetaPropertiesFromResponse(testAuxiliaryResponse) - require.Equal(t, metaPropertyList, properties) - require.Equal(t, nil, Error) + Properties, err := GetMetaPropertiesFromResponse(testAuxiliaryResponse) + require.Equal(t, metaPropertyList, Properties) + require.Equal(t, nil, err) - properties2, Error := GetMetaPropertiesFromResponse(testAuxiliaryResponse2) + properties2, err := GetMetaPropertiesFromResponse(testAuxiliaryResponse2) require.Equal(t, nil, properties2) - require.Equal(t, errors.IncorrectFormat, Error) + require.Equal(t, constants.IncorrectFormat, err) } diff --git a/modules/metas/internal/block/block.go b/modules/metas/internal/block/block.go new file mode 100644 index 000000000..2b406cdb0 --- /dev/null +++ b/modules/metas/internal/block/block.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package block + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + abciTypes "github.com/tendermint/tendermint/abci/types" + + "github.com/AssetMantle/modules/schema/helpers" +) + +type block struct { + mapper helpers.Mapper + parameters helpers.Parameters +} + +var _ helpers.Block = (*block)(nil) + +func (block block) Begin(_ sdkTypes.Context, _ abciTypes.RequestBeginBlock) { + +} + +func (block block) End(_ sdkTypes.Context, _ abciTypes.RequestEndBlock) { + +} + +func Prototype() helpers.Block { + return block{} +} + +func (block block) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, _ ...interface{}) helpers.Block { + block.mapper, block.parameters = mapper, parameters + return block +} diff --git a/modules/metas/internal/block/block_test.go b/modules/metas/internal/block/block_test.go new file mode 100644 index 000000000..ac7258e7d --- /dev/null +++ b/modules/metas/internal/block/block_test.go @@ -0,0 +1,57 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package block + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/metas/internal/mapper" + "github.com/AssetMantle/modules/modules/metas/internal/parameters" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" +) + +func CreateTestInput(t *testing.T) sdkTypes.Context { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + return context +} + +func Test_Block_Methods(t *testing.T) { + block := Prototype() + block.Initialize(mapper.Prototype(), parameters.Prototype(), []helpers.Auxiliary{}) + context := CreateTestInput(t) + block.Begin(context, abciTypes.RequestBeginBlock{}) + block.End(context, abciTypes.RequestEndBlock{}) +} diff --git a/modules/metas/internal/common/codec.go b/modules/metas/internal/common/codec.go new file mode 100644 index 000000000..db2117b8c --- /dev/null +++ b/modules/metas/internal/common/codec.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package common + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/metas/internal/key" + "github.com/AssetMantle/modules/modules/metas/internal/mappable" + "github.com/AssetMantle/modules/utilities/module" +) + +var Codec *codec.Codec + +func init() { + Codec = module.RegisterCodec(key.Prototype, mappable.Prototype) +} diff --git a/modules/metas/internal/genesis/genesis.go b/modules/metas/internal/genesis/genesis.go deleted file mode 100644 index 77927e405..000000000 --- a/modules/metas/internal/genesis/genesis.go +++ /dev/null @@ -1,188 +0,0 @@ -package genesis - -import ( - "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ helpers.Genesis = (*Genesis)(nil) - -func (genesis Genesis) Default() helpers.Genesis { - return genesis.Initialize(genesis.GetMappableList(), genesis.GetParameterList()) -} - -func (genesis Genesis) Validate() error { - if len(genesis.ParameterList) != len(genesis.DefaultParameterList) { - return errors.InvalidParameter - } - - for _, parameter := range genesis.ParameterList { - var isPresent bool - for _, defaultParameter := range genesis.DefaultParameterList { - isPresent = false - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - isPresent = true - break - } - } - - if !isPresent { - return errors.InvalidParameter - } - - if Error := parameter.Validate(); Error != nil { - return Error - } - } - - _, Error := govalidator.ValidateStruct(genesis) - - return Error -} - -func (genesis Genesis) Import(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) { - for _, mappableValue := range genesis.MappableList { - mapper.Create(context, &mappableValue) - } - - for _, parameter := range genesis.ParameterList { - parameters.Mutate(context, ¶meter) - } -} - -func (genesis Genesis) Export(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) helpers.Genesis { - var mappableList []helpers.Mappable - - appendMappableList := func(mappable helpers.Mappable) bool { - mappableList = append(mappableList, mappable) - return false - } - mapper.Iterate(context, key.Prototype(), appendMappableList) - - for _, defaultParameter := range genesis.DefaultParameterList { - parameters = parameters.Fetch(context, defaultParameter.GetID()) - } - - return genesis.Initialize(mappableList, parameters.GetList()) -} - -func (genesis Genesis) LegacyAminoEncode() []byte { - legacyAminoCodec := codec.NewLegacyAmino() - bytes, Error := legacyAminoCodec.MarshalJSON(genesis) - if Error != nil { - panic(Error) - } - - return bytes -} -func (genesis Genesis) LegacyAminoDecode(byte []byte) helpers.Genesis { - var newGenesis Genesis - legacyAminoCodec := codec.NewLegacyAmino() - if Error := legacyAminoCodec.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(genesis.DefaultMappableList, genesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Encode(cdc codec.JSONMarshaler) []byte { - bytes, Error := cdc.MarshalJSON(&genesis) - if Error != nil { - panic(Error) - } - - return bytes -} - -func (genesis Genesis) Decode(cdc codec.JSONMarshaler, byte []byte) helpers.Genesis { - var newGenesis Genesis - if Error := cdc.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(genesis.DefaultMappableList, genesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Initialize(mappableList []helpers.Mappable, parameterList []types.Parameter) helpers.Genesis { - newParametersList := make([]dummy.DummyParameter, len(parameterList)) - for i, _ := range parameterList { - newParametersList[i] = *dummy.NewParameter(parameterList[i].GetID(), parameterList[i].GetData()) - } - newMappableList := make([]mappable.Meta, len(mappableList)) - for i, _ := range mappableList { - newMappableList[i] = *mappableList[i].(*mappable.Meta) - } - newParameter := dummy.Parameter.Mutate(dummy.Parameter.GetData()) - genesis.DefaultParameterList = []dummy.DummyParameter{*dummy.NewParameter(newParameter.GetID(), newParameter.GetData())} - if len(newMappableList) == 0 { - genesis.MappableList = genesis.DefaultMappableList - } else { - genesis.MappableList = newMappableList - } - - if len(newParametersList) == 0 { - genesis.ParameterList = genesis.DefaultParameterList - } else { - for _, defaultParameter := range genesis.DefaultParameterList { - for i, parameter := range newParametersList { - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - newParametersList[i] = *dummy.NewParameter(defaultParameter.Mutate(parameter.GetData()).GetID(), defaultParameter.Mutate(parameter.GetData()).GetData()) - } - } - } - genesis.ParameterList = newParametersList - } - - if Error := genesis.Validate(); Error != nil { - panic(Error) - } - - return &genesis -} - -func (genesis Genesis) GetParameterList() []types.Parameter { - newParameterList := make([]types.Parameter, len(genesis.ParameterList)) - for i, _ := range genesis.ParameterList { - newParameterList[i] = &genesis.ParameterList[i] - } - return newParameterList -} -func (genesis Genesis) GetMappableList() []helpers.Mappable { - newMappableList := make([]helpers.Mappable, len(genesis.MappableList)) - for i, _ := range genesis.MappableList { - newMappableList[i] = &genesis.MappableList[i] - } - return newMappableList -} - -func (genesis Genesis) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*helpers.Key)(nil), - &key.MetaID{}, - ) - registry.RegisterImplementations((*helpers.Mappable)(nil), - &mappable.Meta{}, - ) - registry.RegisterImplementations((*types.Parameter)(nil), - &dummy.DummyParameter{}, - ) - registry.RegisterImplementations((*helpers.Genesis)(nil), - &Genesis{}, - ) -} - -func NewGenesis(defaultMappableList []mappable.Meta, defaultParameterList []dummy.DummyParameter) *Genesis { - return &Genesis{ - DefaultMappableList: defaultMappableList, - DefaultParameterList: defaultParameterList, - MappableList: []mappable.Meta{}, - ParameterList: []dummy.DummyParameter{}, - } -} diff --git a/modules/metas/internal/genesis/genesis.pb.go b/modules/metas/internal/genesis/genesis.pb.go deleted file mode 100644 index 17b26b7ae..000000000 --- a/modules/metas/internal/genesis/genesis.pb.go +++ /dev/null @@ -1,499 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/metas/internal/genesis/genesis.proto - -package genesis - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - mappable "github.com/persistenceOne/persistenceSDK/modules/metas/internal/mappable" - dummy "github.com/persistenceOne/persistenceSDK/modules/metas/internal/parameters/dummy" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Genesis struct { - DefaultMappableList []mappable.Meta `protobuf:"bytes,1,rep,name=defaultMappableList,proto3" json:"defaultMappableList"` - DefaultParameterList []dummy.DummyParameter `protobuf:"bytes,2,rep,name=defaultParameterList,proto3" json:"defaultParameterList"` - MappableList []mappable.Meta `protobuf:"bytes,3,rep,name=MappableList,proto3" json:"MappableList"` - ParameterList []dummy.DummyParameter `protobuf:"bytes,4,rep,name=ParameterList,proto3" json:"ParameterList"` -} - -func (m *Genesis) Reset() { *m = Genesis{} } -func (m *Genesis) String() string { return proto.CompactTextString(m) } -func (*Genesis) ProtoMessage() {} -func (*Genesis) Descriptor() ([]byte, []int) { - return fileDescriptor_3c7d04d0c94d37ac, []int{0} -} -func (m *Genesis) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Genesis) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Genesis.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Genesis) XXX_Merge(src proto.Message) { - xxx_messageInfo_Genesis.Merge(m, src) -} -func (m *Genesis) XXX_Size() int { - return m.Size() -} -func (m *Genesis) XXX_DiscardUnknown() { - xxx_messageInfo_Genesis.DiscardUnknown(m) -} - -var xxx_messageInfo_Genesis proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Genesis)(nil), "persistence_sdk.modules.metas.internal.genesis.Genesis") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/metas/internal/genesis/genesis.proto", fileDescriptor_3c7d04d0c94d37ac) -} - -var fileDescriptor_3c7d04d0c94d37ac = []byte{ - // 327 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x29, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4d, 0x2d, 0x49, 0x2c, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, 0xca, - 0x4b, 0xcc, 0xd1, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0x86, 0xd1, 0x7a, 0x05, 0x45, 0xf9, - 0x25, 0xf9, 0x42, 0x7a, 0x68, 0xba, 0xf5, 0xa0, 0xba, 0xf5, 0xc0, 0xba, 0xf5, 0x60, 0xba, 0xf5, - 0xa0, 0xba, 0xa4, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x5a, 0xf5, 0x41, 0x2c, 0x88, 0x29, 0x52, - 0xee, 0x44, 0xba, 0xa1, 0x20, 0xb1, 0x28, 0x31, 0x37, 0xb5, 0x24, 0xb5, 0xa8, 0x58, 0x3f, 0xa5, - 0x34, 0x37, 0xb7, 0x12, 0x21, 0x00, 0x35, 0xc8, 0x8a, 0x48, 0x83, 0x72, 0x13, 0x0b, 0x0a, 0x12, - 0x93, 0x72, 0x52, 0xc1, 0xe2, 0x10, 0xbd, 0x4a, 0x37, 0x98, 0xb9, 0xd8, 0xdd, 0x21, 0xce, 0x14, - 0xca, 0xe5, 0x12, 0x4e, 0x49, 0x4d, 0x4b, 0x2c, 0xcd, 0x29, 0xf1, 0x85, 0xaa, 0xf4, 0xc9, 0x2c, - 0x2e, 0x91, 0x60, 0x54, 0x60, 0xd6, 0xe0, 0x36, 0x32, 0x25, 0xd6, 0xd3, 0x30, 0x5b, 0xf4, 0x7c, - 0x53, 0x4b, 0x12, 0x9d, 0x58, 0x4e, 0xdc, 0x93, 0x67, 0x08, 0xc2, 0x66, 0xae, 0x50, 0x23, 0x23, - 0x97, 0x08, 0x54, 0x3c, 0x00, 0xe6, 0x23, 0xb0, 0x85, 0x4c, 0x60, 0x0b, 0xdd, 0x89, 0xb5, 0x10, - 0x11, 0x3e, 0x7a, 0xe0, 0xf0, 0xd1, 0x73, 0x01, 0x91, 0x70, 0x23, 0xa1, 0x4e, 0xc0, 0x6a, 0x95, - 0x50, 0x3c, 0x17, 0x0f, 0x8a, 0x5f, 0x99, 0x29, 0xf7, 0x2b, 0x8a, 0x81, 0x42, 0xc5, 0x5c, 0xbc, - 0xa8, 0x9e, 0x63, 0xa1, 0x85, 0xe7, 0x50, 0xed, 0xb0, 0x62, 0xe9, 0x58, 0x20, 0xcf, 0xe0, 0x94, - 0x78, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, - 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0xee, 0xe9, 0x99, 0x25, 0x19, - 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x48, 0xee, 0xf0, 0xcf, 0x4b, 0x45, 0xe6, 0x06, 0xbb, - 0x78, 0x13, 0xc8, 0x16, 0x49, 0x6c, 0xe0, 0x44, 0x64, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0xc1, - 0xb2, 0x8a, 0x79, 0x4f, 0x03, 0x00, 0x00, -} - -func (m *Genesis) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Genesis) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Genesis) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ParameterList) > 0 { - for iNdEx := len(m.ParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.MappableList) > 0 { - for iNdEx := len(m.MappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.DefaultParameterList) > 0 { - for iNdEx := len(m.DefaultParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.DefaultMappableList) > 0 { - for iNdEx := len(m.DefaultMappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultMappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Genesis) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.DefaultMappableList) > 0 { - for _, e := range m.DefaultMappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.DefaultParameterList) > 0 { - for _, e := range m.DefaultParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.MappableList) > 0 { - for _, e := range m.MappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ParameterList) > 0 { - for _, e := range m.ParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Genesis) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Genesis: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Genesis: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultMappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultMappableList = append(m.DefaultMappableList, mappable.Meta{}) - if err := m.DefaultMappableList[len(m.DefaultMappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultParameterList = append(m.DefaultParameterList, dummy.DummyParameter{}) - if err := m.DefaultParameterList[len(m.DefaultParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MappableList = append(m.MappableList, mappable.Meta{}) - if err := m.MappableList[len(m.MappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ParameterList = append(m.ParameterList, dummy.DummyParameter{}) - if err := m.ParameterList[len(m.ParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/metas/internal/genesis/prototype.go b/modules/metas/internal/genesis/prototype.go index 52e4a9c70..894577f15 100644 --- a/modules/metas/internal/genesis/prototype.go +++ b/modules/metas/internal/genesis/prototype.go @@ -1,16 +1,16 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package genesis import ( - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/metas/internal/key" + "github.com/AssetMantle/modules/modules/metas/internal/mappable" + "github.com/AssetMantle/modules/modules/metas/internal/parameters" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" ) func Prototype() helpers.Genesis { - return NewGenesis([]mappable.Meta{}, []dummy.DummyParameter{}) + return baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{}, parameters.Prototype().GetList()) } diff --git a/modules/metas/internal/genesis/prototype_test.go b/modules/metas/internal/genesis/prototype_test.go new file mode 100644 index 000000000..3096175db --- /dev/null +++ b/modules/metas/internal/genesis/prototype_test.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package genesis + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/metas/internal/key" + "github.com/AssetMantle/modules/modules/metas/internal/mappable" + "github.com/AssetMantle/modules/modules/metas/internal/parameters" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Panics(t, func() { + require.Equal(t, Prototype(), baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{}, parameters.Prototype().GetList())) + }) +} diff --git a/modules/metas/internal/key/key.go b/modules/metas/internal/key/key.go new file mode 100644 index 000000000..af865d504 --- /dev/null +++ b/modules/metas/internal/key/key.go @@ -0,0 +1,53 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package key + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/metas/internal/module" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +type key struct { + ids.DataID +} + +var _ helpers.Key = (*key)(nil) + +func (key key) GenerateStoreKeyBytes() []byte { + return module.StoreKeyPrefix.GenerateStoreKey(key.Bytes()) +} +func (key) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, key{}) +} +func (key key) IsPartial() bool { + return len(key.DataID.GetHashID().Bytes()) == 0 +} +func (key key) Equals(compareKey helpers.Key) bool { + if CompareKey, err := keyFromInterface(compareKey); err != nil { + return false + } else { + return key.DataID.Compare(CompareKey.DataID) == 0 + } +} +func keyFromInterface(i interface{}) (key, error) { + switch value := i.(type) { + case key: + return value, nil + default: + return key{}, constants.MetaDataError + } +} + +func NewKey(dataID ids.DataID) helpers.Key { + return key{ + DataID: dataID, + } +} + +func Prototype() helpers.Key { return key{} } diff --git a/modules/metas/internal/key/key_test.go b/modules/metas/internal/key/key_test.go new file mode 100644 index 000000000..5e88d5e7a --- /dev/null +++ b/modules/metas/internal/key/key_test.go @@ -0,0 +1,186 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package key + +import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/metas/internal/module" + base2 "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/ids/base" +) + +var ( + testDataID = base.NewDataID(base2.NewStringData("Data")) + testDataID1 = base.PrototypeDataID() +) + +func TestNewKey(t *testing.T) { + type args struct { + dataID ids.DataID + } + tests := []struct { + name string + args args + want helpers.Key + }{ + {"+ve", args{testDataID}, key{testDataID}}, + {"+ve", args{testDataID1}, key{testDataID1}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewKey(tt.args.dataID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewKey() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Key + }{ + {"+ve", key{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_keyFromInterface(t *testing.T) { + type args struct { + i interface{} + } + tests := []struct { + name string + args args + want key + wantErr bool + }{ + {"+ve", args{NewKey(testDataID)}, key{testDataID}, false}, + {"+ve with nil", args{NewKey(testDataID1)}, key{testDataID1}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := keyFromInterface(tt.args.i) + if (err != nil) != tt.wantErr { + t.Errorf("keyFromInterface() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("keyFromInterface() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_Equals(t *testing.T) { + type fields struct { + DataID ids.DataID + } + type args struct { + compareKey helpers.Key + } + tests := []struct { + name string + fields fields + args args + want bool + }{ + {"+ve", fields{testDataID}, args{NewKey(testDataID)}, true}, + {"+ve", fields{testDataID}, args{NewKey(testDataID1)}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key := key{ + DataID: tt.fields.DataID, + } + if got := key.Equals(tt.args.compareKey); got != tt.want { + t.Errorf("Equals() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_GenerateStoreKeyBytes(t *testing.T) { + type fields struct { + DataID ids.DataID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{testDataID}, module.StoreKeyPrefix.GenerateStoreKey(key{testDataID}.Bytes())}, + {"+ve with nil", fields{testDataID1}, module.StoreKeyPrefix.GenerateStoreKey(key{testDataID1}.Bytes())}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key := key{ + DataID: tt.fields.DataID, + } + if got := key.GenerateStoreKeyBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GenerateStoreKeyBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_IsPartial(t *testing.T) { + type fields struct { + DataID ids.DataID + } + tests := []struct { + name string + fields fields + want bool + }{ + {"+ve", fields{testDataID}, false}, + {"-ve", fields{testDataID1}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key := key{ + DataID: tt.fields.DataID, + } + if got := key.IsPartial(); got != tt.want { + t.Errorf("IsPartial() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_key_RegisterCodec(t *testing.T) { + type fields struct { + DataID ids.DataID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testDataID}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ke := key{ + DataID: tt.fields.DataID, + } + ke.RegisterCodec(tt.args.codec) + }) + } +} diff --git a/modules/metas/internal/key/metaID.go b/modules/metas/internal/key/metaID.go deleted file mode 100644 index 26fff65c9..000000000 --- a/modules/metas/internal/key/metaID.go +++ /dev/null @@ -1,63 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - "bytes" - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "strings" -) - -var _ types.ID = (*MetaID)(nil) -var _ helpers.Key = (*MetaID)(nil) - -func (metaID MetaID) GetStructReference() codec.ProtoMarshaler { - return &metaID -} -func (metaID MetaID) Bytes() []byte { - var Bytes []byte - Bytes = append(Bytes, metaID.TypeID.Bytes()...) - Bytes = append(Bytes, metaID.HashID.Bytes()...) - - return Bytes -} -func (metaID MetaID) String() string { - var values []string - values = append(values, metaID.TypeID.String()) - values = append(values, metaID.HashID.String()) - - return strings.Join(values, constants.FirstOrderCompositeIDSeparator) -} -func (metaID MetaID) Compare(id types.ID) int { - return bytes.Compare(metaID.Bytes(), id.Bytes()) -} -func (metaID MetaID) GenerateStoreKeyBytes() []byte { - return module.StoreKeyPrefix.GenerateStoreKey(metaID.Bytes()) -} -func (MetaID) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, MetaID{}) -} -func (metaID MetaID) IsPartial() bool { - return len(metaID.HashID.Bytes()) == 0 -} -func (metaID MetaID) Equals(key helpers.Key) bool { - id := metaIDFromInterface(key) - return metaID.Compare(&id) == 0 -} - -func NewMetaID(typeID types.ID, hashID types.ID) types.ID { - return &MetaID{ - TypeID: *base.NewID(typeID.String()), - HashID: *base.NewID(hashID.String()), - } -} diff --git a/modules/metas/internal/key/metaID.pb.go b/modules/metas/internal/key/metaID.pb.go deleted file mode 100644 index 774e694c2..000000000 --- a/modules/metas/internal/key/metaID.pb.go +++ /dev/null @@ -1,379 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/metas/internal/key/metaID.proto - -package key - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type MetaID struct { - TypeID base.ID `protobuf:"bytes,1,opt,name=type_i_d,json=typeID,proto3" json:"type_i_d"` - HashID base.ID `protobuf:"bytes,2,opt,name=hash_i_d,json=hashID,proto3" json:"hash_i_d"` -} - -func (m *MetaID) Reset() { *m = MetaID{} } -func (*MetaID) ProtoMessage() {} -func (*MetaID) Descriptor() ([]byte, []int) { - return fileDescriptor_872133bbc3312930, []int{0} -} -func (m *MetaID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MetaID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MetaID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MetaID) XXX_Merge(src proto.Message) { - xxx_messageInfo_MetaID.Merge(m, src) -} -func (m *MetaID) XXX_Size() int { - return m.Size() -} -func (m *MetaID) XXX_DiscardUnknown() { - xxx_messageInfo_MetaID.DiscardUnknown(m) -} - -var xxx_messageInfo_MetaID proto.InternalMessageInfo - -func (m *MetaID) GetTypeID() base.ID { - if m != nil { - return m.TypeID - } - return base.ID{} -} - -func (m *MetaID) GetHashID() base.ID { - if m != nil { - return m.HashID - } - return base.ID{} -} - -func init() { - proto.RegisterType((*MetaID)(nil), "persistence_sdk.modules.metas.internal.key.MetaID") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/metas/internal/key/metaID.proto", fileDescriptor_872133bbc3312930) -} - -var fileDescriptor_872133bbc3312930 = []byte{ - // 266 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x2f, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4d, 0x2d, 0x49, 0x2c, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, 0xca, - 0x4b, 0xcc, 0xd1, 0xcf, 0x4e, 0xad, 0x04, 0x0b, 0x79, 0xba, 0xe8, 0x15, 0x14, 0xe5, 0x97, 0xe4, - 0x0b, 0x69, 0xa1, 0x69, 0xd4, 0x83, 0x6a, 0xd4, 0x03, 0x6b, 0xd4, 0x83, 0x69, 0xd4, 0xcb, 0x4e, - 0xad, 0x94, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x6b, 0xd3, 0x07, 0xb1, 0x20, 0x26, 0x48, 0xa1, - 0x9b, 0xa0, 0x5f, 0x9c, 0x9c, 0x91, 0x9a, 0x9b, 0xa8, 0x5f, 0x52, 0x59, 0x90, 0x5a, 0xac, 0x9f, - 0x94, 0x58, 0x9c, 0xaa, 0x9f, 0x99, 0x02, 0x51, 0xab, 0x34, 0x87, 0x91, 0x8b, 0xcd, 0x17, 0x6c, - 0xbd, 0x90, 0x2b, 0x17, 0x07, 0x48, 0x45, 0x7c, 0x66, 0x7c, 0x8a, 0x04, 0xa3, 0x02, 0xa3, 0x06, - 0xb7, 0x91, 0xaa, 0x1e, 0xba, 0x5b, 0x20, 0x26, 0xe9, 0x81, 0x4d, 0xd2, 0x03, 0x99, 0xa4, 0xe7, - 0xe9, 0xe2, 0xc4, 0x72, 0xe2, 0x9e, 0x3c, 0x43, 0x10, 0x1b, 0x48, 0x10, 0x62, 0x4c, 0x46, 0x62, - 0x71, 0x06, 0xd8, 0x18, 0x26, 0x32, 0x8c, 0x01, 0x69, 0xf6, 0x74, 0xb1, 0x62, 0x99, 0xb1, 0x40, - 0x9e, 0xc1, 0x29, 0xf6, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, - 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0x9c, 0xd3, - 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x91, 0x8c, 0xf7, 0xcf, 0x4b, 0x45, - 0xe6, 0x06, 0xbb, 0x78, 0xe3, 0x09, 0xf8, 0x24, 0x36, 0x70, 0x20, 0x18, 0x03, 0x02, 0x00, 0x00, - 0xff, 0xff, 0x78, 0xd7, 0xf1, 0xa5, 0xad, 0x01, 0x00, 0x00, -} - -func (m *MetaID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MetaID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MetaID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.HashID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMetaID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.TypeID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMetaID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintMetaID(dAtA []byte, offset int, v uint64) int { - offset -= sovMetaID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MetaID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.TypeID.Size() - n += 1 + l + sovMetaID(uint64(l)) - l = m.HashID.Size() - n += 1 + l + sovMetaID(uint64(l)) - return n -} - -func sovMetaID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMetaID(x uint64) (n int) { - return sovMetaID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MetaID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MetaID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MetaID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TypeID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetaID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetaID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TypeID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HashID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetaID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetaID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HashID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMetaID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMetaID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMetaID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMetaID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMetaID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMetaID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMetaID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMetaID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMetaID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/metas/internal/key/metaID_test.go b/modules/metas/internal/key/metaID_test.go deleted file mode 100644 index 284cbb333..000000000 --- a/modules/metas/internal/key/metaID_test.go +++ /dev/null @@ -1,30 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" - "testing" -) - -func Test_MetaID_Methods(t *testing.T) { - typeID := base.NewID("I") - hashID := base.NewID("hashID") - testMetaID := NewMetaID(typeID, hashID).(metaID) - require.NotPanics(t, func() { - require.Equal(t, typeID.String()+constants.FirstOrderCompositeIDSeparator+hashID.String(), testMetaID.String()) - require.Equal(t, true, testMetaID.Equals(testMetaID)) - require.Equal(t, false, testMetaID.Equals(metaID{TypeID: base.NewID("tempID"), HashID: base.NewID("tempHash")})) - require.Equal(t, false, testMetaID.IsPartial()) - require.Equal(t, true, metaID{HashID: base.NewID("")}.IsPartial()) - require.Equal(t, true, testMetaID.Equals(testMetaID)) - require.Equal(t, false, testMetaID.Equals(nil)) - require.Equal(t, testMetaID, FromID(testMetaID)) - require.Equal(t, NewMetaID(base.NewID(""), base.NewID("")), FromID(base.NewID(""))) - }) -} diff --git a/modules/metas/internal/key/utilities.go b/modules/metas/internal/key/utilities.go deleted file mode 100644 index 9f5ffcf31..000000000 --- a/modules/metas/internal/key/utilities.go +++ /dev/null @@ -1,47 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "strings" -) - -func readMetaID(metaIDString string) MetaID { - idList := strings.Split(metaIDString, constants.FirstOrderCompositeIDSeparator) - if len(idList) == 2 { - return MetaID{ - TypeID: *base.NewID(idList[0]), - HashID: *base.NewID(idList[1]), - } - } - - return MetaID{TypeID: *base.NewID(""), HashID: *base.NewID("")} -} -func metaIDFromInterface(i interface{}) MetaID { - switch value := i.(type) { - case MetaID: - return value - case types.ID: - return metaIDFromInterface(readMetaID(value.String())) - default: - panic(i) - } -} - -func GenerateMetaID(data types.Data) types.ID { - return &MetaID{ - TypeID: *base.NewID(data.GetTypeID().String()), - HashID: *base.NewID(data.GenerateHashID().String()), - } -} - -func FromID(id types.ID) helpers.Key { - return metaIDFromInterface(id) -} diff --git a/modules/metas/internal/mappable/mappable.go b/modules/metas/internal/mappable/mappable.go new file mode 100644 index 000000000..c3d14a8c5 --- /dev/null +++ b/modules/metas/internal/mappable/mappable.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mappable + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/metas/internal/key" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +type mappable struct { + data.Data +} + +var _ helpers.Mappable = (*mappable)(nil) + +func (mappable mappable) GetKey() helpers.Key { + return key.NewKey(base.NewDataID(mappable.Data)) +} +func (mappable) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, mappable{}) +} + +func NewMappable(data data.Data) helpers.Mappable { + return mappable{Data: data} +} + +func Prototype() helpers.Mappable { + return mappable{} +} diff --git a/modules/metas/internal/mappable/mappable_test.go b/modules/metas/internal/mappable/mappable_test.go new file mode 100644 index 000000000..8fec88bb1 --- /dev/null +++ b/modules/metas/internal/mappable/mappable_test.go @@ -0,0 +1,101 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mappable + +import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/metas/internal/key" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + base2 "github.com/AssetMantle/modules/schema/ids/base" +) + +func TestNewMappable(t *testing.T) { + type args struct { + data data.Data + } + tests := []struct { + name string + args args + want helpers.Mappable + }{ + {"+ve", args{base.NewStringData("data")}, mappable{base.NewStringData("data")}}, + {"+ve with nil", args{}, mappable{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewMappable(tt.args.data); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewMappable() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Mappable + }{ + {"+ve", mappable{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_mappable_GetKey(t *testing.T) { + type fields struct { + Data data.Data + } + tests := []struct { + name string + fields fields + want helpers.Key + }{ + {"+ve", fields{base.NewStringData("Data")}, key.NewKey(base2.NewDataID(base.NewStringData("Data")))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + mappable := mappable{ + Data: tt.fields.Data, + } + if got := mappable.GetKey(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetKey() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_mappable_RegisterCodec(t *testing.T) { + type fields struct { + Data data.Data + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{base.NewStringData("Data")}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ma := mappable{ + Data: tt.fields.Data, + } + ma.RegisterCodec(tt.args.codec) + }) + } +} diff --git a/modules/metas/internal/mappable/meta.go b/modules/metas/internal/mappable/meta.go deleted file mode 100644 index dece595ed..000000000 --- a/modules/metas/internal/mappable/meta.go +++ /dev/null @@ -1,39 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import ( - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/mappables" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" -) - -var _ mappables.Meta = (*Meta)(nil) - -func (meta Meta) GetStructReference() codec.ProtoMarshaler { - return &meta -} -func (meta Meta) GetData() types.Data { return &meta.Data } -func (meta Meta) GetID() types.ID { return &meta.ID } -func (meta Meta) GetKey() helpers.Key { - return key.FromID(meta.GetID()) -} -func (Meta) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Meta{}) -} - -func NewMeta(data types.Data) *Meta { - return &Meta{ - ID: *base.NewID(key.GenerateMetaID(data).String()), - Data: *base.NewData(data), - } -} diff --git a/modules/metas/internal/mappable/meta.pb.go b/modules/metas/internal/mappable/meta.pb.go deleted file mode 100644 index 1a911ce1a..000000000 --- a/modules/metas/internal/mappable/meta.pb.go +++ /dev/null @@ -1,367 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/metas/internal/mappable/meta.proto - -package mappable - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Meta struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - Data base.Data `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` -} - -func (m *Meta) Reset() { *m = Meta{} } -func (m *Meta) String() string { return proto.CompactTextString(m) } -func (*Meta) ProtoMessage() {} -func (*Meta) Descriptor() ([]byte, []int) { - return fileDescriptor_df5cb6addea086d7, []int{0} -} -func (m *Meta) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Meta) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Meta.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Meta) XXX_Merge(src proto.Message) { - xxx_messageInfo_Meta.Merge(m, src) -} -func (m *Meta) XXX_Size() int { - return m.Size() -} -func (m *Meta) XXX_DiscardUnknown() { - xxx_messageInfo_Meta.DiscardUnknown(m) -} - -var xxx_messageInfo_Meta proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Meta)(nil), "persistence_sdk.modules.metas.internal.mappable.Meta") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/metas/internal/mappable/meta.proto", fileDescriptor_df5cb6addea086d7) -} - -var fileDescriptor_df5cb6addea086d7 = []byte{ - // 278 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x2a, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4d, 0x2d, 0x49, 0x2c, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, 0xca, - 0x4b, 0xcc, 0xd1, 0xcf, 0x4d, 0x2c, 0x28, 0x48, 0x4c, 0xca, 0x49, 0x05, 0x8b, 0xeb, 0x15, 0x14, - 0xe5, 0x97, 0xe4, 0x0b, 0xe9, 0xa3, 0xe9, 0xd5, 0x83, 0xea, 0xd5, 0x03, 0xeb, 0xd5, 0x83, 0xe9, - 0xd5, 0x83, 0xe9, 0x95, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0xeb, 0xd5, 0x07, 0xb1, 0x20, 0xc6, - 0x48, 0x69, 0xa1, 0x3b, 0xa1, 0x38, 0x39, 0x23, 0x35, 0x37, 0x51, 0xbf, 0xa4, 0xb2, 0x20, 0xb5, - 0x58, 0x3f, 0x29, 0xb1, 0x38, 0x55, 0x3f, 0x33, 0x05, 0xaa, 0x56, 0x87, 0xb0, 0xda, 0x94, 0x44, - 0x98, 0x03, 0x95, 0x7a, 0x19, 0xb9, 0x58, 0x7c, 0x53, 0x4b, 0x12, 0x85, 0x6c, 0xb8, 0x98, 0x33, - 0xe3, 0x53, 0x24, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0x54, 0xf5, 0xd0, 0xdd, 0x0d, 0x31, 0x44, - 0x0f, 0x6c, 0x88, 0x1e, 0xc8, 0x10, 0x3d, 0x4f, 0x17, 0x27, 0x96, 0x13, 0xf7, 0xe4, 0x19, 0x82, - 0x98, 0x32, 0x5d, 0x84, 0x1c, 0xb9, 0x58, 0x40, 0x86, 0x4a, 0x30, 0x81, 0xb5, 0xab, 0x13, 0xa1, - 0xdd, 0x25, 0xb1, 0x24, 0x11, 0x6a, 0x00, 0x58, 0xab, 0x15, 0x4b, 0xc7, 0x02, 0x79, 0x06, 0xa7, - 0xa4, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, - 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0xf2, 0x48, 0xcf, 0x2c, 0xc9, - 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0x45, 0x0e, 0x55, 0xff, 0xbc, 0x54, 0x64, 0x6e, 0xb0, 0x8b, - 0x37, 0xa1, 0xf8, 0x49, 0x62, 0x03, 0x7b, 0xdd, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x75, 0xab, - 0xed, 0x7d, 0xd9, 0x01, 0x00, 0x00, -} - -func (m *Meta) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Meta) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Meta) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Data.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMeta(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMeta(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintMeta(dAtA []byte, offset int, v uint64) int { - offset -= sovMeta(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Meta) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovMeta(uint64(l)) - l = m.Data.Size() - n += 1 + l + sovMeta(uint64(l)) - return n -} - -func sovMeta(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMeta(x uint64) (n int) { - return sovMeta(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Meta) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMeta - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Meta: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Meta: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMeta - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMeta - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMeta - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMeta - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMeta - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMeta - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMeta(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMeta - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMeta(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMeta - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMeta - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMeta - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMeta - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMeta - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMeta - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMeta = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMeta = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMeta = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/metas/internal/mappable/prototype.go b/modules/metas/internal/mappable/prototype.go deleted file mode 100644 index 36ed6ea76..000000000 --- a/modules/metas/internal/mappable/prototype.go +++ /dev/null @@ -1,12 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import "github.com/persistenceOne/persistenceSDK/schema/helpers" - -func Prototype() helpers.Mappable { - return &Meta{} -} diff --git a/modules/metas/internal/mapper/prototype.go b/modules/metas/internal/mapper/prototype.go new file mode 100644 index 000000000..df8069a90 --- /dev/null +++ b/modules/metas/internal/mapper/prototype.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mapper + +import ( + "github.com/AssetMantle/modules/modules/metas/internal/key" + "github.com/AssetMantle/modules/modules/metas/internal/mappable" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Mapper { + return baseHelpers.NewMapper(key.Prototype, mappable.Prototype) +} diff --git a/modules/metas/module/module/constants.go b/modules/metas/internal/module/constants.go similarity index 100% rename from modules/metas/module/module/constants.go rename to modules/metas/internal/module/constants.go diff --git a/modules/metas/internal/parameters/dummy/constants.go b/modules/metas/internal/parameters/dummy/constants.go new file mode 100644 index 000000000..770f437dc --- /dev/null +++ b/modules/metas/internal/parameters/dummy/constants.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package dummy + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +var ID = baseIDs.NewStringID("dummy") + +var DefaultData = baseData.NewDecData(sdkTypes.SmallestDec()) diff --git a/modules/metas/internal/parameters/dummy/parameter.go b/modules/metas/internal/parameters/dummy/parameter.go index e78fdc8d0..5ffc0eaf5 100644 --- a/modules/metas/internal/parameters/dummy/parameter.go +++ b/modules/metas/internal/parameters/dummy/parameter.go @@ -1,59 +1,10 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "encoding/json" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" ) -var _ types.Parameter = (*DummyParameter)(nil) - -func (dummyParameter DummyParameter) String() string { - bytes, Error := json.Marshal(dummyParameter) - if Error != nil { - return Error.Error() - } - return string(bytes) -} - -func (dummyParameter DummyParameter) Equal(compareParameter types.Parameter) bool { - if compareParameter == nil { - return false - } - return dummyParameter.Data.Compare(compareParameter.GetData()) == 0 -} - -func (dummyParameter DummyParameter) Validate() error { - return validator(dummyParameter) -} - -func (dummyParameter DummyParameter) GetID() types.ID { - return &dummyParameter.ID -} - -func (dummyParameter DummyParameter) GetData() types.Data { - return &dummyParameter.Data -} - -func (dummyParameter DummyParameter) GetValidator() func(interface{}) error { - return validator -} - -func (dummyParameter DummyParameter) Mutate(data types.Data) types.Parameter { - decData, _ := data.AsDec() - dummyParameter.Data = *base.NewDummyDecData(decData) - return &dummyParameter -} - -func NewParameter(id types.ID, data types.Data) *DummyParameter { - decData, _ := data.AsDec() - return &DummyParameter{ - ID: *base.NewID(id.String()), - Data: *base.NewDummyDecData(decData), - } -} +var Parameter = baseTypes.NewParameter(ID, DefaultData, validator) diff --git a/modules/metas/internal/parameters/dummy/parameter.pb.go b/modules/metas/internal/parameters/dummy/parameter.pb.go deleted file mode 100644 index a033c5a58..000000000 --- a/modules/metas/internal/parameters/dummy/parameter.pb.go +++ /dev/null @@ -1,367 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/metas/internal/parameters/dummy/parameter.proto - -package dummy - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type DummyParameter struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - Data base.DecData `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` -} - -func (m *DummyParameter) Reset() { *m = DummyParameter{} } -func (*DummyParameter) ProtoMessage() {} -func (*DummyParameter) Descriptor() ([]byte, []int) { - return fileDescriptor_7a688f7c03d55b51, []int{0} -} -func (m *DummyParameter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DummyParameter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DummyParameter.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DummyParameter) XXX_Merge(src proto.Message) { - xxx_messageInfo_DummyParameter.Merge(m, src) -} -func (m *DummyParameter) XXX_Size() int { - return m.Size() -} -func (m *DummyParameter) XXX_DiscardUnknown() { - xxx_messageInfo_DummyParameter.DiscardUnknown(m) -} - -var xxx_messageInfo_DummyParameter proto.InternalMessageInfo - -func init() { - proto.RegisterType((*DummyParameter)(nil), "persistence_sdk.modules.metas.internal.parameters.dummy.DummyParameter") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/metas/internal/parameters/dummy/parameter.proto", fileDescriptor_7a688f7c03d55b51) -} - -var fileDescriptor_7a688f7c03d55b51 = []byte{ - // 303 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x72, 0x2f, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4d, 0x2d, 0x49, 0x2c, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, 0xca, - 0x4b, 0xcc, 0xd1, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x4d, 0x2d, 0x49, 0x2d, 0x2a, 0xd6, 0x4f, 0x29, - 0xcd, 0xcd, 0xad, 0x44, 0x08, 0xe8, 0x15, 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0x99, 0xa3, 0x19, 0xa4, - 0x07, 0x35, 0x48, 0x0f, 0x6c, 0x90, 0x1e, 0xcc, 0x20, 0x3d, 0x84, 0x41, 0x7a, 0x60, 0x83, 0xa4, - 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x66, 0xe8, 0x83, 0x58, 0x10, 0xe3, 0xa4, 0xf4, 0xd1, 0xdd, - 0x55, 0x9c, 0x9c, 0x91, 0x9a, 0x9b, 0xa8, 0x5f, 0x52, 0x59, 0x90, 0x5a, 0xac, 0x9f, 0x94, 0x58, - 0x9c, 0xaa, 0x9f, 0x92, 0x9a, 0xec, 0x92, 0x58, 0x92, 0x08, 0xd5, 0xa0, 0x45, 0x58, 0x43, 0x66, - 0x0a, 0x44, 0xad, 0xd2, 0x3c, 0x46, 0x2e, 0x3e, 0x17, 0x90, 0xe5, 0x01, 0x30, 0xc7, 0x08, 0xd9, - 0x70, 0x31, 0x67, 0xc6, 0xa7, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x1b, 0xa9, 0xea, 0xa1, 0x7b, - 0x06, 0x62, 0x98, 0x1e, 0xd8, 0x30, 0x3d, 0x90, 0x61, 0x7a, 0x9e, 0x2e, 0x4e, 0x2c, 0x27, 0xee, - 0xc9, 0x33, 0x04, 0x31, 0x65, 0xba, 0x08, 0xb9, 0x70, 0xb1, 0xa4, 0x24, 0x96, 0x24, 0x4a, 0x30, - 0x81, 0xb5, 0x6b, 0x11, 0xa1, 0xdd, 0x05, 0xe2, 0x78, 0xa8, 0x19, 0x60, 0xdd, 0x56, 0x1c, 0x1d, - 0x0b, 0xe4, 0x19, 0x66, 0x2c, 0x90, 0x67, 0x70, 0xca, 0x3a, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, - 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, - 0x63, 0x39, 0x86, 0xa8, 0x80, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0xe4, - 0x20, 0xf2, 0xcf, 0x4b, 0x45, 0xe6, 0x06, 0xbb, 0x78, 0x13, 0x1b, 0x91, 0x49, 0x6c, 0xe0, 0x30, - 0x31, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x78, 0x34, 0xd7, 0x3a, 0x0a, 0x02, 0x00, 0x00, -} - -func (m *DummyParameter) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DummyParameter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DummyParameter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Data.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintParameter(dAtA []byte, offset int, v uint64) int { - offset -= sovParameter(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *DummyParameter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovParameter(uint64(l)) - l = m.Data.Size() - n += 1 + l + sovParameter(uint64(l)) - return n -} - -func sovParameter(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParameter(x uint64) (n int) { - return sovParameter(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *DummyParameter) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DummyParameter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DummyParameter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParameter(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParameter - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParameter(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParameter - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParameter - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParameter - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParameter = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParameter = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParameter = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/metas/internal/parameters/dummy/prototype.go b/modules/metas/internal/parameters/dummy/prototype.go deleted file mode 100644 index b390a673e..000000000 --- a/modules/metas/internal/parameters/dummy/prototype.go +++ /dev/null @@ -1,3 +0,0 @@ -package dummy - -var Parameter = NewParameter(ID, DefaultData) diff --git a/modules/metas/internal/parameters/dummy/validator.go b/modules/metas/internal/parameters/dummy/validator.go index cc0d80a52..2bb100018 100644 --- a/modules/metas/internal/parameters/dummy/validator.go +++ b/modules/metas/internal/parameters/dummy/validator.go @@ -1,32 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/parameters" ) func validator(i interface{}) error { switch value := i.(type) { - case DummyParameter: - data, Error := value.GetData().AsDec() - if Error != nil || value.GetID().Compare(ID) != 0 || data.IsNegative() { - return errors.InvalidParameter + case parameters.Parameter: + if value.GetID().Compare(ID) != 0 || value.GetData().(data.DecData).Get().IsNegative() { + return constants.InvalidParameter } return nil - case types.Data: - data, Error := value.AsDec() - if Error != nil || data.IsNegative() { - return errors.InvalidParameter + case data.DecData: + if value.Get().IsNegative() { + return constants.InvalidParameter } return nil default: - return errors.IncorrectFormat + return constants.IncorrectFormat } } diff --git a/modules/metas/internal/parameters/dummy/validator_test.go b/modules/metas/internal/parameters/dummy/validator_test.go new file mode 100644 index 000000000..6915a0b78 --- /dev/null +++ b/modules/metas/internal/parameters/dummy/validator_test.go @@ -0,0 +1,21 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package dummy + +import ( + "testing" + + "github.com/stretchr/testify/require" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/errors/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" +) + +func Test_Validator(t *testing.T) { + require.Equal(t, constants.IncorrectFormat, validator(baseIDs.NewStringID(""))) + require.Equal(t, nil, validator(Parameter)) + require.Equal(t, constants.InvalidParameter, validator(baseTypes.NewParameter(baseIDs.NewStringID(""), baseData.NewStringData(""), validator))) +} diff --git a/modules/metas/internal/parameters/prototype.go b/modules/metas/internal/parameters/prototype.go new file mode 100644 index 000000000..f75c3b0ab --- /dev/null +++ b/modules/metas/internal/parameters/prototype.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package parameters + +import ( + "github.com/AssetMantle/modules/modules/metas/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Parameters { + return baseHelpers.NewParameters(dummy.Parameter) +} diff --git a/modules/metas/internal/parameters/prototype_test.go b/modules/metas/internal/parameters/prototype_test.go new file mode 100644 index 000000000..3d3acdd3d --- /dev/null +++ b/modules/metas/internal/parameters/prototype_test.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package parameters + +import ( + "fmt" + "reflect" + "testing" + + "github.com/AssetMantle/modules/modules/metas/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Parameters + }{ + {"+ve", baseHelpers.NewParameters(dummy.Parameter)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Prototype(); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Prototype() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/metas/internal/queries/meta/grpc_query.go b/modules/metas/internal/queries/meta/grpc_query.go deleted file mode 100644 index b8973128a..000000000 --- a/modules/metas/internal/queries/meta/grpc_query.go +++ /dev/null @@ -1,29 +0,0 @@ -package meta - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/key" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type queryServer struct { - queryKeeper -} - -var _ QueryServer = queryServer{} - -func (queryServer queryServer) Get(ctx context.Context, queryRequest *QueryRequest) (*QueryResponse, error) { - cntx := sdkTypes.UnwrapSDKContext(ctx) - - keyr := key.FromID(base.NewID(queryRequest.MetaID.String())) - - collection := queryServer.queryKeeper.mapper.NewCollection(cntx) - response := newQueryResponse(collection.Fetch(keyr), nil) - return &response, response.GetError() - -} - -func NewQueryServerImpl(keeper queryKeeper) QueryServer { - return &queryServer{keeper} -} diff --git a/modules/metas/internal/queries/meta/keeper.go b/modules/metas/internal/queries/meta/keeper.go new file mode 100644 index 000000000..b99a2c3b4 --- /dev/null +++ b/modules/metas/internal/queries/meta/keeper.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package meta + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/metas/internal/key" + "github.com/AssetMantle/modules/schema/helpers" +) + +type queryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.QueryKeeper = (*queryKeeper)(nil) + +func (queryKeeper queryKeeper) Enquire(context sdkTypes.Context, queryRequest helpers.QueryRequest) helpers.QueryResponse { + return newQueryResponse(queryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(queryRequestFromInterface(queryRequest).DataID)), nil) +} + +func (queryKeeper queryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + queryKeeper.mapper = mapper + return queryKeeper +} + +func keeperPrototype() helpers.QueryKeeper { + return queryKeeper{} +} diff --git a/modules/metas/internal/queries/meta/keeper_test.go b/modules/metas/internal/queries/meta/keeper_test.go index 219bbfab4..107c5925a 100644 --- a/modules/metas/internal/queries/meta/keeper_test.go +++ b/modules/metas/internal/queries/meta/keeper_test.go @@ -1,76 +1,149 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package meta import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "testing" + + "github.com/AssetMantle/modules/modules/metas/internal/key" + "github.com/AssetMantle/modules/modules/metas/internal/mappable" + "github.com/AssetMantle/modules/modules/metas/internal/parameters" + "github.com/AssetMantle/modules/schema" + base2 "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/ids/base" ) -func CreateTestInput2(t *testing.T) (sdkTypes.Context, helpers.Keeper) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +type TestKeepers struct { + MetaKeeper helpers.QueryKeeper +} + +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() + storeKey := sdkTypes.NewKVStoreKey("test") paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) - mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) - paramsKeeper := params.NewKeeper( - Codec, - paramsStoreKey, - paramsTransientStoreKeys, - ) - Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) - - testQueryKeeper := keeperPrototype().Initialize(mapper, Parameters, []interface{}{}) + keepers := TestKeepers{ + MetaKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.QueryKeeper), + } - return context, testQueryKeeper + return context, keepers, Mapper, Parameters } -func Test_Query_Keeper_Meta(t *testing.T) { - - context, keepers := CreateTestInput2(t) - typeID := base.NewID("I") - hashID := base.NewID("HashID") - metaID := key.NewMetaID(typeID, hashID) - keepers.(queryKeeper).mapper.NewCollection(context).Add(mappable.NewMeta(base.NewIDData(hashID))) +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryKeeper + }{ + {"+ve", queryKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - testQueryRequest := newQueryRequest(metaID) - require.Equal(t, queryResponse{Success: true, Error: nil, List: keepers.(queryKeeper).mapper.NewCollection(context).Fetch(key.FromID(metaID)).GetList()}, keepers.(queryKeeper).LegacyEnquire(context, testQueryRequest)) +func Test_queryKeeper_Enquire(t *testing.T) { + context, keepers, Mapper, _ := createTestInput(t) + testDataID := base.NewDataID(base2.NewStringData("Data")) + keepers.MetaKeeper.(queryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(base2.NewStringData("Data"))) + type fields struct { + mapper helpers.Mapper + } + type args struct { + context sdkTypes.Context + queryRequest helpers.QueryRequest + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryResponse + }{ + {"+ve", fields{Mapper}, args{context, newQueryRequest(testDataID)}, newQueryResponse(keepers.MetaKeeper.(queryKeeper).mapper.NewCollection(context).Fetch(key.NewKey(queryRequestFromInterface(newQueryRequest(testDataID)).DataID)), nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryKeeper := queryKeeper{ + mapper: tt.fields.mapper, + } + if got := queryKeeper.Enquire(tt.args.context, tt.args.queryRequest); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Enquire() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_queryKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + in2 []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper}, args{Mapper, Parameters, []interface{}{}}, queryKeeper{Mapper}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryKeeper := queryKeeper{ + mapper: tt.fields.mapper, + } + if got := queryKeeper.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/metas/internal/queries/meta/query.go b/modules/metas/internal/queries/meta/query.go index a9885d9f0..320b7ae76 100644 --- a/modules/metas/internal/queries/meta/query.go +++ b/modules/metas/internal/queries/meta/query.go @@ -1,21 +1,15 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package meta import ( - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/helpers/base" + "github.com/AssetMantle/modules/modules/metas/internal/module" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" ) -var _ helpers.QueryRequest = (*QueryRequest)(nil) -var _ helpers.QueryResponse = (*QueryResponse)(nil) - -var Query = base.NewQuery( +var Query = baseHelpers.NewQuery( "metas", "", "", @@ -25,5 +19,6 @@ var Query = base.NewQuery( requestPrototype, responsePrototype, keeperPrototype, - flags.MetaID, + + constants.DataID, ) diff --git a/modules/metas/internal/queries/meta/query.pb.go b/modules/metas/internal/queries/meta/query.pb.go deleted file mode 100644 index 0356cb72b..000000000 --- a/modules/metas/internal/queries/meta/query.pb.go +++ /dev/null @@ -1,673 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/metas/internal/queries/meta/query.proto - -package meta - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - github_com_persistenceOne_persistenceSDK_schema_helpers "github.com/persistenceOne/persistenceSDK/schema/helpers" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type QueryRequest struct { - MetaID base.ID `protobuf:"bytes,1,opt,name=meta_i_d,json=metaID,proto3" json:"meta_i_d" valid:"required~required MetaID missing"` -} - -func (m *QueryRequest) Reset() { *m = QueryRequest{} } -func (m *QueryRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRequest) ProtoMessage() {} -func (*QueryRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_82cfb4622e25f46f, []int{0} -} -func (m *QueryRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRequest.Merge(m, src) -} -func (m *QueryRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRequest proto.InternalMessageInfo - -type QueryResponse struct { - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` - List []github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable `protobuf:"bytes,3,rep,name=list,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable" json:"list"` -} - -func (m *QueryResponse) Reset() { *m = QueryResponse{} } -func (m *QueryResponse) String() string { return proto.CompactTextString(m) } -func (*QueryResponse) ProtoMessage() {} -func (*QueryResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_82cfb4622e25f46f, []int{1} -} -func (m *QueryResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryResponse.Merge(m, src) -} -func (m *QueryResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryRequest)(nil), "persistence_sdk.modules.metas.internal.queries.meta.QueryRequest") - proto.RegisterType((*QueryResponse)(nil), "persistence_sdk.modules.metas.internal.queries.meta.QueryResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/metas/internal/queries/meta/query.proto", fileDescriptor_82cfb4622e25f46f) -} - -var fileDescriptor_82cfb4622e25f46f = []byte{ - // 461 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0x31, 0x8b, 0xd4, 0x40, - 0x14, 0xc7, 0x33, 0xb7, 0xde, 0xb9, 0x17, 0xb5, 0x09, 0x07, 0xae, 0x8b, 0x24, 0x21, 0x20, 0x2c, - 0x16, 0x33, 0x72, 0xd7, 0x5d, 0xa3, 0x2e, 0x0b, 0x7a, 0xe8, 0x21, 0xc6, 0x4e, 0x84, 0x65, 0x36, - 0x79, 0x66, 0x07, 0x93, 0x99, 0xec, 0xbc, 0x89, 0x70, 0x8d, 0x85, 0x95, 0x60, 0x23, 0xf8, 0x05, - 0xae, 0xb3, 0xb2, 0xf6, 0x2b, 0x5c, 0x79, 0x60, 0x23, 0x16, 0x8b, 0xec, 0x5a, 0x58, 0xfb, 0x09, - 0x24, 0x93, 0x2c, 0x2e, 0x5b, 0x1d, 0xda, 0x84, 0x79, 0x6f, 0x92, 0x5f, 0x7e, 0xf3, 0x9f, 0xe7, - 0xde, 0x2d, 0x41, 0xa3, 0x40, 0x03, 0x32, 0x81, 0x31, 0xa6, 0xaf, 0x58, 0xa1, 0xd2, 0x2a, 0x07, - 0x64, 0x05, 0x18, 0x8e, 0x4c, 0x48, 0x03, 0x5a, 0xf2, 0x9c, 0xcd, 0x2a, 0xd0, 0xa2, 0x6d, 0xdb, - 0xe2, 0x84, 0x96, 0x5a, 0x19, 0xe5, 0x1d, 0x6c, 0x00, 0x68, 0x0b, 0xa0, 0x16, 0x40, 0x57, 0x00, - 0xda, 0x02, 0x6c, 0xbb, 0xbf, 0x97, 0xa9, 0x4c, 0xd9, 0xef, 0x59, 0xbd, 0x6a, 0x50, 0xfd, 0x9b, - 0x99, 0x52, 0x59, 0x0e, 0x8c, 0x97, 0x82, 0x71, 0x29, 0x95, 0xe1, 0x46, 0x28, 0x89, 0xed, 0xee, - 0xed, 0x4d, 0x53, 0x4c, 0xa6, 0x50, 0x70, 0x66, 0x4e, 0x4a, 0x40, 0x36, 0xe1, 0x08, 0x4c, 0xa4, - 0xcd, 0xbb, 0xd1, 0x7b, 0xe2, 0x5e, 0x7d, 0x5a, 0x4b, 0xc6, 0x30, 0xab, 0x00, 0x8d, 0x37, 0x73, - 0xbb, 0xf5, 0x8f, 0xc7, 0x62, 0x9c, 0xf6, 0x48, 0x48, 0x06, 0x57, 0xf6, 0x6f, 0xd1, 0x4d, 0xf1, - 0x86, 0x47, 0x2d, 0x8f, 0xd6, 0x3c, 0x7a, 0x34, 0x1a, 0xde, 0x39, 0x9b, 0x07, 0xce, 0xef, 0x79, - 0x30, 0x78, 0xcd, 0x73, 0x91, 0x1e, 0x46, 0x1a, 0x66, 0x95, 0xd0, 0x90, 0xbe, 0x59, 0x2d, 0xc2, - 0x63, 0x30, 0xfc, 0x68, 0x14, 0x16, 0x02, 0x51, 0xc8, 0x2c, 0x8a, 0x77, 0x0a, 0xdb, 0x38, 0xec, - 0xbe, 0x3b, 0x0d, 0x9c, 0x5f, 0xa7, 0x81, 0x13, 0x7d, 0x22, 0xee, 0xb5, 0xd6, 0x06, 0x4b, 0x25, - 0x11, 0xbc, 0x9e, 0x7b, 0x19, 0xab, 0x24, 0x01, 0x44, 0x6b, 0xd3, 0x8d, 0x57, 0xa5, 0xb7, 0xe7, - 0x6e, 0x83, 0xd6, 0x4a, 0xf7, 0xb6, 0x42, 0x32, 0xd8, 0x8d, 0x9b, 0xc2, 0x7b, 0xe1, 0x5e, 0xca, - 0x05, 0x9a, 0x5e, 0x27, 0xec, 0x0c, 0x76, 0x87, 0x0f, 0x6b, 0xa7, 0xef, 0xf3, 0xe0, 0x5e, 0x26, - 0xcc, 0xb4, 0x9a, 0xd0, 0x44, 0x15, 0x6c, 0xed, 0x30, 0x4f, 0x24, 0xac, 0x97, 0xcf, 0x46, 0x8f, - 0x56, 0x51, 0x4d, 0x21, 0xaf, 0x37, 0xe8, 0x31, 0x2f, 0x4b, 0x3e, 0xc9, 0x21, 0xb6, 0xd4, 0xbf, - 0xa6, 0xfb, 0x5f, 0x88, 0xbb, 0x6d, 0x4d, 0xbd, 0xcf, 0xc4, 0xed, 0x3c, 0x00, 0xe3, 0xdd, 0xa7, - 0xff, 0x70, 0xbf, 0x74, 0x3d, 0xfb, 0xfe, 0xf0, 0x7f, 0x10, 0x4d, 0x60, 0x51, 0xf0, 0xf6, 0xeb, - 0xcf, 0x8f, 0x5b, 0x37, 0xbc, 0xeb, 0xeb, 0x27, 0x6b, 0x67, 0xb4, 0x7e, 0x0e, 0x5f, 0x9e, 0x2d, - 0x7c, 0x72, 0xbe, 0xf0, 0xc9, 0x8f, 0x85, 0x4f, 0x3e, 0x2c, 0x7d, 0xe7, 0x7c, 0xe9, 0x3b, 0xdf, - 0x96, 0xbe, 0xf3, 0xfc, 0xf1, 0x85, 0x53, 0xba, 0xc0, 0xe8, 0x4f, 0x76, 0xec, 0x80, 0x1d, 0xfc, - 0x09, 0x00, 0x00, 0xff, 0xff, 0x0f, 0x25, 0x16, 0x38, 0x38, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - Get(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Get(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) { - out := new(QueryResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.metas.internal.queries.meta.Query/Get", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - Get(context.Context, *QueryRequest) (*QueryResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Get(ctx context.Context, req *QueryRequest) (*QueryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Get not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Get_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Get(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.metas.internal.queries.meta.Query/Get", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Get(ctx, req.(*QueryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.metas.internal.queries.meta.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Get", - Handler: _Query_Get_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/metas/internal/queries/meta/query.proto", -} - -func (m *QueryRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MetaID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.List) > 0 { - for iNdEx := len(m.List) - 1; iNdEx >= 0; iNdEx-- { - { - size := m.List[iNdEx].Size() - i -= size - if _, err := m.List[iNdEx].MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Error) > 0 { - i -= len(m.Error) - copy(dAtA[i:], m.Error) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Error))) - i-- - dAtA[i] = 0x12 - } - if m.Success { - i-- - if m.Success { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.MetaID.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Success { - n += 2 - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.List) > 0 { - for _, e := range m.List { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MetaID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MetaID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Success = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field List", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var v github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable - m.List = append(m.List, v) - if err := m.List[len(m.List)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/metas/internal/queries/meta/query.pb.gw.go b/modules/metas/internal/queries/meta/query.pb.gw.go deleted file mode 100644 index e699ce918..000000000 --- a/modules/metas/internal/queries/meta/query.pb.gw.go +++ /dev/null @@ -1,166 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: persistence_sdk/modules/metas/internal/queries/meta/query.proto - -/* -Package meta is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package meta - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage - -var ( - filter_Query_Get_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Get_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Get_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Get(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Get_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Get_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Get(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features (such as grpc.SendHeader, etc) to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Get_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Get_0(rctx, inboundMarshaler, server, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Get_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Get_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Get_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Get_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Get_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"persistence", "metas", "meta"}, "", runtime.AssumeColonVerbOpt(true))) -) - -var ( - forward_Query_Get_0 = runtime.ForwardResponseMessage -) diff --git a/modules/metas/internal/queries/meta/request.go b/modules/metas/internal/queries/meta/request.go index 59697f27b..d0f61a55d 100644 --- a/modules/metas/internal/queries/meta/request.go +++ b/modules/metas/internal/queries/meta/request.go @@ -1,81 +1,74 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package meta import ( "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/cosmos/cosmos-sdk/client/context" + + "github.com/AssetMantle/modules/modules/metas/internal/common" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" ) -var _ helpers.QueryRequest = (*QueryRequest)(nil) +type queryRequest struct { + ids.DataID `json:"dataID" valid:"required~required field dataID missing"` +} + +var _ helpers.QueryRequest = (*queryRequest)(nil) -// QueryRequest godoc -// @Summary Query meta using meta id -// @Descrption Able to query the meta data +// Validate godoc +// @Summary Search for metadata by meta ID +// @Description Able to query the metadata // @Accept json // @Produce json // @Tags Metas -// @Param metaID path string true "meta ID" -// @Success 200 {object} queryResponse "A successful query response" -// @Failure default {object} queryResponse "An unexpected error response." -// @Router /metas/metas/{metaID} [get] -func (queryRequest QueryRequest) Validate() error { - _, Error := govalidator.ValidateStruct(queryRequest) - return Error -} - -func (queryRequest QueryRequest) FromCLI(cliCommand helpers.CLICommand, _ client.Context) helpers.QueryRequest { - return newQueryRequest(base.NewID(cliCommand.ReadString(flags.MetaID))) -} - -func (queryRequest QueryRequest) FromMap(vars map[string]string) helpers.QueryRequest { - return newQueryRequest(base.NewID(vars[Query.GetName()])) +// @Param dataID path string true "Unique identifier of metadata value." +// @Success 200 {object} queryResponse "Message for a successful query response" +// @Failure default {object} queryResponse "Message for an unexpected error response." +// @Router /metas/metas/{dataID} [get] +func (queryRequest queryRequest) Validate() error { + _, err := govalidator.ValidateStruct(queryRequest) + return err } - -func (queryRequest QueryRequest) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryRequest) +func (queryRequest) FromCLI(cliCommand helpers.CLICommand, _ context.CLIContext) (helpers.QueryRequest, error) { + if dataID, err := baseIDs.ReadDataID(cliCommand.ReadString(constants.DataID)); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(dataID), nil + } } - -func (queryRequest QueryRequest) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryRequest, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest) FromMap(vars map[string]string) (helpers.QueryRequest, error) { + if dataID, err := baseIDs.ReadDataID(vars[Query.GetName()]); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(dataID), nil } - - return queryRequest, nil } -func (queryRequest QueryRequest) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryRequest) +func (queryRequest queryRequest) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryRequest) } - -func (queryRequest QueryRequest) LegacyAminoDecode(bytes []byte) (helpers.QueryRequest, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest queryRequest) Decode(bytes []byte) (helpers.QueryRequest, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryRequest); err != nil { + return nil, err } return queryRequest, nil } func requestPrototype() helpers.QueryRequest { - return QueryRequest{} + return queryRequest{} } - -func queryRequestFromInterface(request helpers.QueryRequest) QueryRequest { +func queryRequestFromInterface(request helpers.QueryRequest) queryRequest { switch value := request.(type) { - case *QueryRequest: - return *value + case queryRequest: + return value default: - return QueryRequest{} + return queryRequest{} } } - -func newQueryRequest(metaID types.ID) helpers.QueryRequest { - return QueryRequest{MetaID: *base.NewID(metaID.String())} +func newQueryRequest(dataID ids.DataID) helpers.QueryRequest { + return queryRequest{DataID: dataID} } diff --git a/modules/metas/internal/queries/meta/request_test.go b/modules/metas/internal/queries/meta/request_test.go index 8c6aff77d..fbeeebfd6 100644 --- a/modules/metas/internal/queries/meta/request_test.go +++ b/modules/metas/internal/queries/meta/request_test.go @@ -1,58 +1,251 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package meta import ( - "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/common" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/spf13/viper" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/metas/internal/common" + base2 "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/ids/base" ) -func Test_Meta_Request(t *testing.T) { +var ( + testDataID = base.NewDataID(base2.NewStringData("Data")) +) + +func Test_newQueryRequest(t *testing.T) { + type args struct { + dataID ids.DataID + } + tests := []struct { + name string + args args + want helpers.QueryRequest + }{ + {"+ve with nil", args{base.PrototypeDataID()}, queryRequest{base.PrototypeDataID()}}, + {"+ve", args{testDataID}, queryRequest{testDataID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newQueryRequest(tt.args.dataID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newQueryRequest() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequestFromInterface(t *testing.T) { + type args struct { + request helpers.QueryRequest + } + tests := []struct { + name string + args args + want queryRequest + }{ + {"+ve", args{newQueryRequest(testDataID)}, queryRequest{testDataID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := queryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("queryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() +func Test_queryRequest_Decode(t *testing.T) { + encodedQuery, err := common.Codec.MarshalJSON(newQueryRequest(testDataID)) + require.NoError(t, err) + encodedQuery1, err := common.Codec.MarshalJSON(newQueryRequest(base.PrototypeDataID())) + require.NoError(t, err) + type fields struct { + DataID ids.DataID + } + type args struct { + bytes []byte + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testDataID}, args{encodedQuery}, newQueryRequest(testDataID), false}, + {"+ve with nil", fields{base.PrototypeDataID()}, args{encodedQuery1}, newQueryRequest(base.PrototypeDataID()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + DataID: tt.fields.DataID, + } + got, err := queryRequest.Decode(tt.args.bytes) + if (err != nil) != tt.wantErr { + t.Errorf("Decode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Decode() got = %v, want %v", got, tt.want) + } + }) + } +} - testMetaID := base.NewID("MetaID") - testQueryRequest := newQueryRequest(testMetaID) - require.Equal(t, nil, testQueryRequest.Validate()) - require.Equal(t, queryRequest{}, requestPrototype()) +func Test_queryRequest_Encode(t *testing.T) { + encodedQuery, err := common.Codec.MarshalJSON(newQueryRequest(testDataID)) + require.NoError(t, err) + encodedQuery1, err := common.Codec.MarshalJSON(newQueryRequest(base.PrototypeDataID())) + require.NoError(t, err) + type fields struct { + DataID ids.DataID + } + tests := []struct { + name string + fields fields + want []byte + wantErr bool + }{ + {"+ve", fields{testDataID}, encodedQuery, false}, + {"+ve with nil", fields{base.PrototypeDataID()}, encodedQuery1, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + DataID: tt.fields.DataID, + } + got, err := queryRequest.Encode() + if (err != nil) != tt.wantErr { + t.Errorf("Encode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Encode() got = %v, want %v", got, tt.want) + } + }) + } +} - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.MetaID}) - cliContext := context.NewCLIContext().WithCodec(Codec) - require.Equal(t, newQueryRequest(base.NewID("")), queryRequest{}.FromCLI(cliCommand, cliContext)) +func Test_queryRequest_FromCLI(t *testing.T) { + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.DataID}) + viper.Set(constants.DataID.GetName(), testDataID.String()) + type fields struct { + DataID ids.DataID + } + type args struct { + cliCommand helpers.CLICommand + in1 context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testDataID}, args{cliCommand, context.CLIContext{}}, newQueryRequest(testDataID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + DataID: tt.fields.DataID, + } + got, err := qu.FromCLI(tt.args.cliCommand, tt.args.in1) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} +func Test_queryRequest_FromMap(t *testing.T) { vars := make(map[string]string) - vars["metas"] = "randomString" - require.Equal(t, newQueryRequest(base.NewID("randomString")), queryRequest{}.FromMap(vars)) - - encodedRequest, Error := testQueryRequest.LegacyAminoEncode() - encodedResult, _ := common.LegacyAminoCodec.MarshalJSON(testQueryRequest) - require.Equal(t, encodedResult, encodedRequest) - require.Nil(t, Error) - - decodedRequest, Error := queryRequest{}.LegacyAminoDecode(encodedRequest) - require.Equal(t, testQueryRequest, decodedRequest) - require.Equal(t, nil, Error) - - randomDecode, _ := queryRequest{}.LegacyAminoDecode(base.NewID("").Bytes()) - require.Equal(t, nil, randomDecode) - require.Equal(t, testQueryRequest, queryRequestFromInterface(testQueryRequest)) - require.Equal(t, queryRequest{}, queryRequestFromInterface(nil)) + vars[Query.GetName()] = testDataID.String() + vars1 := make(map[string]string) + vars1[Query.GetName()] = testDataID.String() + type fields struct { + DataID ids.DataID + } + type args struct { + vars map[string]string + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testDataID}, args{vars}, newQueryRequest(testDataID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + DataID: tt.fields.DataID, + } + got, err := qu.FromMap(tt.args.vars) + if (err != nil) != tt.wantErr { + t.Errorf("FromMap() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromMap() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequest_Validate(t *testing.T) { + type fields struct { + DataID ids.DataID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testDataID}, false}, + {"+ve", fields{base.PrototypeDataID()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + DataID: tt.fields.DataID, + } + if err := queryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryRequest + }{ + {"+ve", queryRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/metas/internal/queries/meta/response.go b/modules/metas/internal/queries/meta/response.go index ac3c64fec..0b19c7b6e 100644 --- a/modules/metas/internal/queries/meta/response.go +++ b/modules/metas/internal/queries/meta/response.go @@ -1,64 +1,49 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package meta import ( - "errors" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/metas/internal/common" + "github.com/AssetMantle/modules/schema/helpers" ) -var _ helpers.QueryResponse = (*QueryResponse)(nil) +type queryResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` + List []helpers.Mappable `json:"list"` +} + +var _ helpers.QueryResponse = (*queryResponse)(nil) -func (queryResponse QueryResponse) IsSuccessful() bool { +func (queryResponse queryResponse) IsSuccessful() bool { return queryResponse.Success } -func (queryResponse QueryResponse) GetError() error { - return errors.New(queryResponse.Error) +func (queryResponse queryResponse) GetError() error { + return queryResponse.Error } -func (queryResponse QueryResponse) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryResponse) +func (queryResponse queryResponse) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryResponse) } -func (queryResponse QueryResponse) LegacyAminoDecode(bytes []byte) (helpers.QueryResponse, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error +func (queryResponse queryResponse) Decode(bytes []byte) (helpers.QueryResponse, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryResponse); err != nil { + return nil, err } - return &queryResponse, nil -} -func (queryResponse QueryResponse) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryResponse) -} - -func (queryResponse QueryResponse) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryResponse, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error - } - return &queryResponse, nil + return queryResponse, nil } - func responsePrototype() helpers.QueryResponse { - return &QueryResponse{} + return queryResponse{} } - -func newQueryResponse(collection helpers.Collection, error error) QueryResponse { +func newQueryResponse(collection helpers.Collection, error error) helpers.QueryResponse { success := true if error != nil { success = false - return QueryResponse{ - Success: success, - Error: "yes", - List: collection.GetList(), - } } - return QueryResponse{ + + return queryResponse{ Success: success, - Error: "no", + Error: error, List: collection.GetList(), } - } diff --git a/modules/metas/internal/queries/meta/response_test.go b/modules/metas/internal/queries/meta/response_test.go index 1acaa1792..1fd12d053 100644 --- a/modules/metas/internal/queries/meta/response_test.go +++ b/modules/metas/internal/queries/meta/response_test.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package meta @@ -17,17 +15,17 @@ import ( "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/mapper" - "github.com/persistenceOne/persistenceSDK/schema" + "github.com/AssetMantle/modules/modules/metas/internal/common" + "github.com/AssetMantle/modules/modules/metas/internal/mapper" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/errors/constants" ) func CreateTestInput(t *testing.T) sdkTypes.Context { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() @@ -56,21 +54,21 @@ func Test_Meta_Response(t *testing.T) { collection := mapper.Prototype().NewCollection(context) testQueryResponse := newQueryResponse(collection, nil) - testQueryResponseWithError := newQueryResponse(collection, errors.IncorrectFormat) + testQueryResponseWithError := newQueryResponse(collection, constants.IncorrectFormat) require.Equal(t, true, testQueryResponse.IsSuccessful()) require.Equal(t, false, testQueryResponseWithError.IsSuccessful()) require.Equal(t, nil, testQueryResponse.GetError()) - require.Equal(t, errors.IncorrectFormat, testQueryResponseWithError.GetError()) + require.Equal(t, constants.IncorrectFormat, testQueryResponseWithError.GetError()) - encodedResponse, _ := testQueryResponse.LegacyAminoEncode() - bytes, _ := common.LegacyAminoCodec.MarshalJSON(testQueryResponse) + encodedResponse, _ := testQueryResponse.Encode() + bytes, _ := common.Codec.MarshalJSON(testQueryResponse) require.Equal(t, bytes, encodedResponse) - decodedResponse, _ := queryResponse{}.LegacyAminoDecode(bytes) + decodedResponse, _ := queryResponse{}.Decode(bytes) require.Equal(t, testQueryResponse, decodedResponse) - decodedResponse2, _ := queryResponse{}.LegacyAminoDecode([]byte{}) + decodedResponse2, _ := queryResponse{}.Decode([]byte{}) require.Equal(t, nil, decodedResponse2) require.Equal(t, queryResponse{}, responsePrototype()) diff --git a/modules/metas/internal/queries/prototype.go b/modules/metas/internal/queries/prototype.go new file mode 100644 index 000000000..135d0c4cc --- /dev/null +++ b/modules/metas/internal/queries/prototype.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queries + +import ( + "github.com/AssetMantle/modules/modules/metas/internal/queries/meta" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Queries { + return baseHelpers.NewQueries( + meta.Query, + ) +} diff --git a/modules/metas/internal/queries/prototype_test.go b/modules/metas/internal/queries/prototype_test.go new file mode 100644 index 000000000..2df0492f0 --- /dev/null +++ b/modules/metas/internal/queries/prototype_test.go @@ -0,0 +1,19 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queries + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/metas/internal/queries/meta" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Get("metas").GetName(), baseHelpers.NewQueries( + meta.Query, + ).Get("metas").GetName()) +} diff --git a/modules/metas/internal/simulator/constants.go b/modules/metas/internal/simulator/constants.go new file mode 100644 index 000000000..0e23f0a61 --- /dev/null +++ b/modules/metas/internal/simulator/constants.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +const OpWeightSubmitTextProposal = "op_weight_submit_text_proposal" +const DefaultWeightTextProposal = 1 + +const OpWeightMsg = "OpWeightMsg" +const DefaultWeightMsg = 1 diff --git a/modules/metas/internal/simulator/genesis.go b/modules/metas/internal/simulator/genesis.go new file mode 100644 index 000000000..1c6913bdb --- /dev/null +++ b/modules/metas/internal/simulator/genesis.go @@ -0,0 +1,46 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "math/rand" + + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + + "github.com/AssetMantle/modules/modules/metas/internal/common" + "github.com/AssetMantle/modules/modules/metas/internal/key" + "github.com/AssetMantle/modules/modules/metas/internal/mappable" + metasModule "github.com/AssetMantle/modules/modules/metas/internal/module" + "github.com/AssetMantle/modules/modules/metas/internal/parameters" + "github.com/AssetMantle/modules/modules/metas/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/data" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + parameters2 "github.com/AssetMantle/modules/schema/parameters" + baseSimulation "github.com/AssetMantle/modules/simulation/schema/types/base" +) + +func (simulator) RandomizedGenesisState(simulationState *module.SimulationState) { + var Data data.Data + + simulationState.AppParams.GetOrGenerate( + simulationState.Cdc, + dummy.ID.String(), + &Data, + simulationState.Rand, + func(rand *rand.Rand) { Data = baseData.NewDecData(sdkTypes.NewDecWithPrec(int64(rand.Intn(99)), 2)) }, + ) + + mappableList := make([]helpers.Mappable, simulationState.Rand.Intn(99)) + + for i := range mappableList { + mappableList[i] = mappable.NewMappable(baseSimulation.GenerateRandomData(simulationState.Rand)) + } + + genesisState := baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, nil, parameters.Prototype().GetList()).Initialize(mappableList, []parameters2.Parameter{dummy.Parameter.Mutate(Data)}) + + simulationState.GenState[metasModule.Name] = common.Codec.MustMarshalJSON(genesisState) +} diff --git a/modules/metas/internal/simulator/operations.go b/modules/metas/internal/simulator/operations.go index e97b97359..3c3884187 100644 --- a/modules/metas/internal/simulator/operations.go +++ b/modules/metas/internal/simulator/operations.go @@ -1,20 +1,18 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( + "math/rand" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" - sdkModuleSimulation "github.com/cosmos/cosmos-sdk/x/simulation" - "math/rand" + "github.com/cosmos/cosmos-sdk/x/simulation" ) -func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec.JSONMarshaler) simulation.WeightedOperation { +func (simulator) WeightedOperations(appParams simulation.AppParams, codec *codec.Codec) simulation.WeightedOperations { var weightMsg int appParams.GetOrGenerate(codec, OpWeightMsg, &weightMsg, nil, @@ -23,10 +21,12 @@ func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec. }, ) - return sdkModuleSimulation.NewWeightedOperation( - weightMsg, - simulateMsg(), - ) + return simulation.WeightedOperations{ + simulation.NewWeightedOperation( + weightMsg, + simulateMsg(), + ), + } } func simulateMsg() simulation.Operation { diff --git a/modules/metas/internal/simulator/params.go b/modules/metas/internal/simulator/params.go index bcc08585e..17df0d0f7 100644 --- a/modules/metas/internal/simulator/params.go +++ b/modules/metas/internal/simulator/params.go @@ -1,29 +1,28 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - simTypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "math/rand" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/simulation" + + "github.com/AssetMantle/modules/modules/metas/internal/common" + "github.com/AssetMantle/modules/modules/metas/internal/module" + "github.com/AssetMantle/modules/modules/metas/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/data/base" ) -func (simulator) ParamChangeList(_ *rand.Rand) []simTypes.ParamChange { - return []simTypes.ParamChange{ +func (simulator) ParamChangeList(_ *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange(module.Name, dummy.ID.String(), func(r *rand.Rand) string { - bytes, Error := common.LegacyAminoCodec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdkTypes.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) - if Error != nil { - panic(Error) + bytes, err := common.Codec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdk.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) + if err != nil { + panic(err) } return string(bytes) }), diff --git a/modules/metas/internal/simulator/proposals.go b/modules/metas/internal/simulator/proposals.go index e12b080e4..ce4efd54f 100644 --- a/modules/metas/internal/simulator/proposals.go +++ b/modules/metas/internal/simulator/proposals.go @@ -1,33 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( + "math/rand" + sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" - simulation2 "github.com/cosmos/cosmos-sdk/x/simulation" - "math/rand" + "github.com/cosmos/cosmos-sdk/x/simulation" ) func (simulator) WeightedProposalContentList() []simulation.WeightedProposalContent { return []simulation.WeightedProposalContent{ - simulation2.NewWeightedProposalContent( - OpWeightSubmitTextProposal, - DefaultWeightTextProposal, - contentSimulatorFunc(), - ), + { + AppParamsKey: OpWeightSubmitTextProposal, + DefaultWeight: DefaultWeightTextProposal, + ContentSimulatorFn: simulateTextProposalContent, + }, } } -func contentSimulatorFunc() simulation.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) simulation.Content { - return types.NewTextProposal( - simulation.RandStringOfLength(r, 140), - simulation.RandStringOfLength(r, 5000), - ) - } +func simulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Account) types.Content { + return types.NewTextProposal( + simulation.RandStringOfLength(r, 140), + simulation.RandStringOfLength(r, 5000), + ) } diff --git a/modules/metas/internal/simulator/prototype.go b/modules/metas/internal/simulator/prototype.go new file mode 100644 index 000000000..3da39d69f --- /dev/null +++ b/modules/metas/internal/simulator/prototype.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +func Prototype() helpers.Simulator { + return newSimulator() +} diff --git a/modules/metas/internal/simulator/prototype_test.go b/modules/metas/internal/simulator/prototype_test.go new file mode 100644 index 000000000..4352a8d45 --- /dev/null +++ b/modules/metas/internal/simulator/prototype_test.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype(), newSimulator()) +} diff --git a/modules/metas/internal/simulator/simulator.go b/modules/metas/internal/simulator/simulator.go new file mode 100644 index 000000000..d963561c2 --- /dev/null +++ b/modules/metas/internal/simulator/simulator.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +type simulator struct{} + +var _ helpers.Simulator = (*simulator)(nil) + +func newSimulator() helpers.Simulator { + return simulator{} +} diff --git a/modules/metas/internal/simulator/simulator_test.go b/modules/metas/internal/simulator/simulator_test.go new file mode 100644 index 000000000..1a738209a --- /dev/null +++ b/modules/metas/internal/simulator/simulator_test.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func Test_newSimulator(t *testing.T) { + require.Equal(t, newSimulator(), simulator{}) +} diff --git a/modules/metas/internal/transactions/prototype.go b/modules/metas/internal/transactions/prototype.go new file mode 100644 index 000000000..3d0d3b516 --- /dev/null +++ b/modules/metas/internal/transactions/prototype.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transactions + +import ( + "github.com/AssetMantle/modules/modules/metas/internal/transactions/reveal" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Transactions { + return baseHelpers.NewTransactions( + reveal.Transaction, + ) +} diff --git a/modules/metas/internal/transactions/prototype_test.go b/modules/metas/internal/transactions/prototype_test.go new file mode 100644 index 000000000..921f2d46a --- /dev/null +++ b/modules/metas/internal/transactions/prototype_test.go @@ -0,0 +1,19 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transactions + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/metas/internal/transactions/reveal" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Get("reveal").GetName(), baseHelpers.NewTransactions( + reveal.Transaction, + ).Get("reveal").GetName()) +} diff --git a/modules/metas/internal/transactions/reveal/keeper.go b/modules/metas/internal/transactions/reveal/keeper.go new file mode 100644 index 000000000..720227429 --- /dev/null +++ b/modules/metas/internal/transactions/reveal/keeper.go @@ -0,0 +1,46 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package reveal + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/metas/internal/key" + "github.com/AssetMantle/modules/modules/metas/internal/mappable" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + dataID := baseIDs.NewDataID(message.Data) + metas := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(dataID)) + + data := metas.Get(key.NewKey(dataID)) + if data != nil { + return newTransactionResponse(constants.EntityAlreadyExists) + } + + if message.Data.GenerateHashID().Compare(baseIDs.GenerateHashID()) != 0 { + metas.Add(mappable.NewMappable(message.Data)) + } + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, _ []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/metas/internal/transactions/reveal/keeper_test.go b/modules/metas/internal/transactions/reveal/keeper_test.go index eda056928..7fe43e451 100644 --- a/modules/metas/internal/transactions/reveal/keeper_test.go +++ b/modules/metas/internal/transactions/reveal/keeper_test.go @@ -1,32 +1,31 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package reveal import ( + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" - cryptoCodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" - vestingTypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/schema/data/utilities" + + "github.com/AssetMantle/modules/modules/metas/internal/key" + "github.com/AssetMantle/modules/modules/metas/internal/mappable" + "github.com/AssetMantle/modules/modules/metas/internal/parameters" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" ) type TestKeepers struct { @@ -34,13 +33,11 @@ type TestKeepers struct { } func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) - vestingTypes.RegisterLegacyAminoCodec(Codec) vesting.RegisterCodec(Codec) Codec.Seal() @@ -60,8 +57,8 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", @@ -75,14 +72,13 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { } func Test_transactionKeeper_Transact(t *testing.T) { - context, keepers := CreateTestInput(t) defaultAddr := sdkTypes.AccAddress("addr") - defaultFact, Error := base.ReadMetaFact("S|default") - require.Equal(t, nil, Error) - newFact, Error := base.ReadMetaFact("S|newFact") - require.Equal(t, nil, Error) - keepers.MetasKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMeta(defaultFact.GetData())) + data, err := utilities.ReadData("S|default") + require.Equal(t, nil, err) + newFact, err := utilities.ReadData("S|newFact") + require.Equal(t, nil, err) + keepers.MetasKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(data)) t.Run("PositiveCase", func(t *testing.T) { want := newTransactionResponse(nil) if got := keepers.MetasKeeper.Transact(context, newMessage(defaultAddr, newFact)); !reflect.DeepEqual(got, want) { @@ -92,8 +88,8 @@ func Test_transactionKeeper_Transact(t *testing.T) { t.Run("NegativeCase-Reveal metas again", func(t *testing.T) { t.Parallel() - want := newTransactionResponse(errors.EntityAlreadyExists) - if got := keepers.MetasKeeper.Transact(context, newMessage(defaultAddr, defaultFact)); !reflect.DeepEqual(got, want) { + want := newTransactionResponse(constants.EntityAlreadyExists) + if got := keepers.MetasKeeper.Transact(context, newMessage(defaultAddr, data)); !reflect.DeepEqual(got, want) { t.Errorf("Transact() = %v, want %v", got, want) } }) diff --git a/modules/metas/internal/transactions/reveal/message.go b/modules/metas/internal/transactions/reveal/message.go index 173d805ed..1a071411b 100644 --- a/modules/metas/internal/transactions/reveal/message.go +++ b/modules/metas/internal/transactions/reveal/message.go @@ -1,68 +1,62 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package reveal import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/metas/internal/module" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + Data data.Data `json:"data" valid:"required~required field data missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(constants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, metaFact types.MetaFact) *Message { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - MetaFact: *base.NewMetaFact(metaFact.GetData()), +func newMessage(from sdkTypes.AccAddress, data data.Data) sdkTypes.Msg { + return message{ + From: from, + Data: data, } } diff --git a/modules/metas/internal/transactions/reveal/message.pb.go b/modules/metas/internal/transactions/reveal/message.pb.go deleted file mode 100644 index 56cc370d6..000000000 --- a/modules/metas/internal/transactions/reveal/message.pb.go +++ /dev/null @@ -1,582 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/metas/internal/transactions/reveal/message.proto - -package reveal - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - MetaFact base.MetaFact `protobuf:"bytes,2,opt,name=meta_fact,json=metaFact,proto3" json:"meta_fact" valid:"required~required field MetaFact missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_b89912b997b8f0d0, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b89912b997b8f0d0, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.metas.internal.transactions.reveal.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.metas.internal.transactions.reveal.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/metas/internal/transactions/reveal/message.proto", fileDescriptor_b89912b997b8f0d0) -} - -var fileDescriptor_b89912b997b8f0d0 = []byte{ - // 419 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0x31, 0x6f, 0x13, 0x31, - 0x14, 0xc7, 0xcf, 0x05, 0x95, 0xf6, 0xd8, 0x0e, 0x90, 0xaa, 0x0c, 0x77, 0xa7, 0x9b, 0x2a, 0x81, - 0xec, 0xaa, 0x2c, 0x28, 0x5b, 0x03, 0x54, 0x48, 0x28, 0xaa, 0x94, 0x32, 0xb1, 0x54, 0x8e, 0xef, - 0xe5, 0x6a, 0x71, 0xb6, 0x0f, 0x3f, 0xa7, 0x12, 0x03, 0x0c, 0x4c, 0x8c, 0xf0, 0x0d, 0x32, 0x32, - 0xf0, 0x41, 0x3a, 0x76, 0x44, 0x0c, 0x27, 0x94, 0x2c, 0xcc, 0xfd, 0x04, 0x28, 0xbe, 0x9c, 0x12, - 0x05, 0x24, 0x22, 0xba, 0xd9, 0x83, 0x7f, 0xff, 0x9f, 0xdf, 0xff, 0x85, 0x2f, 0x2a, 0xb0, 0x28, - 0xd1, 0x81, 0x16, 0x70, 0x86, 0xf9, 0x1b, 0xa6, 0x4c, 0x3e, 0x2e, 0x01, 0x99, 0x02, 0xc7, 0x91, - 0x49, 0xed, 0xc0, 0x6a, 0x5e, 0x32, 0x67, 0xb9, 0x46, 0x2e, 0x9c, 0x34, 0x1a, 0x99, 0x85, 0x0b, - 0xe0, 0x25, 0x53, 0x80, 0xc8, 0x0b, 0xa0, 0x95, 0x35, 0xce, 0x44, 0xdd, 0x35, 0x12, 0x5d, 0x90, - 0xa8, 0x27, 0xd1, 0x96, 0x44, 0x57, 0x49, 0xb4, 0x21, 0x75, 0xee, 0x17, 0xa6, 0x30, 0x1e, 0xc3, - 0xe6, 0xa7, 0x86, 0xd8, 0x39, 0x58, 0x77, 0x43, 0x71, 0x0e, 0x8a, 0x33, 0xf7, 0xae, 0x02, 0x64, - 0x43, 0x8e, 0xe0, 0x2d, 0x8f, 0xb9, 0x70, 0xcd, 0x8b, 0xec, 0xdb, 0x56, 0x78, 0xa7, 0xdf, 0x58, - 0x45, 0x5f, 0x48, 0x78, 0x7b, 0x64, 0x8d, 0xda, 0x23, 0x29, 0xd9, 0xdf, 0xed, 0xbd, 0xbf, 0xac, - 0x93, 0xe0, 0x47, 0x9d, 0x3c, 0x2f, 0xa4, 0x3b, 0x1f, 0x0f, 0xa9, 0x30, 0x8a, 0xad, 0xf0, 0x4f, - 0x34, 0xac, 0x5e, 0x4f, 0x9f, 0xbd, 0xfc, 0x33, 0x8d, 0x1e, 0x09, 0x71, 0x94, 0xe7, 0x16, 0x10, - 0xaf, 0xeb, 0xe4, 0xd1, 0x05, 0x2f, 0x65, 0xde, 0xcd, 0x2c, 0xbc, 0x1d, 0x4b, 0x0b, 0xf9, 0x87, - 0xf6, 0x90, 0x8e, 0x24, 0x94, 0x79, 0x7a, 0x6c, 0x8d, 0x4a, 0x95, 0x44, 0x94, 0xba, 0xc8, 0x06, - 0x5e, 0x25, 0xfa, 0x48, 0xc2, 0xdd, 0xb9, 0xf2, 0xd9, 0x88, 0x0b, 0xb7, 0xb7, 0x95, 0x92, 0xfd, - 0xbb, 0x87, 0x0f, 0xe9, 0xfa, 0xe0, 0x9a, 0x60, 0xea, 0x83, 0xa9, 0x0f, 0xee, 0x2f, 0xbe, 0xd9, - 0x7b, 0x32, 0xff, 0xc5, 0x75, 0x9d, 0x1c, 0xfc, 0x23, 0xbc, 0x7d, 0xb0, 0x14, 0xd8, 0x69, 0x47, - 0xd5, 0xdd, 0xf9, 0x34, 0x49, 0x82, 0x5f, 0x93, 0x24, 0xc8, 0x1e, 0x84, 0xf7, 0x5e, 0x2d, 0xdb, - 0x18, 0x00, 0x56, 0x46, 0x23, 0x1c, 0x7e, 0x25, 0xe1, 0xad, 0x3e, 0x16, 0xd1, 0x84, 0x84, 0xdb, - 0x03, 0x5f, 0x50, 0xf4, 0x94, 0xfe, 0x7f, 0xbb, 0x74, 0xd1, 0x48, 0xe7, 0xe4, 0x26, 0x90, 0xbf, - 0x88, 0x66, 0x41, 0x4f, 0x5d, 0x4e, 0x63, 0x72, 0x35, 0x8d, 0xc9, 0xcf, 0x69, 0x4c, 0x3e, 0xcf, - 0xe2, 0xe0, 0x6a, 0x16, 0x07, 0xdf, 0x67, 0x71, 0xf0, 0xfa, 0x74, 0xe3, 0x9e, 0x37, 0xdf, 0xf8, - 0xe1, 0xb6, 0x5f, 0xb3, 0xc7, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0xcd, 0xf0, 0x17, 0x64, 0x36, - 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Reveal(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Reveal(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.metas.internal.transactions.reveal.Msg/Reveal", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Reveal(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Reveal(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Reveal not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Reveal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Reveal(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.metas.internal.transactions.reveal.Msg/Reveal", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Reveal(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.metas.internal.transactions.reveal.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Reveal", - Handler: _Msg_Reveal_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/metas/internal/transactions/reveal/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MetaFact.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MetaFact.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MetaFact", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MetaFact.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/metas/internal/transactions/reveal/message_test.go b/modules/metas/internal/transactions/reveal/message_test.go index c727f47b5..b452ef3fb 100644 --- a/modules/metas/internal/transactions/reveal/message_test.go +++ b/modules/metas/internal/transactions/reveal/message_test.go @@ -1,39 +1,39 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package reveal import ( + "testing" + + "github.com/AssetMantle/modules/schema/data/utilities" + sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" "github.com/stretchr/testify/require" - "testing" + + "github.com/AssetMantle/modules/modules/metas/internal/module" + "github.com/AssetMantle/modules/utilities/transaction" ) func Test_Reveal_Message(t *testing.T) { - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) - metaFact := "S|newMetaFact" - newMetaFact, Error := base.ReadMetaFact(metaFact) - require.Equal(t, nil, Error) + data := "S|newData" + newData, err := utilities.ReadData(data) + require.Equal(t, nil, err) - testMessage := newMessage(fromAccAddress, newMetaFact) - require.Equal(t, Message{From: fromAccAddress, MetaFact: newMetaFact}, testMessage) + testMessage := newMessage(fromAccAddress, newData) + require.Equal(t, message{From: fromAccAddress, Data: newData}, testMessage) require.Equal(t, module.Name, testMessage.Route()) require.Equal(t, Transaction.GetName(), testMessage.Type()) require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) + require.NotNil(t, message{}.ValidateBasic()) + require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) + require.Equal(t, message{}, messageFromInterface(nil)) + require.Equal(t, message{}, messagePrototype()) } diff --git a/modules/metas/internal/transactions/reveal/msg_server.go b/modules/metas/internal/transactions/reveal/msg_server.go deleted file mode 100644 index ca9412a83..000000000 --- a/modules/metas/internal/transactions/reveal/msg_server.go +++ /dev/null @@ -1,36 +0,0 @@ -package reveal - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/mappable" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -func (msgServer msgServer) Reveal(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - metaID := key.GenerateMetaID(message.MetaFact.GetData()) - metas := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(metaID)) - - meta := metas.Get(key.FromID(metaID)) - if meta != nil { - return nil, errors.EntityAlreadyExists - } - - if message.MetaFact.GetHashID().Compare(base.NewID("")) != 0 { - metas.Add(mappable.NewMeta(message.MetaFact.GetData())) - } - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} - -var _ MsgServer = msgServer{} diff --git a/modules/metas/internal/transactions/reveal/request.go b/modules/metas/internal/transactions/reveal/request.go index cf89b73e9..5d4074c9b 100644 --- a/modules/metas/internal/transactions/reveal/request.go +++ b/modules/metas/internal/transactions/reveal/request.go @@ -1,54 +1,53 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package reveal import ( "encoding/json" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/metas/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/data/utilities" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { - BaseReq rest.BaseReq `json:"baseReq"` - MetaFact string `json:"metaFact" valid:"required~required field metaFact missing, matches(^[DHIS]{1}[|]{1}.*$)"` + BaseReq rest.BaseReq `json:"baseReq"` + Data string `json:"data" valid:"required~required field data missing, matches(^[DHIS]{1}[|]{1}.*$)"` } var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary reveal metas transaction -// @Descrption reveal metas transaction +// Validate godoc +// @Summary Reveal metas transaction +// @Description Reveal metas transaction // @Accept text/plain // @Produce json // @Tags Metas -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body transactionRequest true "Request body to reveal meta transaction" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /metas/reveal [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.MetaFact), + cliCommand.ReadString(constants.Data), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -57,30 +56,30 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err } - metaFact, Error := base.ReadMetaFact(transactionRequest.MetaFact) - if Error != nil { - return nil, Error + data, err := utilities.ReadData(transactionRequest.Data) + if err != nil { + return nil, err } return newMessage( from, - metaFact, + data, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} } -func newTransactionRequest(baseReq rest.BaseReq, metaFact string) helpers.TransactionRequest { +func newTransactionRequest(baseReq rest.BaseReq, data string) helpers.TransactionRequest { return transactionRequest{ - BaseReq: baseReq, - MetaFact: metaFact, + BaseReq: baseReq, + Data: data, } } diff --git a/modules/metas/internal/transactions/reveal/request_test.go b/modules/metas/internal/transactions/reveal/request_test.go index 2b9ff29ac..1efac4d72 100644 --- a/modules/metas/internal/transactions/reveal/request_test.go +++ b/modules/metas/internal/transactions/reveal/request_test.go @@ -1,79 +1,81 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package reveal import ( "encoding/json" + "testing" + + "github.com/AssetMantle/modules/schema/data/utilities" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" - "testing" + + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" ) func Test_Reveal_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.MetaFact}) + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.Data}) cliContext := context.NewCLIContext().WithCodec(Codec) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) - metaFact := "S|newMetaFact" - newMetaFact, Error := base.ReadMetaFact(metaFact) - require.Equal(t, nil, Error) + data := "S|newData" + newData, err := utilities.ReadData(data) + require.Equal(t, nil, err) testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, metaFact) + testTransactionRequest := newTransactionRequest(testBaseReq, data) - require.Equal(t, transactionRequest{BaseReq: testBaseReq, MetaFact: metaFact}, testTransactionRequest) + require.Equal(t, transactionRequest{BaseReq: testBaseReq, Data: data}, testTransactionRequest) require.Equal(t, nil, testTransactionRequest.Validate()) - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, MetaFact: ""}, requestFromCLI) + requestFromCLI, err := transactionRequest{}.FromCLI(cliCommand, cliContext) + require.Equal(t, nil, err) + require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, Data: ""}, requestFromCLI) jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) + transactionRequestUnmarshalled, err := transactionRequest{}.FromJSON(jsonMessage) + require.Equal(t, nil, err) require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) + randomUnmarshall, err := transactionRequest{}.FromJSON([]byte{}) require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) + require.NotNil(t, err) require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, newMetaFact), msg) - require.Nil(t, Error) + msg, err := testTransactionRequest.MakeMsg() + require.Equal(t, newMessage(fromAccAddress, newData), msg) + require.Nil(t, err) - msg2, Error := newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, metaFact).MakeMsg() - require.NotNil(t, Error) + msg2, err := newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, data).MakeMsg() + require.NotNil(t, err) require.Nil(t, msg2) - msg2, Error = newTransactionRequest(rest.BaseReq{From: fromAddress, ChainID: "test"}, "randomString").MakeMsg() - require.NotNil(t, Error) + msg2, err = newTransactionRequest(rest.BaseReq{From: fromAddress, ChainID: "test"}, "randomString").MakeMsg() + require.NotNil(t, err) require.Nil(t, msg2) require.Equal(t, transactionRequest{}, requestPrototype()) require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) + requestPrototype().RegisterCodec(codec.New()) }) } diff --git a/modules/metas/internal/transactions/reveal/response.go b/modules/metas/internal/transactions/reveal/response.go new file mode 100644 index 000000000..aa17d3081 --- /dev/null +++ b/modules/metas/internal/transactions/reveal/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package reveal + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/metas/internal/transactions/reveal/response_test.go b/modules/metas/internal/transactions/reveal/response_test.go new file mode 100644 index 000000000..80a7eef48 --- /dev/null +++ b/modules/metas/internal/transactions/reveal/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package reveal + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Reveal_Response(t *testing.T) { + testTransactionResponse := newTransactionResponse(constants.IncorrectFormat) + testTransactionResponse2 := newTransactionResponse(nil) + + require.Equal(t, transactionResponse{Success: false, Error: constants.IncorrectFormat}, testTransactionResponse) + require.Equal(t, false, testTransactionResponse.IsSuccessful()) + require.Equal(t, true, testTransactionResponse2.IsSuccessful()) + + require.Equal(t, constants.IncorrectFormat, testTransactionResponse.GetError()) + require.Equal(t, nil, testTransactionResponse2.GetError()) +} diff --git a/modules/metas/module/transactions/reveal/transaction.go b/modules/metas/internal/transactions/reveal/transaction.go similarity index 100% rename from modules/metas/module/transactions/reveal/transaction.go rename to modules/metas/internal/transactions/reveal/transaction.go diff --git a/modules/metas/module/block/block.go b/modules/metas/module/block/block.go deleted file mode 100644 index ccffdee01..000000000 --- a/modules/metas/module/block/block.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package block - -import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - abciTypes "github.com/tendermint/tendermint/abci/types" - - "github.com/AssetMantle/modules/schema/helpers" -) - -type block struct { - mapper helpers.Mapper - parameters helpers.Parameters -} - -var _ helpers.Block = (*block)(nil) - -func (block block) Begin(_ sdkTypes.Context, _ abciTypes.RequestBeginBlock) { - -} - -func (block block) End(_ sdkTypes.Context, _ abciTypes.RequestEndBlock) []abciTypes.ValidatorUpdate { - return []abciTypes.ValidatorUpdate{} -} - -func Prototype() helpers.Block { - return block{} -} - -func (block block) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, _ ...interface{}) helpers.Block { - block.mapper, block.parameters = mapper, parameters - return block -} diff --git a/modules/metas/module/common/codec.go b/modules/metas/module/common/codec.go deleted file mode 100644 index f34c9ea76..000000000 --- a/modules/metas/module/common/codec.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package common - -import ( - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/AssetMantle/modules/modules/metas/module/key" - "github.com/AssetMantle/modules/modules/metas/module/mappable" - codec2 "github.com/AssetMantle/modules/utilities" -) - -var Codec *codec.LegacyAmino - -func init() { - Codec = codec2.MakeModuleCode(key.Prototype, mappable.Prototype) -} diff --git a/modules/metas/module/genesis/prototype.go b/modules/metas/module/genesis/prototype.go deleted file mode 100644 index 785db464b..000000000 --- a/modules/metas/module/genesis/prototype.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package genesis - -import ( - "github.com/AssetMantle/modules/modules/metas/module/key" - "github.com/AssetMantle/modules/modules/metas/module/mappable" - "github.com/AssetMantle/modules/modules/metas/module/parameters" - "github.com/AssetMantle/modules/schema/helpers" - baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" -) - -func Prototype() helpers.Genesis { - return baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{}, parameters.Prototype().GetList()) -} diff --git a/modules/metas/module/invariants/dummy/invariant.go b/modules/metas/module/invariants/dummy/invariant.go deleted file mode 100644 index 89f539d6a..000000000 --- a/modules/metas/module/invariants/dummy/invariant.go +++ /dev/null @@ -1,9 +0,0 @@ -package dummy - -import ( - "github.com/cosmos/cosmos-sdk/types" -) - -var Invariant = func(_ types.Context) (string, bool) { - return "", false -} diff --git a/modules/metas/module/invariants/prototype.go b/modules/metas/module/invariants/prototype.go deleted file mode 100644 index 5ef216b4e..000000000 --- a/modules/metas/module/invariants/prototype.go +++ /dev/null @@ -1,12 +0,0 @@ -package invariants - -import ( - "github.com/AssetMantle/modules/modules/metas/module/invariants/dummy" - "github.com/AssetMantle/modules/modules/metas/module/module" - "github.com/AssetMantle/modules/schema/helpers" - "github.com/AssetMantle/modules/schema/helpers/base" -) - -func Prototype() helpers.Invariants { - return base.NewInvariants(module.Name, "", dummy.Invariant) -} diff --git a/modules/metas/module/key/key.go b/modules/metas/module/key/key.go deleted file mode 100644 index 418426ab2..000000000 --- a/modules/metas/module/key/key.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package key - -import ( - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/AssetMantle/modules/modules/metas/module/module" - "github.com/AssetMantle/modules/schema" - "github.com/AssetMantle/modules/schema/errors/constants" - "github.com/AssetMantle/modules/schema/helpers" - "github.com/AssetMantle/modules/schema/ids" - "github.com/AssetMantle/modules/schema/ids/base" -) - -type key struct { - ids.ID -} - -var _ helpers.Key = (*key)(nil) - -func (key key) GenerateStoreKeyBytes() []byte { - return module.StoreKeyPrefix.GenerateStoreKey(key.Bytes()) -} -func (key) RegisterCodec(codec *codec.LegacyAmino) { - schema.RegisterModuleConcrete(codec, key{}) -} -func (key key) IsPartial() bool { - return key.ID.(*base.ID).GetDataID().HashId == nil -} -func (key key) Equals(compareKey helpers.Key) bool { - if CompareKey, err := keyFromInterface(compareKey); err != nil { - return false - } else { - return key.ID.Compare(CompareKey.ID) == 0 - } -} -func keyFromInterface(i interface{}) (key, error) { - switch value := i.(type) { - case key: - return value, nil - default: - return key{}, constants.MetaDataError - } -} - -func NewKey(dataID ids.ID) helpers.Key { - return key{ - ID: dataID, - } -} - -func Prototype() helpers.Key { return key{} } diff --git a/modules/metas/module/mappable/mappable.go b/modules/metas/module/mappable/mappable.go deleted file mode 100644 index 9fe26560f..000000000 --- a/modules/metas/module/mappable/mappable.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package mappable - -import ( - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/AssetMantle/modules/modules/metas/module/key" - "github.com/AssetMantle/modules/schema" - "github.com/AssetMantle/modules/schema/data" - "github.com/AssetMantle/modules/schema/helpers" - "github.com/AssetMantle/modules/schema/ids/base" -) - -type mappable struct { - data.Data -} - -var _ helpers.Mappable = (*mappable)(nil) - -func (mappable mappable) GetKey() helpers.Key { - return key.NewKey(base.GenerateDataID(mappable.Data)) -} -func (mappable) RegisterCodec(codec *codec.LegacyAmino) { - schema.RegisterModuleConcrete(codec, mappable{}) -} - -func NewMappable(data data.Data) helpers.Mappable { - return mappable{Data: data} -} - -func Prototype() helpers.Mappable { - return mappable{} -} diff --git a/modules/metas/module/mapper/prototype.go b/modules/metas/module/mapper/prototype.go deleted file mode 100644 index 1daa142fe..000000000 --- a/modules/metas/module/mapper/prototype.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package mapper - -import ( - "github.com/AssetMantle/modules/modules/metas/module/key" - "github.com/AssetMantle/modules/modules/metas/module/mappable" - "github.com/AssetMantle/modules/schema/helpers" - baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" -) - -func Prototype() helpers.Mapper { - return baseHelpers.NewMapper(key.Prototype, mappable.Prototype) -} diff --git a/modules/metas/module/parameters/dummy/parameter.go b/modules/metas/module/parameters/dummy/parameter.go deleted file mode 100644 index 5ffc0eaf5..000000000 --- a/modules/metas/module/parameters/dummy/parameter.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package dummy - -import ( - baseTypes "github.com/AssetMantle/modules/schema/parameters/base" -) - -var Parameter = baseTypes.NewParameter(ID, DefaultData, validator) diff --git a/modules/metas/module/parameters/dummy/validator.go b/modules/metas/module/parameters/dummy/validator.go deleted file mode 100644 index 2bb100018..000000000 --- a/modules/metas/module/parameters/dummy/validator.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package dummy - -import ( - "github.com/AssetMantle/modules/schema/data" - "github.com/AssetMantle/modules/schema/errors/constants" - "github.com/AssetMantle/modules/schema/parameters" -) - -func validator(i interface{}) error { - switch value := i.(type) { - case parameters.Parameter: - if value.GetID().Compare(ID) != 0 || value.GetData().(data.DecData).Get().IsNegative() { - return constants.InvalidParameter - } - - return nil - case data.DecData: - if value.Get().IsNegative() { - return constants.InvalidParameter - } - - return nil - default: - return constants.IncorrectFormat - } -} diff --git a/modules/metas/module/parameters/prototype.go b/modules/metas/module/parameters/prototype.go deleted file mode 100644 index 17cf1ef83..000000000 --- a/modules/metas/module/parameters/prototype.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package parameters - -import ( - "github.com/AssetMantle/modules/modules/metas/module/parameters/dummy" - "github.com/AssetMantle/modules/schema/helpers" - baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" -) - -func Prototype() helpers.Parameters { - return baseHelpers.NewParameters(dummy.Parameter) -} diff --git a/modules/metas/module/queries/meta/keeper.go b/modules/metas/module/queries/meta/keeper.go deleted file mode 100644 index 6a9fd1228..000000000 --- a/modules/metas/module/queries/meta/keeper.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package meta - -import ( - "context" - - sdkTypes "github.com/cosmos/cosmos-sdk/types" - - "github.com/AssetMantle/modules/modules/metas/module/key" - "github.com/AssetMantle/modules/schema/helpers" - baseIDs "github.com/AssetMantle/modules/schema/ids/base" -) - -type queryKeeper struct { - mapper helpers.Mapper -} - -var _ helpers.QueryKeeper = (*queryKeeper)(nil) -var _ QueryServer = &queryKeeper{} - -func (queryKeeper queryKeeper) Meta(ctx context.Context, request *QueryRequest) (*QueryResponse, error) { - // TODO implement me - panic("implement me") -} - -func (queryKeeper queryKeeper) mustEmbedUnimplementedQueryServer() { - // TODO implement me - panic("implement me") -} - -func (queryKeeper queryKeeper) Enquire(context sdkTypes.Context, queryRequest helpers.QueryRequest) helpers.QueryResponse { - return newQueryResponse(queryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(baseIDs.NewDataID(baseIDs.NewStringID(queryRequestFromInterface(queryRequest).DataID.Type.IdString), baseIDs.NewHashID(queryRequestFromInterface(queryRequest).DataID.HashId.IdBytes)))), nil) -} - -func (queryKeeper queryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { - queryKeeper.mapper = mapper - return queryKeeper -} - -func keeperPrototype() helpers.QueryKeeper { - return queryKeeper{} -} diff --git a/modules/metas/module/queries/meta/query.go b/modules/metas/module/queries/meta/query.go deleted file mode 100644 index c3a84f1d5..000000000 --- a/modules/metas/module/queries/meta/query.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package meta - -import ( - "context" - - "github.com/cosmos/cosmos-sdk/client" - sdkModuleTypes "github.com/cosmos/cosmos-sdk/types/module" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - - "github.com/AssetMantle/modules/modules/metas/module/module" - "github.com/AssetMantle/modules/schema/helpers" - baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" - "github.com/AssetMantle/modules/schema/helpers/constants" -) - -type Configurator struct{} - -func (c Configurator) ConfigureGRPCServer(cfg sdkModuleTypes.Configurator) { - RegisterQueryServer(cfg.QueryServer(), queryKeeper{}) -} - -func (c Configurator) ConfigureGRPCGatewayHandler(clientCtx client.Context, mux *runtime.ServeMux) { - RegisterQueryHandlerClient(context.Background(), mux, NewQueryClient(clientCtx)) -} - -var _ helpers.GRPCConfigurator = &Configurator{} - -var Query = baseHelpers.NewQuery( - "metas", - "", - "", - - module.Name, - - requestPrototype, - responsePrototype, - keeperPrototype, - Configurator{}, - - constants.DataID, -) diff --git a/modules/metas/module/queries/meta/query.pb.go b/modules/metas/module/queries/meta/query.pb.go deleted file mode 100644 index 603679a8f..000000000 --- a/modules/metas/module/queries/meta/query.pb.go +++ /dev/null @@ -1,133 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: modules/metas/module/queries/meta/query.proto - -package meta - -import ( - context "context" - fmt "fmt" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -func init() { - proto.RegisterFile("modules/metas/module/queries/meta/query.proto", fileDescriptor_5f48faf22f8c8956) -} - -var fileDescriptor_5f48faf22f8c8956 = []byte{ - // 279 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0xcd, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4d, 0x2d, 0x49, 0x2c, 0xd6, 0x87, 0xf0, 0xf4, 0x0b, 0x4b, 0x53, - 0x8b, 0x32, 0xa1, 0x82, 0x60, 0x4e, 0xa5, 0x5e, 0x41, 0x51, 0x7e, 0x49, 0xbe, 0x10, 0x0b, 0x48, - 0x44, 0x4a, 0x26, 0x3d, 0x3f, 0x3f, 0x3d, 0x27, 0x55, 0x3f, 0xb1, 0x20, 0x53, 0x3f, 0x31, 0x2f, - 0x2f, 0xbf, 0x24, 0xb1, 0x24, 0x33, 0x3f, 0xaf, 0x18, 0xa2, 0x46, 0xca, 0x84, 0x48, 0x23, 0x83, - 0x52, 0x0b, 0x4b, 0x53, 0x8b, 0x4b, 0xa0, 0xba, 0x4c, 0x89, 0xd6, 0x55, 0x5c, 0x90, 0x9f, 0x57, - 0x9c, 0x0a, 0xd1, 0x66, 0x14, 0xc3, 0xc5, 0x1a, 0x08, 0x12, 0x16, 0x0a, 0xe6, 0x62, 0xf1, 0x4d, - 0x2d, 0x49, 0x14, 0x12, 0xd2, 0x03, 0xa9, 0xd5, 0x0b, 0x44, 0xb2, 0x41, 0x4a, 0x18, 0x45, 0x0c, - 0xa2, 0x5f, 0x49, 0xa9, 0xe9, 0xf2, 0x93, 0xc9, 0x4c, 0x32, 0x42, 0x52, 0xfa, 0xb9, 0x89, 0x79, - 0x25, 0x39, 0xa9, 0x50, 0x8b, 0xcb, 0x0c, 0x93, 0x52, 0x4b, 0x12, 0x0d, 0xc1, 0x3c, 0xa7, 0x05, - 0x8c, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, - 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0xc0, 0xc5, 0x91, 0x9c, 0x9f, 0x0b, - 0x36, 0xd6, 0x89, 0x0b, 0x6c, 0x6e, 0x00, 0xc8, 0x39, 0x01, 0x8c, 0x51, 0x0e, 0xe9, 0x99, 0x25, - 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x8e, 0xc5, 0xc5, 0xa9, 0x25, 0xbe, 0x50, 0xd3, - 0x61, 0xde, 0x23, 0xe4, 0xcd, 0x45, 0x4c, 0xcc, 0xbe, 0x11, 0x11, 0xab, 0x98, 0xc0, 0xde, 0x39, - 0x05, 0xa1, 0x1e, 0x31, 0x09, 0x80, 0xa8, 0x18, 0xf7, 0x00, 0x27, 0x10, 0x9d, 0x92, 0x58, 0x92, - 0xf8, 0x0a, 0x22, 0x93, 0xc4, 0x06, 0x0e, 0x07, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xd2, - 0xb0, 0xef, 0xf0, 0xc9, 0x01, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - Meta(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Meta(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) { - out := new(QueryResponse) - err := c.cc.Invoke(ctx, "/meta.Query/Meta", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - Meta(context.Context, *QueryRequest) (*QueryResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Meta(ctx context.Context, req *QueryRequest) (*QueryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Meta not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Meta_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Meta(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/meta.Query/Meta", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Meta(ctx, req.(*QueryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "meta.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Meta", - Handler: _Query_Meta_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "modules/metas/module/queries/meta/query.proto", -} diff --git a/modules/metas/module/queries/meta/query.pb.gw.go b/modules/metas/module/queries/meta/query.pb.gw.go deleted file mode 100644 index 3dbffd893..000000000 --- a/modules/metas/module/queries/meta/query.pb.gw.go +++ /dev/null @@ -1,171 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: modules/metas/module/queries/meta/query.proto - -/* -Package meta is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package meta - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -var ( - filter_Query_Meta_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Meta_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Meta_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Meta(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Meta_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Meta_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Meta(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Meta_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Meta_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Meta_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Meta_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Meta_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Meta_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Meta_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"mantle", "metas", "v1beta1", "meta"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_Meta_0 = runtime.ForwardResponseMessage -) diff --git a/modules/metas/module/queries/meta/query.proto b/modules/metas/module/queries/meta/query.proto deleted file mode 100644 index a6e96d6bd..000000000 --- a/modules/metas/module/queries/meta/query.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; -package meta; - -import "google/api/annotations.proto"; -import "modules/metas/module/queries/meta/queryRequest.proto"; -import "modules/metas/module/queries/meta/queryResponse.proto"; - -service Query{ - rpc Meta(QueryRequest) returns(QueryResponse){ - option (google.api.http).get = "/mantle/metas/v1beta1/meta"; - } -} \ No newline at end of file diff --git a/modules/metas/module/queries/meta/queryRequest.pb.go b/modules/metas/module/queries/meta/queryRequest.pb.go deleted file mode 100644 index 7b33d0a82..000000000 --- a/modules/metas/module/queries/meta/queryRequest.pb.go +++ /dev/null @@ -1,332 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: modules/metas/module/queries/meta/queryRequest.proto - -package meta - -import ( - fmt "fmt" - base "github.com/AssetMantle/modules/schema/ids/base" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type QueryRequest struct { - DataID *base.DataID `protobuf:"bytes,1,opt,name=data_i_d,json=dataID,proto3" json:"data_i_d,omitempty"` -} - -func (m *QueryRequest) Reset() { *m = QueryRequest{} } -func (m *QueryRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRequest) ProtoMessage() {} -func (*QueryRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_badac1d4305d49be, []int{0} -} -func (m *QueryRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRequest.Merge(m, src) -} -func (m *QueryRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRequest proto.InternalMessageInfo - -func (m *QueryRequest) GetDataID() *base.DataID { - if m != nil { - return m.DataID - } - return nil -} - -func init() { - proto.RegisterType((*QueryRequest)(nil), "meta.QueryRequest") -} - -func init() { - proto.RegisterFile("modules/metas/module/queries/meta/queryRequest.proto", fileDescriptor_badac1d4305d49be) -} - -var fileDescriptor_badac1d4305d49be = []byte{ - // 244 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0xc9, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4d, 0x2d, 0x49, 0x2c, 0xd6, 0x87, 0xf0, 0xf4, 0x0b, 0x4b, 0x53, - 0x8b, 0x32, 0xa1, 0x82, 0x60, 0x4e, 0x65, 0x50, 0x6a, 0x61, 0x69, 0x6a, 0x71, 0x89, 0x5e, 0x41, - 0x51, 0x7e, 0x49, 0xbe, 0x10, 0x0b, 0x48, 0x42, 0x4a, 0xa6, 0x38, 0x39, 0x23, 0x35, 0x37, 0x51, - 0x3f, 0x33, 0xa5, 0x58, 0x3f, 0x29, 0xb1, 0x38, 0x55, 0x3f, 0x25, 0xb1, 0x24, 0xd1, 0xd3, 0x05, - 0xa2, 0x46, 0xc9, 0x8c, 0x8b, 0x27, 0x10, 0x49, 0xa7, 0x90, 0x1a, 0x17, 0x07, 0x48, 0x3e, 0x3e, - 0x33, 0x3e, 0x45, 0x82, 0x51, 0x81, 0x51, 0x83, 0xdb, 0x88, 0x47, 0x0f, 0xa4, 0x4b, 0xcf, 0x05, - 0xac, 0x2b, 0x88, 0x0d, 0xa2, 0xdb, 0x69, 0x39, 0xe3, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, - 0x31, 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, - 0xcb, 0x31, 0x70, 0x71, 0x24, 0xe7, 0xe7, 0xea, 0x81, 0xac, 0x76, 0x12, 0x44, 0x36, 0x3a, 0x00, - 0x64, 0x5f, 0x00, 0x63, 0x94, 0x43, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, - 0xbe, 0x63, 0x71, 0x71, 0x6a, 0x89, 0x6f, 0x62, 0x5e, 0x49, 0x4e, 0xaa, 0x3e, 0xdc, 0x8b, 0x84, - 0xbc, 0xba, 0x88, 0x89, 0xd9, 0x37, 0x22, 0x62, 0x15, 0x13, 0x8b, 0x6f, 0x6a, 0x49, 0xe2, 0x29, - 0x08, 0xf5, 0x88, 0x49, 0x00, 0x44, 0xc5, 0xb8, 0x07, 0x38, 0x81, 0x68, 0x90, 0x23, 0x5f, 0x41, - 0x64, 0x92, 0xd8, 0xc0, 0x1e, 0x35, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x07, 0xcf, 0xfb, 0xf8, - 0x44, 0x01, 0x00, 0x00, -} - -func (m *QueryRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.DataID != nil { - { - size, err := m.DataID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQueryRequest(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintQueryRequest(dAtA []byte, offset int, v uint64) int { - offset -= sovQueryRequest(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.DataID != nil { - l = m.DataID.Size() - n += 1 + l + sovQueryRequest(uint64(l)) - } - return n -} - -func sovQueryRequest(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQueryRequest(x uint64) (n int) { - return sovQueryRequest(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQueryRequest - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DataID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQueryRequest - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQueryRequest - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQueryRequest - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.DataID == nil { - m.DataID = &base.DataID{} - } - if err := m.DataID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQueryRequest(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQueryRequest - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQueryRequest(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQueryRequest - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQueryRequest - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQueryRequest - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQueryRequest - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQueryRequest - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQueryRequest - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQueryRequest = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQueryRequest = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQueryRequest = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/metas/module/queries/meta/queryRequest.proto b/modules/metas/module/queries/meta/queryRequest.proto deleted file mode 100644 index 054e52d9c..000000000 --- a/modules/metas/module/queries/meta/queryRequest.proto +++ /dev/null @@ -1,7 +0,0 @@ -syntax = "proto3"; -package meta; - -import "schema/ids/base/dataID.proto"; -message QueryRequest { - base.DataID data_i_d = 1; -} \ No newline at end of file diff --git a/modules/metas/module/queries/meta/queryResponse.pb.go b/modules/metas/module/queries/meta/queryResponse.pb.go deleted file mode 100644 index d152e8b55..000000000 --- a/modules/metas/module/queries/meta/queryResponse.pb.go +++ /dev/null @@ -1,362 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: modules/metas/module/queries/meta/queryResponse.proto - -package meta - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type QueryResponse struct { - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` -} - -func (m *QueryResponse) Reset() { *m = QueryResponse{} } -func (m *QueryResponse) String() string { return proto.CompactTextString(m) } -func (*QueryResponse) ProtoMessage() {} -func (*QueryResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1092e53c379925f8, []int{0} -} -func (m *QueryResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryResponse.Merge(m, src) -} -func (m *QueryResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryResponse proto.InternalMessageInfo - -func (m *QueryResponse) GetSuccess() bool { - if m != nil { - return m.Success - } - return false -} - -func (m *QueryResponse) GetError() string { - if m != nil { - return m.Error - } - return "" -} - -func init() { - proto.RegisterType((*QueryResponse)(nil), "meta.QueryResponse") -} - -func init() { - proto.RegisterFile("modules/metas/module/queries/meta/queryResponse.proto", fileDescriptor_1092e53c379925f8) -} - -var fileDescriptor_1092e53c379925f8 = []byte{ - // 229 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0xcd, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4d, 0x2d, 0x49, 0x2c, 0xd6, 0x87, 0xf0, 0xf4, 0x0b, 0x4b, 0x53, - 0x8b, 0x32, 0xa1, 0x82, 0x60, 0x4e, 0x65, 0x50, 0x6a, 0x71, 0x41, 0x7e, 0x5e, 0x71, 0xaa, 0x5e, - 0x41, 0x51, 0x7e, 0x49, 0xbe, 0x10, 0x0b, 0x48, 0x46, 0xc9, 0x9e, 0x8b, 0x37, 0x10, 0x59, 0x52, - 0x48, 0x82, 0x8b, 0xbd, 0xb8, 0x34, 0x39, 0x39, 0xb5, 0xb8, 0x58, 0x82, 0x51, 0x81, 0x51, 0x83, - 0x23, 0x08, 0xc6, 0x15, 0x12, 0xe1, 0x62, 0x4d, 0x2d, 0x2a, 0xca, 0x2f, 0x92, 0x60, 0x52, 0x60, - 0xd4, 0xe0, 0x0c, 0x82, 0x70, 0x9c, 0x56, 0x30, 0x9e, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, - 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, 0x78, 0x2c, 0xc7, 0x70, 0xe3, 0xb1, - 0x1c, 0x03, 0x17, 0x47, 0x72, 0x7e, 0xae, 0x1e, 0xc8, 0x16, 0x27, 0x21, 0x14, 0x3b, 0x02, 0x40, - 0xf6, 0x07, 0x30, 0x46, 0x39, 0xa4, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, - 0x3b, 0x16, 0x17, 0xa7, 0x96, 0xf8, 0x26, 0xe6, 0x95, 0xe4, 0xa4, 0xea, 0xc3, 0xfd, 0x43, 0xc8, - 0x5f, 0x8b, 0x98, 0x98, 0x7d, 0x23, 0x22, 0x56, 0x31, 0xb1, 0xf8, 0xa6, 0x96, 0x24, 0x9e, 0x82, - 0x50, 0x8f, 0x98, 0x04, 0x40, 0x54, 0x8c, 0x7b, 0x80, 0x13, 0x88, 0x4e, 0x49, 0x2c, 0x49, 0x7c, - 0x05, 0x91, 0x49, 0x62, 0x03, 0x7b, 0xdc, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xd3, 0xe2, 0x47, - 0x01, 0x31, 0x01, 0x00, 0x00, -} - -func (m *QueryResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Error) > 0 { - i -= len(m.Error) - copy(dAtA[i:], m.Error) - i = encodeVarintQueryResponse(dAtA, i, uint64(len(m.Error))) - i-- - dAtA[i] = 0x12 - } - if m.Success { - i-- - if m.Success { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQueryResponse(dAtA []byte, offset int, v uint64) int { - offset -= sovQueryResponse(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Success { - n += 2 - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovQueryResponse(uint64(l)) - } - return n -} - -func sovQueryResponse(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQueryResponse(x uint64) (n int) { - return sovQueryResponse(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQueryResponse - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQueryResponse - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Success = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQueryResponse - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQueryResponse - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQueryResponse - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQueryResponse(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQueryResponse - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQueryResponse(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQueryResponse - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQueryResponse - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQueryResponse - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQueryResponse - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQueryResponse - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQueryResponse - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQueryResponse = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQueryResponse = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQueryResponse = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/metas/module/queries/meta/queryResponse.proto b/modules/metas/module/queries/meta/queryResponse.proto deleted file mode 100644 index 007c15c4a..000000000 --- a/modules/metas/module/queries/meta/queryResponse.proto +++ /dev/null @@ -1,8 +0,0 @@ -syntax = "proto3"; -package meta; - - -message QueryResponse{ - bool success = 1; - string error = 2; -} \ No newline at end of file diff --git a/modules/metas/module/queries/meta/request.go b/modules/metas/module/queries/meta/request.go deleted file mode 100644 index a0920b36d..000000000 --- a/modules/metas/module/queries/meta/request.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package meta - -import ( - "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" - - "github.com/AssetMantle/modules/modules/metas/module/common" - "github.com/AssetMantle/modules/schema/helpers" - "github.com/AssetMantle/modules/schema/helpers/constants" - "github.com/AssetMantle/modules/schema/ids" - baseIDs "github.com/AssetMantle/modules/schema/ids/base" -) - -// type queryRequest struct { -// ids.DataID `json:"dataID" valid:"required~required field dataID missing"` -// } - -var _ helpers.QueryRequest = (*QueryRequest)(nil) - -// Validate godoc -// @Summary Search for metadata by meta ID -// @Description Able to query the metadata -// @Accept json -// @Produce json -// @Tags Metas -// @Param dataID path string true "Unique identifier of metadata value." -// @Success 200 {object} queryResponse "Message for a successful query response" -// @Failure default {object} queryResponse "Message for an unexpected error response." -// @Router /metas/metas/{dataID} [get] -func (queryRequest *QueryRequest) Validate() error { - _, err := govalidator.ValidateStruct(queryRequest) - return err -} -func (*QueryRequest) FromCLI(cliCommand helpers.CLICommand, _ client.Context) (helpers.QueryRequest, error) { - if dataID, err := baseIDs.ReadDataID(cliCommand.ReadString(constants.DataID)); err != nil { - return &QueryRequest{}, err - } else { - return newQueryRequest(dataID), nil - } -} -func (*QueryRequest) FromMap(vars map[string]string) (helpers.QueryRequest, error) { - if dataID, err := baseIDs.ReadDataID(vars[Query.GetName()]); err != nil { - return &QueryRequest{}, err - } else { - return newQueryRequest(dataID), nil - } -} -func (queryRequest *QueryRequest) Encode() ([]byte, error) { - return common.Codec.MarshalJSON(queryRequest) -} -func (queryRequest *QueryRequest) Decode(bytes []byte) (helpers.QueryRequest, error) { - if err := common.Codec.UnmarshalJSON(bytes, &queryRequest); err != nil { - return nil, err - } - - return queryRequest, nil -} -func requestPrototype() helpers.QueryRequest { - return &QueryRequest{} -} -func queryRequestFromInterface(request helpers.QueryRequest) *QueryRequest { - switch value := request.(type) { - case *QueryRequest: - return value - default: - return &QueryRequest{} - } -} -func newQueryRequest(dataID ids.ID) helpers.QueryRequest { - if dataID.(*baseIDs.ID).GetDataID() == nil { - panic("dataID is nil") - } - return &QueryRequest{DataID: dataID.(*baseIDs.ID).GetDataID()} -} diff --git a/modules/metas/module/queries/meta/response.go b/modules/metas/module/queries/meta/response.go deleted file mode 100644 index 9b497e3cf..000000000 --- a/modules/metas/module/queries/meta/response.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package meta - -import ( - "github.com/AssetMantle/modules/modules/metas/module/common" - "github.com/AssetMantle/modules/schema/helpers" -) - -var _ helpers.QueryResponse = (*QueryResponse)(nil) - -func (queryResponse *QueryResponse) IsSuccessful() bool { - return queryResponse.Success -} -func (queryResponse *QueryResponse) Encode() ([]byte, error) { - return common.Codec.MarshalJSON(queryResponse) -} -func (queryResponse *QueryResponse) Decode(bytes []byte) (helpers.QueryResponse, error) { - if err := common.Codec.UnmarshalJSON(bytes, &queryResponse); err != nil { - return nil, err - } - - return queryResponse, nil -} -func responsePrototype() helpers.QueryResponse { - return &QueryResponse{} -} -func newQueryResponse(collection helpers.Collection, error error) helpers.QueryResponse { - success := true - if error != nil { - success = false - } - - return &QueryResponse{ - Success: success, - Error: error.Error(), - } -} diff --git a/modules/metas/module/queries/prototype.go b/modules/metas/module/queries/prototype.go deleted file mode 100644 index 4151ab0b7..000000000 --- a/modules/metas/module/queries/prototype.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package queries - -import ( - "github.com/AssetMantle/modules/modules/metas/module/queries/meta" - "github.com/AssetMantle/modules/schema/helpers" - baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" -) - -func Prototype() helpers.Queries { - return baseHelpers.NewQueries( - meta.Query, - ) -} diff --git a/modules/metas/module/transactions/prototype.go b/modules/metas/module/transactions/prototype.go deleted file mode 100644 index 9fe1539a7..000000000 --- a/modules/metas/module/transactions/prototype.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package transactions - -import ( - "github.com/AssetMantle/modules/modules/metas/module/transactions/reveal" - "github.com/AssetMantle/modules/schema/helpers" - baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" -) - -func Prototype() helpers.Transactions { - return baseHelpers.NewTransactions( - reveal.Transaction, - ) -} diff --git a/modules/metas/module/transactions/reveal/keeper.go b/modules/metas/module/transactions/reveal/keeper.go deleted file mode 100644 index ea22db53c..000000000 --- a/modules/metas/module/transactions/reveal/keeper.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package reveal - -import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - - "github.com/AssetMantle/modules/modules/metas/module/key" - "github.com/AssetMantle/modules/modules/metas/module/mappable" - "github.com/AssetMantle/modules/schema/errors/constants" - "github.com/AssetMantle/modules/schema/helpers" - baseIDs "github.com/AssetMantle/modules/schema/ids/base" -) - -type transactionKeeper struct { - mapper helpers.Mapper - parameters helpers.Parameters -} - -var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) - -func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { - message := messageFromInterface(msg) - dataID := baseIDs.GenerateDataID(message.Data) - metas := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(dataID)) - - data := metas.Get(key.NewKey(dataID)) - if data != nil { - return newTransactionResponse(constants.EntityAlreadyExists) - } - - if message.Data.GenerateHashID().Compare(baseIDs.GenerateHashID()) != 0 { - metas.Add(mappable.NewMappable(message.Data)) - } - - return newTransactionResponse(nil) -} - -func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, _ []interface{}) helpers.Keeper { - transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters - return transactionKeeper -} -func keeperPrototype() helpers.TransactionKeeper { - return transactionKeeper{} -} diff --git a/modules/metas/module/transactions/reveal/message.go b/modules/metas/module/transactions/reveal/message.go deleted file mode 100644 index 10273fc4a..000000000 --- a/modules/metas/module/transactions/reveal/message.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package reveal - -import ( - "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/msgservice" - // gogoproto "github.com/gogo/protobuf/proto" - // "github.com/golang/protobuf/proto" - - "github.com/AssetMantle/modules/modules/metas/module/module" - "github.com/AssetMantle/modules/schema" - "github.com/AssetMantle/modules/schema/data" - "github.com/AssetMantle/modules/schema/errors/constants" - "github.com/AssetMantle/modules/schema/helpers" - codecUtilities "github.com/AssetMantle/modules/utilities" -) - -var _ helpers.Message = &Message{} -var _ sdkTypes.Msg = &Message{} - -// func init() { -// gogoproto.RegisterType((*Message)(nil), "reveal.Message") -// proto.RegisterType((*Message)(nil), "reveal.Message") -// } -func (message *Message) RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Transaction_serviceDesc) -} -func (message *Message) GenerateOnSuccessEvents() sdkTypes.Events { - return nil -} -func (message *Message) Route() string { return module.Name } -func (message *Message) Type() string { return Transaction.GetName() } -func (message *Message) ValidateBasic() error { - if _, err := govalidator.ValidateStruct(message); err != nil { - return sdkErrors.Wrap(constants.IncorrectMessage, err.Error()) - } - - return nil -} -func (message *Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(codecUtilities.MakeMessageCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message *Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{sdkTypes.AccAddress(message.From)} -} -func (*Message) RegisterCodec(codec *codec.LegacyAmino) { - schema.RegisterModuleConcrete(codec, &Message{}) -} -func messageFromInterface(msg sdkTypes.Msg) *Message { - switch value := msg.(type) { - case *Message: - return value - default: - return &Message{} - } -} -func messagePrototype() helpers.Message { - return &Message{} -} - -func newMessage(from []byte, data data.Data) sdkTypes.Msg { - return &Message{ - From: from, - Data: data, - } -} diff --git a/modules/metas/module/transactions/reveal/message.pb.go b/modules/metas/module/transactions/reveal/message.pb.go deleted file mode 100644 index cf7e72966..000000000 --- a/modules/metas/module/transactions/reveal/message.pb.go +++ /dev/null @@ -1,376 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: modules/metas/module/transactions/reveal/message.proto - -package reveal - -import ( - fmt "fmt" - github_com_AssetMantle_modules_schema_data "github.com/AssetMantle/modules/schema/data" - _ "github.com/AssetMantle/modules/schema/data/base" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From []byte `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - Data github_com_AssetMantle_modules_schema_data.Data `protobuf:"bytes,2,opt,name=data,proto3,customtype=github.com/AssetMantle/modules/schema/data.Data" json:"data"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_890b0fd202f6503c, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -func (m *Message) GetFrom() []byte { - if m != nil { - return m.From - } - return nil -} - -func init() { - proto.RegisterType((*Message)(nil), "reveal.Message") -} - -func init() { - proto.RegisterFile("modules/metas/module/transactions/reveal/message.proto", fileDescriptor_890b0fd202f6503c) -} - -var fileDescriptor_890b0fd202f6503c = []byte{ - // 295 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0xcb, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4d, 0x2d, 0x49, 0x2c, 0xd6, 0x87, 0xf0, 0xf4, 0x4b, 0x8a, 0x12, - 0xf3, 0x8a, 0x13, 0x93, 0x4b, 0x32, 0xf3, 0xf3, 0x8a, 0xf5, 0x8b, 0x52, 0xcb, 0x52, 0x13, 0x73, - 0xf4, 0x73, 0x53, 0x8b, 0x8b, 0x13, 0xd3, 0x53, 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0xd8, - 0x20, 0xa2, 0x52, 0x22, 0xe9, 0xf9, 0xe9, 0xf9, 0x60, 0x21, 0x7d, 0x10, 0x0b, 0x22, 0x2b, 0x25, - 0x5d, 0x9c, 0x9c, 0x91, 0x9a, 0x9b, 0xa8, 0x9f, 0x92, 0x58, 0x92, 0xa8, 0x9f, 0x94, 0x58, 0x9c, - 0x0a, 0x66, 0x41, 0x24, 0x95, 0xca, 0xb8, 0xd8, 0x7d, 0x21, 0x66, 0x09, 0x09, 0x71, 0xb1, 0xa4, - 0x15, 0xe5, 0xe7, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0xf0, 0x04, 0x81, 0xd9, 0x42, 0xe1, 0x5c, 0x2c, - 0x20, 0xc5, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xdc, 0x46, 0x5c, 0x7a, 0x20, 0xed, 0x7a, 0x2e, 0x89, - 0x25, 0x89, 0x4e, 0xe6, 0x27, 0xee, 0xc9, 0x33, 0xdc, 0xba, 0x27, 0xaf, 0x9f, 0x9e, 0x59, 0x92, - 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0xef, 0x58, 0x5c, 0x9c, 0x5a, 0xe2, 0x9b, 0x98, 0x57, - 0x92, 0x93, 0xaa, 0x0f, 0xf3, 0x0a, 0x92, 0xe5, 0x60, 0x8d, 0x41, 0x60, 0x03, 0x9d, 0x36, 0x33, - 0x9e, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, - 0x31, 0x5c, 0x78, 0x2c, 0xc7, 0x70, 0xe3, 0xb1, 0x1c, 0x03, 0x17, 0x57, 0x72, 0x7e, 0xae, 0x1e, - 0xc4, 0x47, 0x4e, 0x3c, 0x50, 0xc7, 0x05, 0x80, 0x1c, 0x1b, 0xc0, 0x18, 0xe5, 0x4e, 0xc0, 0x36, - 0x62, 0x03, 0x70, 0x11, 0x13, 0x73, 0x50, 0x44, 0xc4, 0x2a, 0x26, 0xb6, 0x20, 0x30, 0xf7, 0x14, - 0x8c, 0xf1, 0x88, 0x49, 0x08, 0xc2, 0x88, 0x71, 0x0f, 0x70, 0xf2, 0x4d, 0x2d, 0x49, 0x04, 0x39, - 0xf6, 0x15, 0x4c, 0x36, 0x89, 0x0d, 0x1c, 0x68, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xe2, - 0xd1, 0x11, 0xfb, 0xa9, 0x01, 0x00, 0x00, -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Data.Size() - i -= size - if _, err := m.Data.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintMessage(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovMessage(uint64(l)) - } - l = m.Data.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = append(m.From[:0], dAtA[iNdEx:postIndex]...) - if m.From == nil { - m.From = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/metas/module/transactions/reveal/message.proto b/modules/metas/module/transactions/reveal/message.proto deleted file mode 100644 index 7228bb4e0..000000000 --- a/modules/metas/module/transactions/reveal/message.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; -package reveal; - -import "gogoproto/gogo.proto"; -import "schema/data/base/data.proto"; - -message Message { - bytes from = 1; - base.Data data = 2 [ - (gogoproto.customtype) = "github.com/AssetMantle/modules/schema/data.Data", - (gogoproto.nullable) = false - ]; -} \ No newline at end of file diff --git a/modules/metas/module/transactions/reveal/request.go b/modules/metas/module/transactions/reveal/request.go deleted file mode 100644 index 231693053..000000000 --- a/modules/metas/module/transactions/reveal/request.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package reveal - -import ( - "encoding/json" - "net/http" - - "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - - "github.com/AssetMantle/modules/schema" - "github.com/AssetMantle/modules/schema/data/utilities" - "github.com/AssetMantle/modules/schema/helpers" - "github.com/AssetMantle/modules/schema/helpers/constants" -) - -var _ helpers.TransactionRequest = (*TransactionRequest)(nil) - -func (transactionRequest *TransactionRequest) GetRequest() helpers.TransactionRequest { - // TODO implement me - panic("implement me") -} - -func (transactionRequest *TransactionRequest) ValidateBasic(responseWriter http.ResponseWriter) bool { - // TODO implement me - panic("implement me") -} -func (transactionRequest *TransactionRequest) Validate() error { - _, err := govalidator.ValidateStruct(transactionRequest) - return err -} -func (transactionRequest *TransactionRequest) FromCLI(cliCommand helpers.CLICommand, context client.Context) (helpers.TransactionRequest, error) { - return newTransactionRequest( - cliCommand.ReadBaseReq(context), - cliCommand.ReadString(constants.Data), - ), nil -} -func (transactionRequest *TransactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { - return nil, err - } - - return transactionRequest, nil -} - -func (transactionRequest *TransactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from := transactionRequest.From - - data, err := utilities.ReadData(transactionRequest.Data) - if err != nil { - return nil, err - } - - return newMessage( - sdkTypes.MustAccAddressFromBech32(from), - data, - ), nil -} -func (*TransactionRequest) RegisterCodec(codec *codec.LegacyAmino) { - schema.RegisterModuleConcrete(codec, TransactionRequest{}) -} -func requestPrototype() helpers.TransactionRequest { - return &TransactionRequest{} -} -func newTransactionRequest(baseReq rest.BaseReq, data string) helpers.TransactionRequest { - return &TransactionRequest{ - From: baseReq.From, - Data: data, - } -} diff --git a/modules/metas/module/transactions/reveal/response.go b/modules/metas/module/transactions/reveal/response.go deleted file mode 100644 index b02f96902..000000000 --- a/modules/metas/module/transactions/reveal/response.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package reveal - -import ( - "github.com/AssetMantle/modules/schema/helpers" -) - -var _ helpers.TransactionResponse = (*TransactionResponse)(nil) - -func (transactionResponse *TransactionResponse) IsSuccessful() bool { - return transactionResponse.Success -} -func newTransactionResponse(error error) helpers.TransactionResponse { - success := true - if error != nil { - success = false - } - - return &TransactionResponse{ - Success: success, - Error: error.Error(), - } -} diff --git a/modules/metas/module/transactions/reveal/transaction.pb.go b/modules/metas/module/transactions/reveal/transaction.pb.go deleted file mode 100644 index 8c16584d2..000000000 --- a/modules/metas/module/transactions/reveal/transaction.pb.go +++ /dev/null @@ -1,133 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: modules/metas/module/transactions/reveal/transaction.proto - -package reveal - -import ( - context "context" - fmt "fmt" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -func init() { - proto.RegisterFile("modules/metas/module/transactions/reveal/transaction.proto", fileDescriptor_f8ff0aa578548ac1) -} - -var fileDescriptor_f8ff0aa578548ac1 = []byte{ - // 285 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0xca, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4d, 0x2d, 0x49, 0x2c, 0xd6, 0x87, 0xf0, 0xf4, 0x4b, 0x8a, 0x12, - 0xf3, 0x8a, 0x13, 0x93, 0x4b, 0x32, 0xf3, 0xf3, 0x8a, 0xf5, 0x8b, 0x52, 0xcb, 0x52, 0x13, 0x73, - 0x90, 0xc5, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0xd8, 0x20, 0x32, 0x52, 0x66, 0x44, 0x9b, - 0x91, 0x9b, 0x5a, 0x5c, 0x9c, 0x98, 0x9e, 0x0a, 0xd1, 0x2f, 0xe5, 0x44, 0x8e, 0xdd, 0x41, 0xa9, - 0xc5, 0x05, 0xf9, 0x79, 0xc5, 0x30, 0x33, 0x64, 0xd2, 0xf3, 0xf3, 0xd3, 0x73, 0x52, 0xf5, 0x13, - 0x0b, 0x32, 0xf5, 0x13, 0xf3, 0xf2, 0xf2, 0x4b, 0x12, 0xc1, 0x1a, 0x21, 0xb2, 0x46, 0xc9, 0x5c, - 0xdc, 0x21, 0x08, 0xad, 0x42, 0x21, 0x5c, 0x6c, 0x41, 0x60, 0x03, 0x85, 0xf8, 0xf5, 0x20, 0x26, - 0xeb, 0xf9, 0x42, 0x5c, 0x24, 0x25, 0x0d, 0x13, 0x08, 0xc1, 0xb4, 0x4a, 0x49, 0xa6, 0xe9, 0xf2, - 0x93, 0xc9, 0x4c, 0x62, 0x4a, 0x22, 0xfa, 0xb9, 0x89, 0x79, 0x25, 0x39, 0xa9, 0x50, 0x07, 0x43, - 0x74, 0x38, 0x6d, 0x67, 0x3c, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, - 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x06, 0x2e, 0xae, - 0xe4, 0xfc, 0x5c, 0xa8, 0xc1, 0x4e, 0x02, 0x48, 0x26, 0x07, 0x80, 0x5c, 0x17, 0xc0, 0x18, 0xe5, - 0x9e, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0xef, 0x58, 0x5c, 0x9c, 0x5a, - 0xe2, 0x0b, 0x35, 0x1f, 0x16, 0x30, 0x44, 0x06, 0xd0, 0x22, 0x26, 0xe6, 0xa0, 0x88, 0x88, 0x55, - 0x4c, 0x50, 0xef, 0x9d, 0x82, 0x31, 0x1e, 0x31, 0x09, 0x41, 0x18, 0x31, 0xee, 0x01, 0x4e, 0xbe, - 0xa9, 0x25, 0x89, 0x29, 0x89, 0x25, 0x89, 0xaf, 0x60, 0xb2, 0x49, 0x6c, 0xe0, 0x50, 0x32, 0x06, - 0x04, 0x00, 0x00, 0xff, 0xff, 0xd2, 0x95, 0xed, 0x70, 0x05, 0x02, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// TransactionClient is the client API for Transaction service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type TransactionClient interface { - Reveal(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type transactionClient struct { - cc grpc1.ClientConn -} - -func NewTransactionClient(cc grpc1.ClientConn) TransactionClient { - return &transactionClient{cc} -} - -func (c *transactionClient) Reveal(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/reveal.Transaction/Reveal", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// TransactionServer is the server API for Transaction service. -type TransactionServer interface { - Reveal(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedTransactionServer can be embedded to have forward compatible implementations. -type UnimplementedTransactionServer struct { -} - -func (*UnimplementedTransactionServer) Reveal(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Reveal not implemented") -} - -func RegisterTransactionServer(s grpc1.Server, srv TransactionServer) { - s.RegisterService(&_Transaction_serviceDesc, srv) -} - -func _Transaction_Reveal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(TransactionServer).Reveal(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/reveal.Transaction/Reveal", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(TransactionServer).Reveal(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Transaction_serviceDesc = grpc.ServiceDesc{ - ServiceName: "reveal.Transaction", - HandlerType: (*TransactionServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Reveal", - Handler: _Transaction_Reveal_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "modules/metas/module/transactions/reveal/transaction.proto", -} diff --git a/modules/metas/module/transactions/reveal/transaction.pb.gw.go b/modules/metas/module/transactions/reveal/transaction.pb.gw.go deleted file mode 100644 index 8b80d263c..000000000 --- a/modules/metas/module/transactions/reveal/transaction.pb.gw.go +++ /dev/null @@ -1,171 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: modules/metas/module/transactions/reveal/transaction.proto - -/* -Package reveal is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package reveal - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage -var _ = metadata.Join - -var ( - filter_Transaction_Reveal_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Transaction_Reveal_0(ctx context.Context, marshaler runtime.Marshaler, client TransactionClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq Message - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Transaction_Reveal_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Reveal(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Transaction_Reveal_0(ctx context.Context, marshaler runtime.Marshaler, server TransactionServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq Message - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Transaction_Reveal_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Reveal(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterTransactionHandlerServer registers the http handlers for service Transaction to "mux". -// UnaryRPC :call TransactionServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterTransactionHandlerFromEndpoint instead. -func RegisterTransactionHandlerServer(ctx context.Context, mux *runtime.ServeMux, server TransactionServer) error { - - mux.Handle("POST", pattern_Transaction_Reveal_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Transaction_Reveal_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Transaction_Reveal_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterTransactionHandlerFromEndpoint is same as RegisterTransactionHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterTransactionHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterTransactionHandler(ctx, mux, conn) -} - -// RegisterTransactionHandler registers the http handlers for service Transaction to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterTransactionHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterTransactionHandlerClient(ctx, mux, NewTransactionClient(conn)) -} - -// RegisterTransactionHandlerClient registers the http handlers for service Transaction -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "TransactionClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "TransactionClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "TransactionClient" to call the correct interceptors. -func RegisterTransactionHandlerClient(ctx context.Context, mux *runtime.ServeMux, client TransactionClient) error { - - mux.Handle("POST", pattern_Transaction_Reveal_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Transaction_Reveal_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Transaction_Reveal_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Transaction_Reveal_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"mantle", "metas", "reveal"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Transaction_Reveal_0 = runtime.ForwardResponseMessage -) diff --git a/modules/metas/module/transactions/reveal/transaction.proto b/modules/metas/module/transactions/reveal/transaction.proto deleted file mode 100644 index c9d58c5f3..000000000 --- a/modules/metas/module/transactions/reveal/transaction.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; -package reveal; - -import "modules/metas/module/transactions/reveal/message.proto"; -import "modules/metas/module/transactions/reveal/transactionResponse.proto"; -import "google/api/annotations.proto"; - -service Transaction{ - rpc Reveal(Message) returns (TransactionResponse){ - option (google.api.http).post = "/mantle/metas/reveal"; - } -} \ No newline at end of file diff --git a/modules/metas/module/transactions/reveal/transactionRequest.pb.go b/modules/metas/module/transactions/reveal/transactionRequest.pb.go deleted file mode 100644 index cd50e656c..000000000 --- a/modules/metas/module/transactions/reveal/transactionRequest.pb.go +++ /dev/null @@ -1,372 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: modules/metas/module/transactions/reveal/transactionRequest.proto - -package reveal - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type TransactionRequest struct { - From string `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"` - Data string `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *TransactionRequest) Reset() { *m = TransactionRequest{} } -func (m *TransactionRequest) String() string { return proto.CompactTextString(m) } -func (*TransactionRequest) ProtoMessage() {} -func (*TransactionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_c0aca19224f63e93, []int{0} -} -func (m *TransactionRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionRequest.Merge(m, src) -} -func (m *TransactionRequest) XXX_Size() int { - return m.Size() -} -func (m *TransactionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionRequest proto.InternalMessageInfo - -func (m *TransactionRequest) GetFrom() string { - if m != nil { - return m.From - } - return "" -} - -func (m *TransactionRequest) GetData() string { - if m != nil { - return m.Data - } - return "" -} - -func init() { - proto.RegisterType((*TransactionRequest)(nil), "reveal.TransactionRequest") -} - -func init() { - proto.RegisterFile("modules/metas/module/transactions/reveal/transactionRequest.proto", fileDescriptor_c0aca19224f63e93) -} - -var fileDescriptor_c0aca19224f63e93 = []byte{ - // 231 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x72, 0xcc, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4d, 0x2d, 0x49, 0x2c, 0xd6, 0x87, 0xf0, 0xf4, 0x4b, 0x8a, 0x12, - 0xf3, 0x8a, 0x13, 0x93, 0x4b, 0x32, 0xf3, 0xf3, 0x8a, 0xf5, 0x8b, 0x52, 0xcb, 0x52, 0x13, 0x73, - 0x90, 0xc5, 0x82, 0x52, 0x0b, 0x4b, 0x53, 0x8b, 0x4b, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, - 0xd8, 0x20, 0x0a, 0x94, 0x6c, 0xb8, 0x84, 0x42, 0x30, 0xd4, 0x08, 0x09, 0x71, 0xb1, 0xa4, 0x15, - 0xe5, 0xe7, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x06, 0x81, 0xd9, 0x20, 0xb1, 0x94, 0xc4, 0x92, - 0x44, 0x09, 0x26, 0x88, 0x18, 0x88, 0xed, 0xb4, 0x8f, 0xf1, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, - 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, - 0x8f, 0xe5, 0x18, 0xb8, 0xb8, 0x92, 0xf3, 0x73, 0xf5, 0x20, 0x96, 0x38, 0x89, 0x63, 0x5a, 0x11, - 0x00, 0x72, 0x45, 0x00, 0x63, 0x94, 0x7b, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, - 0xae, 0xbe, 0x63, 0x71, 0x71, 0x6a, 0x89, 0x6f, 0x62, 0x5e, 0x49, 0x4e, 0xaa, 0x3e, 0xdc, 0x87, - 0x44, 0xfa, 0x74, 0x11, 0x13, 0x73, 0x50, 0x44, 0xc4, 0x2a, 0x26, 0xb6, 0x20, 0x30, 0xf7, 0x14, - 0x8c, 0xf1, 0x88, 0x49, 0x08, 0xc2, 0x88, 0x71, 0x0f, 0x70, 0xf2, 0x4d, 0x2d, 0x49, 0x04, 0xb9, - 0xfb, 0x15, 0x4c, 0x36, 0x89, 0x0d, 0x1c, 0x1a, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x1c, - 0x30, 0xcd, 0xed, 0x52, 0x01, 0x00, 0x00, -} - -func (m *TransactionRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintTransactionRequest(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0x12 - } - if len(m.From) > 0 { - i -= len(m.From) - copy(dAtA[i:], m.From) - i = encodeVarintTransactionRequest(dAtA, i, uint64(len(m.From))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintTransactionRequest(dAtA []byte, offset int, v uint64) int { - offset -= sovTransactionRequest(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *TransactionRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.From) - if l > 0 { - n += 1 + l + sovTransactionRequest(uint64(l)) - } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTransactionRequest(uint64(l)) - } - return n -} - -func sovTransactionRequest(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTransactionRequest(x uint64) (n int) { - return sovTransactionRequest(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *TransactionRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTransactionRequest - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTransactionRequest - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTransactionRequest - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTransactionRequest - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.From = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTransactionRequest - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTransactionRequest - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTransactionRequest - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTransactionRequest(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTransactionRequest - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTransactionRequest(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTransactionRequest - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTransactionRequest - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTransactionRequest - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTransactionRequest - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTransactionRequest - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTransactionRequest - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTransactionRequest = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTransactionRequest = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTransactionRequest = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/metas/module/transactions/reveal/transactionRequest.proto b/modules/metas/module/transactions/reveal/transactionRequest.proto deleted file mode 100644 index 95c668d98..000000000 --- a/modules/metas/module/transactions/reveal/transactionRequest.proto +++ /dev/null @@ -1,7 +0,0 @@ -syntax = "proto3"; -package reveal; - -message TransactionRequest{ - string from = 1; - string data = 2; -} \ No newline at end of file diff --git a/modules/metas/module/transactions/reveal/transactionResponse.pb.go b/modules/metas/module/transactions/reveal/transactionResponse.pb.go deleted file mode 100644 index 07a36c7ee..000000000 --- a/modules/metas/module/transactions/reveal/transactionResponse.pb.go +++ /dev/null @@ -1,364 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: modules/metas/module/transactions/reveal/transactionResponse.proto - -package reveal - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type TransactionResponse struct { - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - // TODO define error object - Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_7ddaedcb2f4c228e, []int{0} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func (m *TransactionResponse) GetSuccess() bool { - if m != nil { - return m.Success - } - return false -} - -func (m *TransactionResponse) GetError() string { - if m != nil { - return m.Error - } - return "" -} - -func init() { - proto.RegisterType((*TransactionResponse)(nil), "reveal.TransactionResponse") -} - -func init() { - proto.RegisterFile("modules/metas/module/transactions/reveal/transactionResponse.proto", fileDescriptor_7ddaedcb2f4c228e) -} - -var fileDescriptor_7ddaedcb2f4c228e = []byte{ - // 243 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x72, 0xca, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x4d, 0x2d, 0x49, 0x2c, 0xd6, 0x87, 0xf0, 0xf4, 0x4b, 0x8a, 0x12, - 0xf3, 0x8a, 0x13, 0x93, 0x4b, 0x32, 0xf3, 0xf3, 0x8a, 0xf5, 0x8b, 0x52, 0xcb, 0x52, 0x13, 0x73, - 0x90, 0xc5, 0x82, 0x52, 0x8b, 0x0b, 0xf2, 0xf3, 0x8a, 0x53, 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, - 0x85, 0xd8, 0x20, 0x2a, 0x94, 0x5c, 0xb9, 0x84, 0x43, 0x30, 0x15, 0x09, 0x49, 0x70, 0xb1, 0x17, - 0x97, 0x26, 0x27, 0xa7, 0x16, 0x17, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x04, 0xc1, 0xb8, 0x42, - 0x22, 0x5c, 0xac, 0xa9, 0x45, 0x45, 0xf9, 0x45, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x10, - 0x8e, 0xd3, 0x7e, 0xc6, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, - 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0xe0, 0xe2, 0x4a, - 0xce, 0xcf, 0xd5, 0x83, 0xd8, 0xe6, 0x24, 0x81, 0xc5, 0xae, 0x00, 0x90, 0x7b, 0x02, 0x18, 0xa3, - 0xdc, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x1d, 0x8b, 0x8b, 0x53, - 0x4b, 0x7c, 0x13, 0xf3, 0x4a, 0x72, 0x52, 0xf5, 0xe1, 0x9e, 0x25, 0xd2, 0xd3, 0x8b, 0x98, 0x98, - 0x83, 0x22, 0x22, 0x56, 0x31, 0xb1, 0x05, 0x81, 0xb9, 0xa7, 0x60, 0x8c, 0x47, 0x4c, 0x42, 0x10, - 0x46, 0x8c, 0x7b, 0x80, 0x93, 0x6f, 0x6a, 0x49, 0x62, 0x4a, 0x62, 0x49, 0xe2, 0x2b, 0x98, 0x6c, - 0x12, 0x1b, 0x38, 0x5c, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xd3, 0x4d, 0x0a, 0x22, 0x5d, - 0x01, 0x00, 0x00, -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Error) > 0 { - i -= len(m.Error) - copy(dAtA[i:], m.Error) - i = encodeVarintTransactionResponse(dAtA, i, uint64(len(m.Error))) - i-- - dAtA[i] = 0x12 - } - if m.Success { - i-- - if m.Success { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintTransactionResponse(dAtA []byte, offset int, v uint64) int { - offset -= sovTransactionResponse(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Success { - n += 2 - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovTransactionResponse(uint64(l)) - } - return n -} - -func sovTransactionResponse(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTransactionResponse(x uint64) (n int) { - return sovTransactionResponse(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTransactionResponse - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTransactionResponse - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Success = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTransactionResponse - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTransactionResponse - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTransactionResponse - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTransactionResponse(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTransactionResponse - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipTransactionResponse(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTransactionResponse - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTransactionResponse - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowTransactionResponse - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthTransactionResponse - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTransactionResponse - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTransactionResponse - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTransactionResponse = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTransactionResponse = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTransactionResponse = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/metas/module/transactions/reveal/transactionResponse.proto b/modules/metas/module/transactions/reveal/transactionResponse.proto deleted file mode 100644 index d55675cbd..000000000 --- a/modules/metas/module/transactions/reveal/transactionResponse.proto +++ /dev/null @@ -1,8 +0,0 @@ -syntax = "proto3"; -package reveal; - -message TransactionResponse{ - bool success = 1; - // TODO define error object - string error = 2; -} \ No newline at end of file diff --git a/modules/metas/prototype.go b/modules/metas/prototype.go index 7ab48de57..7bb6811f3 100644 --- a/modules/metas/prototype.go +++ b/modules/metas/prototype.go @@ -4,14 +4,15 @@ package metas import ( - "github.com/AssetMantle/modules/modules/metas/module/block" - "github.com/AssetMantle/modules/modules/metas/module/genesis" - "github.com/AssetMantle/modules/modules/metas/module/invariants" - "github.com/AssetMantle/modules/modules/metas/module/mapper" - "github.com/AssetMantle/modules/modules/metas/module/module" - "github.com/AssetMantle/modules/modules/metas/module/parameters" - "github.com/AssetMantle/modules/modules/metas/module/queries" - "github.com/AssetMantle/modules/modules/metas/module/transactions" + "github.com/AssetMantle/modules/modules/metas/auxiliaries" + "github.com/AssetMantle/modules/modules/metas/internal/block" + "github.com/AssetMantle/modules/modules/metas/internal/genesis" + "github.com/AssetMantle/modules/modules/metas/internal/mapper" + "github.com/AssetMantle/modules/modules/metas/internal/module" + "github.com/AssetMantle/modules/modules/metas/internal/parameters" + "github.com/AssetMantle/modules/modules/metas/internal/queries" + "github.com/AssetMantle/modules/modules/metas/internal/simulator" + "github.com/AssetMantle/modules/modules/metas/internal/transactions" "github.com/AssetMantle/modules/schema/helpers" baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" ) @@ -19,19 +20,13 @@ import ( func Prototype() helpers.Module { return baseHelpers.NewModule( module.Name, - 1, - Prototypee, - block.Prototype, + auxiliaries.Prototype, genesis.Prototype, - invariants.Prototype, mapper.Prototype, - nil, parameters.Prototype, queries.Prototype, - nil, + simulator.Prototype, transactions.Prototype, + block.Prototype, ) } -func Prototypee() helpers.Auxiliaries { - return baseHelpers.NewAuxiliaries() -} diff --git a/modules/metas/prototype_test.go b/modules/metas/prototype_test.go new file mode 100644 index 000000000..1041553e9 --- /dev/null +++ b/modules/metas/prototype_test.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package metas + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries" + "github.com/AssetMantle/modules/modules/metas/internal/block" + "github.com/AssetMantle/modules/modules/metas/internal/genesis" + "github.com/AssetMantle/modules/modules/metas/internal/mapper" + "github.com/AssetMantle/modules/modules/metas/internal/module" + "github.com/AssetMantle/modules/modules/metas/internal/parameters" + "github.com/AssetMantle/modules/modules/metas/internal/queries" + "github.com/AssetMantle/modules/modules/metas/internal/simulator" + "github.com/AssetMantle/modules/modules/metas/internal/transactions" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Name(), baseHelpers.NewModule( + module.Name, + auxiliaries.Prototype, + genesis.Prototype, + mapper.Prototype, + parameters.Prototype, + queries.Prototype, + simulator.Prototype, + transactions.Prototype, + block.Prototype, + ).Name()) +} diff --git a/modules/orders/auxiliaries/prototype.go b/modules/orders/auxiliaries/prototype.go new file mode 100644 index 000000000..31a4dee9b --- /dev/null +++ b/modules/orders/auxiliaries/prototype.go @@ -0,0 +1,13 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Auxiliaries { + return baseHelpers.NewAuxiliaries() +} diff --git a/modules/orders/auxiliaries/prototype_test.go b/modules/orders/auxiliaries/prototype_test.go new file mode 100644 index 000000000..090358515 --- /dev/null +++ b/modules/orders/auxiliaries/prototype_test.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "testing" + + "github.com/stretchr/testify/require" + + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Test_Auxiliary_Prototype(t *testing.T) { + require.Equal(t, baseHelpers.NewAuxiliaries(), Prototype()) +} diff --git a/modules/orders/doc.go b/modules/orders/doc.go new file mode 100644 index 000000000..99896cdc1 --- /dev/null +++ b/modules/orders/doc.go @@ -0,0 +1,5 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +// Package orders defines the orders' module. +package orders diff --git a/modules/orders/internal/block/block.go b/modules/orders/internal/block/block.go new file mode 100755 index 000000000..755f635b0 --- /dev/null +++ b/modules/orders/internal/block/block.go @@ -0,0 +1,203 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package block + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + abciTypes "github.com/tendermint/tendermint/abci/types" + + "github.com/AssetMantle/modules/modules/metas/auxiliaries/scrub" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/properties/constants" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +type block struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + scrubAuxiliary helpers.Auxiliary +} + +var _ helpers.Block = (*block)(nil) + +func (block block) Begin(_ sdkTypes.Context, _ abciTypes.RequestBeginBlock) { + +} + +func (block block) End(context sdkTypes.Context, _ abciTypes.RequestEndBlock) { + executeOrders := make(map[ids.OrderID]bool) + orders := block.mapper.NewCollection(context) + + orders.Iterate( + // TODO ***** define a proper new key + key.NewKey(baseIDs.PrototypeOrderID()), + func(Mappable helpers.Mappable) bool { + order := Mappable.(documents.Order) + + if order.GetExpiryHeight().Compare(baseTypes.NewHeight(context.BlockHeight())) <= 0 { + // TODO ***** check security of sending and receiving from module and module account security + if auxiliaryResponse := block.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, order.GetMakerID(), order.GetMakerOwnableID(), order.GetMakerOwnableSplit())); !auxiliaryResponse.IsSuccessful() { + panic(auxiliaryResponse.GetError()) + } + orders.Remove(mappable.NewMappable(order)) + } else { + // TODO ***** figure out use case + // // TODO ***** test + // id1 := baseIDs.NewOrderID(order.GetClassificationID(), order.GetMakerOwnableID(), order.GetTakerOwnableID(), sdkTypes.SmallestDec(), baseTypes.NewHeight(0), baseIDs.PrototypeIdentityID(), baseQualified.NewImmutables(baseLists.NewPropertyList())) + // // TODO ***** test + // id2 := baseIDs.NewOrderID(order.GetClassificationID(), order.GetTakerOwnableID(), order.GetMakerOwnableID(), sdkTypes.SmallestDec(), baseTypes.NewHeight(0), baseIDs.PrototypeIdentityID(), baseQualified.NewImmutables(baseLists.NewPropertyList())) + // if !executeOrders[id1] && !executeOrders[id2] { + // executeOrders[id1] = true + // } + } + return false + }, + ) + + for partialOrderID := range executeOrders { + nextPartialOrderID := false + + orders.Iterate(key.NewKey(partialOrderID), + func(Mappable helpers.Mappable) bool { + order := Mappable.(documents.Order) + orders.Iterate( + key.NewKey(baseIDs.PrototypeOrderID()), + func(Mappable helpers.Mappable) bool { + executableOrder := Mappable.(documents.Order) + var leftOrder documents.Order + var rightOrder documents.Order + + orderHeight := order.GetCreationHeight() + + executableOrderHeight := executableOrder.GetCreationHeight() + + switch { + case orderHeight.Compare(executableOrderHeight) > 0: + leftOrder = order + rightOrder = executableOrder + case executableOrderHeight.Compare(orderHeight) > 0: + leftOrder = executableOrder + rightOrder = order + default: + leftOrder = order + rightOrder = executableOrder + } + + leftOrderExchangeRate := leftOrder.GetExchangeRate() + + leftOrderMakerOwnableSplit := leftOrder.GetMakerOwnableSplit() + + rightOrderExchangeRate := rightOrder.GetExchangeRate() + + rightOrderMakerOwnableSplit := rightOrder.GetMakerOwnableSplit() + + rightOrderTakerOwnableSplitDemanded := rightOrderExchangeRate.MulTruncate(rightOrderMakerOwnableSplit).MulTruncate(sdkTypes.SmallestDec()) + + if leftOrderExchangeRate.MulTruncate(rightOrderExchangeRate).MulTruncate(sdkTypes.SmallestDec()).MulTruncate(sdkTypes.SmallestDec()).LTE(sdkTypes.OneDec()) { + switch { + case leftOrderMakerOwnableSplit.GT(rightOrderTakerOwnableSplitDemanded): + if auxiliaryResponse := block.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, leftOrder.GetMakerID(), leftOrder.GetTakerOwnableID(), rightOrderMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { + panic(auxiliaryResponse.GetError()) + } + if auxiliaryResponse := block.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, rightOrder.GetMakerID(), leftOrder.GetMakerOwnableID(), rightOrderTakerOwnableSplitDemanded)); !auxiliaryResponse.IsSuccessful() { + panic(auxiliaryResponse.GetError()) + } + + mutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(constants.MakerOwnableSplitProperty.GetKey(), baseData.NewDecData(leftOrderMakerOwnableSplit.Sub(rightOrderTakerOwnableSplitDemanded)))) + + orders.Mutate(mappable.NewMappable(base.NewOrder(leftOrder.GetClassificationID(), leftOrder.GetImmutables(), leftOrder.Mutate(mutableProperties.GetList()...).GetMutables()))) + orders.Remove(mappable.NewMappable(rightOrder)) + + if executableOrderHeight.Compare(orderHeight) > 0 { + return true + } + case leftOrderMakerOwnableSplit.LT(rightOrderTakerOwnableSplitDemanded): + sendToLeftOrder := leftOrderMakerOwnableSplit.QuoTruncate(sdkTypes.SmallestDec()).QuoTruncate(rightOrderExchangeRate) + if auxiliaryResponse := block.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, leftOrder.GetMakerID(), leftOrder.GetTakerOwnableID(), sendToLeftOrder)); !auxiliaryResponse.IsSuccessful() { + panic(auxiliaryResponse.GetError()) + } + if auxiliaryResponse := block.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, rightOrder.GetMakerID(), leftOrder.GetMakerOwnableID(), leftOrderMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { + panic(auxiliaryResponse.GetError()) + } + + mutableProperties, err := scrub.GetPropertiesFromResponse(block.scrubAuxiliary.GetKeeper().Help(context, scrub.NewAuxiliaryRequest(baseLists.NewPropertyList(baseProperties.NewMetaProperty(constants.MakerOwnableSplitProperty.GetKey(), baseData.NewDecData(rightOrderMakerOwnableSplit.Sub(sendToLeftOrder))))))) + if err != nil { + panic(err) + } + + orders.Mutate(mappable.NewMappable(base.NewOrder(rightOrder.GetClassificationID(), rightOrder.GetImmutables(), rightOrder.GetMutables().Mutate(mutableProperties.GetList()...)))) + orders.Remove(mappable.NewMappable(leftOrder)) + + if orderHeight.Compare(executableOrderHeight) >= 0 { + return true + } + default: + // case leftOrderMakerOwnableSplit.Equal(rightOrderTakerOwnableSplitDemanded): + if auxiliaryResponse := block.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, leftOrder.GetMakerID(), leftOrder.GetTakerOwnableID(), rightOrderMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { + panic(auxiliaryResponse.GetError()) + } + if auxiliaryResponse := block.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, rightOrder.GetMakerID(), leftOrder.GetMakerOwnableID(), leftOrderMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { + panic(auxiliaryResponse.GetError()) + } + + orders.Remove(mappable.NewMappable(rightOrder)) + orders.Remove(mappable.NewMappable(leftOrder)) + return true + } + } else { + nextPartialOrderID = true + return true + } + return false + }, + ) + return nextPartialOrderID + }) + + if nextPartialOrderID { + continue + } + } +} + +func Prototype() helpers.Block { + return block{} +} + +func (block block) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaryKeepers ...interface{}) helpers.Block { + block.mapper, block.parameters = mapper, parameters + + for _, auxiliaryKeeper := range auxiliaryKeepers { + switch value := auxiliaryKeeper.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case supplement.Auxiliary.GetName(): + block.supplementAuxiliary = value + case transfer.Auxiliary.GetName(): + block.transferAuxiliary = value + case scrub.Auxiliary.GetName(): + block.scrubAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return block +} diff --git a/modules/orders/internal/block/block_test.go b/modules/orders/internal/block/block_test.go index 71d62583a..1888d2979 100644 --- a/modules/orders/internal/block/block_test.go +++ b/modules/orders/internal/block/block_test.go @@ -4,9 +4,10 @@ package block import ( - "github.com/AssetMantle/modules/modules/metas/auxiliaries/scrub" "testing" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/scrub" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" diff --git a/modules/orders/internal/common/codec.go b/modules/orders/internal/common/codec.go new file mode 100644 index 000000000..3d765e0c1 --- /dev/null +++ b/modules/orders/internal/common/codec.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package common + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/utilities/module" +) + +var Codec *codec.Codec + +func init() { + Codec = module.RegisterCodec(key.Prototype, mappable.Prototype) +} diff --git a/modules/orders/internal/genesis/genesis.go b/modules/orders/internal/genesis/genesis.go deleted file mode 100644 index c2d345aa2..000000000 --- a/modules/orders/internal/genesis/genesis.go +++ /dev/null @@ -1,188 +0,0 @@ -package genesis - -import ( - "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ helpers.Genesis = (*Genesis)(nil) - -func (genesis Genesis) Default() helpers.Genesis { - return genesis.Initialize(genesis.GetMappableList(), genesis.GetParameterList()) -} - -func (genesis Genesis) Validate() error { - if len(genesis.ParameterList) != len(genesis.DefaultParameterList) { - return errors.InvalidParameter - } - - for _, parameter := range genesis.ParameterList { - var isPresent bool - for _, defaultParameter := range genesis.DefaultParameterList { - isPresent = false - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - isPresent = true - break - } - } - - if !isPresent { - return errors.InvalidParameter - } - - if Error := parameter.Validate(); Error != nil { - return Error - } - } - - _, Error := govalidator.ValidateStruct(genesis) - - return Error -} - -func (genesis Genesis) Import(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) { - for _, mappableValue := range genesis.MappableList { - mapper.Create(context, &mappableValue) - } - - for _, parameter := range genesis.ParameterList { - parameters.Mutate(context, ¶meter) - } -} - -func (genesis Genesis) Export(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) helpers.Genesis { - var mappableList []helpers.Mappable - - appendMappableList := func(mappable helpers.Mappable) bool { - mappableList = append(mappableList, mappable) - return false - } - mapper.Iterate(context, key.Prototype(), appendMappableList) - - for _, defaultParameter := range genesis.DefaultParameterList { - parameters = parameters.Fetch(context, defaultParameter.GetID()) - } - - return genesis.Initialize(mappableList, parameters.GetList()) -} - -func (genesis Genesis) LegacyAminoEncode() []byte { - legacyAminoCodec := codec.NewLegacyAmino() - bytes, Error := legacyAminoCodec.MarshalJSON(genesis) - if Error != nil { - panic(Error) - } - - return bytes -} -func (genesis Genesis) LegacyAminoDecode(byte []byte) helpers.Genesis { - var newGenesis Genesis - legacyAminoCodec := codec.NewLegacyAmino() - if Error := legacyAminoCodec.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(genesis.DefaultMappableList, genesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Encode(cdc codec.JSONMarshaler) []byte { - bytes, Error := cdc.MarshalJSON(&genesis) - if Error != nil { - panic(Error) - } - - return bytes -} - -func (genesis Genesis) Decode(cdc codec.JSONMarshaler, byte []byte) helpers.Genesis { - var newGenesis Genesis - if Error := cdc.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(genesis.DefaultMappableList, genesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Initialize(mappableList []helpers.Mappable, parameterList []types.Parameter) helpers.Genesis { - newParametersList := make([]dummy.DummyParameter, len(parameterList)) - for i, _ := range parameterList { - newParametersList[i] = *dummy.NewParameter(parameterList[i].GetID(), parameterList[i].GetData()) - } - newMappableList := make([]mappable.Order, len(mappableList)) - for i, _ := range mappableList { - newMappableList[i] = *mappableList[i].(*mappable.Order) - } - newParameter := dummy.Parameter.Mutate(dummy.Parameter.GetData()) - genesis.DefaultParameterList = []dummy.DummyParameter{*dummy.NewParameter(newParameter.GetID(), newParameter.GetData())} - if len(newMappableList) == 0 { - genesis.MappableList = genesis.DefaultMappableList - } else { - genesis.MappableList = newMappableList - } - - if len(newParametersList) == 0 { - genesis.ParameterList = genesis.DefaultParameterList - } else { - for _, defaultParameter := range genesis.DefaultParameterList { - for i, parameter := range newParametersList { - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - newParametersList[i] = *dummy.NewParameter(defaultParameter.Mutate(parameter.GetData()).GetID(), defaultParameter.Mutate(parameter.GetData()).GetData()) - } - } - } - genesis.ParameterList = newParametersList - } - - if Error := genesis.Validate(); Error != nil { - panic(Error) - } - - return &genesis -} - -func (genesis Genesis) GetParameterList() []types.Parameter { - newParameterList := make([]types.Parameter, len(genesis.ParameterList)) - for i, _ := range genesis.ParameterList { - newParameterList[i] = &genesis.ParameterList[i] - } - return newParameterList -} -func (genesis Genesis) GetMappableList() []helpers.Mappable { - newMappableList := make([]helpers.Mappable, len(genesis.MappableList)) - for i, _ := range genesis.MappableList { - newMappableList[i] = &genesis.MappableList[i] - } - return newMappableList -} - -func (genesis Genesis) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*helpers.Key)(nil), - &key.OrderID{}, - ) - registry.RegisterImplementations((*helpers.Mappable)(nil), - &mappable.Order{}, - ) - registry.RegisterImplementations((*types.Parameter)(nil), - &dummy.DummyParameter{}, - ) - registry.RegisterImplementations((*helpers.Genesis)(nil), - &Genesis{}, - ) -} - -func NewGenesis(defaultMappableList []mappable.Order, defaultParameterList []dummy.DummyParameter) *Genesis { - return &Genesis{ - DefaultMappableList: defaultMappableList, - DefaultParameterList: defaultParameterList, - MappableList: []mappable.Order{}, - ParameterList: []dummy.DummyParameter{}, - } -} diff --git a/modules/orders/internal/genesis/genesis.pb.go b/modules/orders/internal/genesis/genesis.pb.go deleted file mode 100644 index 97dae072b..000000000 --- a/modules/orders/internal/genesis/genesis.pb.go +++ /dev/null @@ -1,499 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/genesis/genesis.proto - -package genesis - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - mappable "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - dummy "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters/dummy" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Genesis struct { - DefaultMappableList []mappable.Order `protobuf:"bytes,1,rep,name=defaultMappableList,proto3" json:"defaultMappableList"` - DefaultParameterList []dummy.DummyParameter `protobuf:"bytes,2,rep,name=defaultParameterList,proto3" json:"defaultParameterList"` - MappableList []mappable.Order `protobuf:"bytes,3,rep,name=MappableList,proto3" json:"MappableList"` - ParameterList []dummy.DummyParameter `protobuf:"bytes,4,rep,name=ParameterList,proto3" json:"ParameterList"` -} - -func (m *Genesis) Reset() { *m = Genesis{} } -func (m *Genesis) String() string { return proto.CompactTextString(m) } -func (*Genesis) ProtoMessage() {} -func (*Genesis) Descriptor() ([]byte, []int) { - return fileDescriptor_7dcbd95c78f6df33, []int{0} -} -func (m *Genesis) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Genesis) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Genesis.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Genesis) XXX_Merge(src proto.Message) { - xxx_messageInfo_Genesis.Merge(m, src) -} -func (m *Genesis) XXX_Size() int { - return m.Size() -} -func (m *Genesis) XXX_DiscardUnknown() { - xxx_messageInfo_Genesis.DiscardUnknown(m) -} - -var xxx_messageInfo_Genesis proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Genesis)(nil), "persistence_sdk.modules.orders.internal.genesis.Genesis") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/orders/internal/genesis/genesis.proto", fileDescriptor_7dcbd95c78f6df33) -} - -var fileDescriptor_7dcbd95c78f6df33 = []byte{ - // 325 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x2d, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x2f, 0x4a, 0x49, 0x2d, 0x2a, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, - 0xca, 0x4b, 0xcc, 0xd1, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0x86, 0xd1, 0x7a, 0x05, 0x45, - 0xf9, 0x25, 0xf9, 0x42, 0xfa, 0x68, 0xda, 0xf5, 0xa0, 0xda, 0xf5, 0x20, 0xda, 0xf5, 0x60, 0xda, - 0xf5, 0xa0, 0xda, 0xa4, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x7a, 0xf5, 0x41, 0x2c, 0x88, 0x31, - 0x52, 0x1e, 0xc4, 0xba, 0xa2, 0x20, 0xb1, 0x28, 0x31, 0x37, 0xb5, 0x04, 0x24, 0x96, 0x52, 0x9a, - 0x9b, 0x5b, 0x89, 0x10, 0x80, 0x9a, 0x64, 0x43, 0xac, 0x49, 0xb9, 0x89, 0x05, 0x05, 0x89, 0x49, - 0x39, 0xa9, 0x10, 0x09, 0x88, 0x6e, 0xa5, 0x7b, 0xcc, 0x5c, 0xec, 0xee, 0x10, 0x97, 0x0a, 0xe5, - 0x73, 0x09, 0xa7, 0xa4, 0xa6, 0x25, 0x96, 0xe6, 0x94, 0xf8, 0x42, 0x95, 0xfa, 0x64, 0x16, 0x97, - 0x48, 0x30, 0x2a, 0x30, 0x6b, 0x70, 0x1b, 0x99, 0xeb, 0x11, 0xeb, 0x71, 0x98, 0x3d, 0x7a, 0xfe, - 0x20, 0x09, 0x27, 0x96, 0x13, 0xf7, 0xe4, 0x19, 0x82, 0xb0, 0x99, 0x2c, 0xd4, 0xc4, 0xc8, 0x25, - 0x02, 0x15, 0x0f, 0x80, 0xf9, 0x0a, 0x6c, 0x25, 0x13, 0xd8, 0x4a, 0x0f, 0xa2, 0xad, 0x44, 0x04, - 0x92, 0x1e, 0x38, 0x90, 0xf4, 0x5c, 0x40, 0x24, 0xdc, 0x4c, 0xa8, 0x1b, 0xb0, 0xda, 0x25, 0x94, - 0xc8, 0xc5, 0x83, 0xe2, 0x5d, 0x66, 0x6a, 0x78, 0x17, 0xc5, 0x48, 0xa1, 0x12, 0x2e, 0x5e, 0x54, - 0xff, 0xb1, 0xd0, 0xc4, 0x7f, 0xa8, 0x96, 0x58, 0xb1, 0x74, 0x2c, 0x90, 0x67, 0x70, 0x4a, 0x3a, - 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, - 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0x8f, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, - 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0xe4, 0x44, 0xed, 0x9f, 0x97, 0x8a, 0xcc, 0x0d, 0x76, 0xf1, 0x26, - 0x94, 0x43, 0x92, 0xd8, 0xc0, 0x69, 0xc9, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x40, 0xc2, 0x35, - 0x4e, 0x5b, 0x03, 0x00, 0x00, -} - -func (m *Genesis) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Genesis) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Genesis) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ParameterList) > 0 { - for iNdEx := len(m.ParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.MappableList) > 0 { - for iNdEx := len(m.MappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.DefaultParameterList) > 0 { - for iNdEx := len(m.DefaultParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.DefaultMappableList) > 0 { - for iNdEx := len(m.DefaultMappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultMappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Genesis) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.DefaultMappableList) > 0 { - for _, e := range m.DefaultMappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.DefaultParameterList) > 0 { - for _, e := range m.DefaultParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.MappableList) > 0 { - for _, e := range m.MappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ParameterList) > 0 { - for _, e := range m.ParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Genesis) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Genesis: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Genesis: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultMappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultMappableList = append(m.DefaultMappableList, mappable.Order{}) - if err := m.DefaultMappableList[len(m.DefaultMappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultParameterList = append(m.DefaultParameterList, dummy.DummyParameter{}) - if err := m.DefaultParameterList[len(m.DefaultParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MappableList = append(m.MappableList, mappable.Order{}) - if err := m.MappableList[len(m.MappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ParameterList = append(m.ParameterList, dummy.DummyParameter{}) - if err := m.ParameterList[len(m.ParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/orders/internal/genesis/prototype.go b/modules/orders/internal/genesis/prototype.go index c90b3ee62..5049de3aa 100644 --- a/modules/orders/internal/genesis/prototype.go +++ b/modules/orders/internal/genesis/prototype.go @@ -1,16 +1,16 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package genesis import ( - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" ) func Prototype() helpers.Genesis { - return NewGenesis([]mappable.Order{}, []dummy.DummyParameter{}) + return baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{}, parameters.Prototype().GetList()) } diff --git a/modules/orders/internal/genesis/prototype_test.go b/modules/orders/internal/genesis/prototype_test.go new file mode 100644 index 000000000..9357bf4b3 --- /dev/null +++ b/modules/orders/internal/genesis/prototype_test.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package genesis + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Panics(t, func() { + require.Equal(t, Prototype(), baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{}, parameters.Prototype().GetList())) + }) +} diff --git a/modules/orders/internal/key/key.go b/modules/orders/internal/key/key.go new file mode 100644 index 000000000..807624891 --- /dev/null +++ b/modules/orders/internal/key/key.go @@ -0,0 +1,55 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package key + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +type key struct { + ids.OrderID +} + +var _ helpers.Key = (*key)(nil) + +func (key key) GenerateStoreKeyBytes() []byte { + return module.StoreKeyPrefix.GenerateStoreKey(key.Bytes()) +} +func (key) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, key{}) +} +func (key key) IsPartial() bool { + return len(key.OrderID.Bytes()) == 0 +} +func (key key) Equals(compareKey helpers.Key) bool { + if compareKey, err := keyFromInterface(compareKey); err != nil { + return false + } else { + return key.OrderID.Compare(compareKey.OrderID) == 0 + } +} +func keyFromInterface(i interface{}) (key, error) { + switch value := i.(type) { + case key: + return value, nil + default: + return key{}, constants.MetaDataError + } +} + +func NewKey(orderID ids.OrderID) helpers.Key { + return key{ + OrderID: orderID, + } +} + +func Prototype() helpers.Key { + return key{} +} diff --git a/modules/orders/internal/key/key_test.go b/modules/orders/internal/key/key_test.go index fb37d64f9..4d385e6b3 100644 --- a/modules/orders/internal/key/key_test.go +++ b/modules/orders/internal/key/key_test.go @@ -4,6 +4,11 @@ package key import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/AssetMantle/modules/modules/orders/internal/module" baseData "github.com/AssetMantle/modules/schema/data/base" "github.com/AssetMantle/modules/schema/helpers" @@ -12,9 +17,6 @@ import ( baseLists "github.com/AssetMantle/modules/schema/lists/base" baseProperties "github.com/AssetMantle/modules/schema/properties/base" baseQualified "github.com/AssetMantle/modules/schema/qualified/base" - "github.com/cosmos/cosmos-sdk/codec" - "reflect" - "testing" ) var ( diff --git a/modules/orders/internal/key/orderID.go b/modules/orders/internal/key/orderID.go deleted file mode 100644 index 398db314d..000000000 --- a/modules/orders/internal/key/orderID.go +++ /dev/null @@ -1,128 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - "bytes" - "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseTraits "github.com/persistenceOne/persistenceSDK/schema/traits/qualified" - "github.com/persistenceOne/persistenceSDK/schema/types" - baseTypes "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "strconv" - "strings" -) - -var _ types.ID = (*OrderID)(nil) -var _ helpers.Key = (*OrderID)(nil) - -func (orderID OrderID) GetStructReference() codec.ProtoMarshaler { - return &orderID -} -func (orderID OrderID) Bytes() []byte { - var Bytes []byte - - rateIDBytes, err := orderID.getRateIDBytes() - if err != nil { - return Bytes - } - - creationIDBytes, err := orderID.getCreationHeightBytes() - if err != nil { - return Bytes - } - - Bytes = append(Bytes, orderID.ClassificationID.Bytes()...) - Bytes = append(Bytes, orderID.MakerOwnableID.Bytes()...) - Bytes = append(Bytes, orderID.TakerOwnableID.Bytes()...) - Bytes = append(Bytes, rateIDBytes...) - Bytes = append(Bytes, creationIDBytes...) - Bytes = append(Bytes, orderID.MakerID.Bytes()...) - Bytes = append(Bytes, orderID.HashID.Bytes()...) - - return Bytes -} -func (orderID OrderID) String() string { - var values []string - values = append(values, orderID.ClassificationID.String()) - values = append(values, orderID.MakerOwnableID.String()) - values = append(values, orderID.TakerOwnableID.String()) - values = append(values, orderID.RateID.String()) - values = append(values, orderID.CreationID.String()) - values = append(values, orderID.MakerID.String()) - values = append(values, orderID.HashID.String()) - - return strings.Join(values, constants.SecondOrderCompositeIDSeparator) -} -func (orderID OrderID) Compare(id types.ID) int { - return bytes.Compare(orderID.Bytes(), id.Bytes()) -} -func (orderID OrderID) GenerateStoreKeyBytes() []byte { - return module.StoreKeyPrefix.GenerateStoreKey(orderID.Bytes()) -} -func (OrderID) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, OrderID{}) -} -func (orderID OrderID) IsPartial() bool { - return len(orderID.HashID.Bytes()) == 0 -} -func (orderID OrderID) Equals(key helpers.Key) bool { - id := orderIDFromInterface(key) - return orderID.Compare(&id) == 0 -} - -func (orderID OrderID) getRateIDBytes() ([]byte, error) { - var Bytes []byte - - if orderID.RateID.String() == "" { - return Bytes, nil - } - - exchangeRate, err := sdkTypes.NewDecFromStr(orderID.RateID.String()) - if err != nil { - return Bytes, err - } - - Bytes = append(Bytes, uint8(len(strings.Split(exchangeRate.String(), ".")[0]))) - Bytes = append(Bytes, []byte(exchangeRate.String())...) - - return Bytes, err -} - -func (orderID OrderID) getCreationHeightBytes() ([]byte, error) { - var Bytes []byte - - if orderID.CreationID.String() == "" { - return Bytes, nil - } - - height, err := strconv.ParseInt(orderID.CreationID.String(), 10, 64) - if err != nil { - return Bytes, err - } - - Bytes = append(Bytes, uint8(len(orderID.CreationID.String()))) - Bytes = append(Bytes, []byte(strconv.FormatInt(height, 10))...) - - return Bytes, err -} - -func NewOrderID(classificationID types.ID, makerOwnableID types.ID, takerOwnableID types.ID, rateID types.ID, creationID types.ID, makerID types.ID, immutableProperties types.Properties) types.ID { - return &OrderID{ - ClassificationID: classificationID, - MakerOwnableID: makerOwnableID, - TakerOwnableID: takerOwnableID, - RateID: rateID, - CreationID: creationID, - MakerID: makerID, - HashID: baseTraits.HasImmutables{Properties: *baseTypes.NewProperties(immutableProperties.GetList()...)}.GenerateHashID(), - } -} diff --git a/modules/orders/internal/key/orderID.pb.go b/modules/orders/internal/key/orderID.pb.go deleted file mode 100644 index f4b20d91b..000000000 --- a/modules/orders/internal/key/orderID.pb.go +++ /dev/null @@ -1,607 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/key/orderID.proto - -package key - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - github_com_persistenceOne_persistenceSDK_schema_types "github.com/persistenceOne/persistenceSDK/schema/types" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type OrderID struct { - ClassificationID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,1,opt,name=classification_i_d,json=classificationID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"classification_i_d"` - MakerOwnableID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,2,opt,name=maker_ownable_i_d,json=makerOwnableID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"maker_ownable_i_d"` - TakerOwnableID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,3,opt,name=taker_ownable_i_d,json=takerOwnableID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"taker_ownable_i_d"` - RateID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,4,opt,name=rate_i_d,json=rateID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"rate_i_d"` - CreationID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,5,opt,name=creation_i_d,json=creationID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"creation_i_d"` - MakerID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,6,opt,name=maker_i_d,json=makerID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"maker_i_d"` - HashID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,7,opt,name=hash_i_d,json=hashID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"hash_i_d"` -} - -func (m *OrderID) Reset() { *m = OrderID{} } -func (*OrderID) ProtoMessage() {} -func (*OrderID) Descriptor() ([]byte, []int) { - return fileDescriptor_db3a535cdb38bb7b, []int{0} -} -func (m *OrderID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *OrderID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_OrderID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *OrderID) XXX_Merge(src proto.Message) { - xxx_messageInfo_OrderID.Merge(m, src) -} -func (m *OrderID) XXX_Size() int { - return m.Size() -} -func (m *OrderID) XXX_DiscardUnknown() { - xxx_messageInfo_OrderID.DiscardUnknown(m) -} - -var xxx_messageInfo_OrderID proto.InternalMessageInfo - -func init() { - proto.RegisterType((*OrderID)(nil), "persistence_sdk.modules.orders.internal.key.OrderID") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/orders/internal/key/orderID.proto", fileDescriptor_db3a535cdb38bb7b) -} - -var fileDescriptor_db3a535cdb38bb7b = []byte{ - // 348 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x93, 0x3f, 0x4b, 0xf3, 0x40, - 0x18, 0xc0, 0x93, 0xf7, 0xed, 0x9f, 0xb7, 0xc7, 0x8b, 0x68, 0x70, 0x10, 0x87, 0x54, 0x9c, 0x04, - 0xe1, 0x6e, 0x70, 0x51, 0x27, 0x29, 0xb7, 0x04, 0x87, 0x82, 0x6e, 0x45, 0x0c, 0x97, 0xe4, 0xb1, - 0x39, 0x92, 0xdc, 0x95, 0xbb, 0x2b, 0xd2, 0x6f, 0xe1, 0xe8, 0xe8, 0xc7, 0xe9, 0x58, 0x70, 0x11, - 0x87, 0x22, 0xed, 0x17, 0x91, 0xe4, 0x2c, 0xb6, 0x0a, 0xe2, 0x90, 0x2d, 0x39, 0xf8, 0xfd, 0x7e, - 0xf0, 0x3c, 0x3c, 0xe8, 0x6c, 0x04, 0x4a, 0x73, 0x6d, 0x40, 0xc4, 0x10, 0xea, 0x24, 0x23, 0x85, - 0x4c, 0xc6, 0x39, 0x68, 0x22, 0x55, 0x02, 0x4a, 0x13, 0x2e, 0x0c, 0x28, 0xc1, 0x72, 0x92, 0xc1, - 0xc4, 0xbe, 0x05, 0x14, 0x8f, 0x94, 0x34, 0xd2, 0x3b, 0xfe, 0x82, 0xe2, 0x0f, 0x14, 0x5b, 0x14, - 0xaf, 0x50, 0x9c, 0xc1, 0x64, 0x7f, 0x77, 0x28, 0x87, 0xb2, 0xe2, 0x48, 0xf9, 0x65, 0x15, 0x87, - 0xcf, 0x4d, 0xd4, 0xee, 0x5b, 0xa9, 0x27, 0x90, 0x17, 0xe7, 0x4c, 0x6b, 0x7e, 0xc7, 0x63, 0x66, - 0xb8, 0x14, 0x21, 0x0f, 0x93, 0x3d, 0xf7, 0xc0, 0x3d, 0xea, 0xf4, 0x2e, 0xa6, 0xf3, 0xae, 0xf3, - 0x3a, 0xef, 0x9e, 0x0e, 0xb9, 0x49, 0xc7, 0x11, 0x8e, 0x65, 0x41, 0xd6, 0xea, 0x7d, 0x01, 0xeb, - 0xbf, 0xd7, 0xf4, 0x92, 0xe8, 0x38, 0x85, 0x82, 0x11, 0x33, 0x19, 0x81, 0xc6, 0x01, 0xbd, 0xda, - 0xde, 0x74, 0x07, 0xd4, 0xcb, 0xd0, 0x4e, 0xc1, 0x32, 0x50, 0xa1, 0xbc, 0x17, 0x2c, 0xca, 0xa1, - 0xca, 0xfd, 0xa9, 0x29, 0xb7, 0x55, 0xa9, 0xfb, 0xd6, 0x6c, 0x63, 0xe6, 0x5b, 0xec, 0x6f, 0x5d, - 0x31, 0xb3, 0x19, 0x1b, 0xa0, 0x7f, 0x8a, 0x19, 0xdb, 0x68, 0xd4, 0xd4, 0x68, 0x95, 0xc6, 0x80, - 0x7a, 0x11, 0xfa, 0x1f, 0x2b, 0xf8, 0xdc, 0x4f, 0xb3, 0x26, 0x3f, 0x5a, 0x59, 0x03, 0xea, 0xdd, - 0xa0, 0x8e, 0xdd, 0x4c, 0x19, 0x68, 0xd5, 0x14, 0x68, 0x57, 0x4a, 0x3b, 0x9d, 0x94, 0xe9, 0xb4, - 0x92, 0xb7, 0xeb, 0x9a, 0x4e, 0x69, 0x0c, 0xe8, 0x79, 0xe3, 0xf1, 0xa9, 0xeb, 0xf4, 0x6e, 0xa7, - 0x0b, 0xdf, 0x9d, 0x2d, 0x7c, 0xf7, 0x6d, 0xe1, 0xbb, 0x0f, 0x4b, 0xdf, 0x99, 0x2d, 0x7d, 0xe7, - 0x65, 0xe9, 0x3b, 0x03, 0xfa, 0xeb, 0xc2, 0x0f, 0x67, 0x18, 0xb5, 0xaa, 0xe3, 0x39, 0x79, 0x0f, - 0x00, 0x00, 0xff, 0xff, 0xe7, 0xe6, 0x46, 0x64, 0xbc, 0x03, 0x00, 0x00, -} - -func (m *OrderID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *OrderID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *OrderID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.HashID.Size() - i -= size - if _, err := m.HashID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintOrderID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size := m.MakerID.Size() - i -= size - if _, err := m.MakerID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintOrderID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.CreationID.Size() - i -= size - if _, err := m.CreationID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintOrderID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.RateID.Size() - i -= size - if _, err := m.RateID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintOrderID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.TakerOwnableID.Size() - i -= size - if _, err := m.TakerOwnableID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintOrderID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size := m.MakerOwnableID.Size() - i -= size - if _, err := m.MakerOwnableID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintOrderID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.ClassificationID.Size() - i -= size - if _, err := m.ClassificationID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintOrderID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintOrderID(dAtA []byte, offset int, v uint64) int { - offset -= sovOrderID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *OrderID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ClassificationID.Size() - n += 1 + l + sovOrderID(uint64(l)) - l = m.MakerOwnableID.Size() - n += 1 + l + sovOrderID(uint64(l)) - l = m.TakerOwnableID.Size() - n += 1 + l + sovOrderID(uint64(l)) - l = m.RateID.Size() - n += 1 + l + sovOrderID(uint64(l)) - l = m.CreationID.Size() - n += 1 + l + sovOrderID(uint64(l)) - l = m.MakerID.Size() - n += 1 + l + sovOrderID(uint64(l)) - l = m.HashID.Size() - n += 1 + l + sovOrderID(uint64(l)) - return n -} - -func sovOrderID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozOrderID(x uint64) (n int) { - return sovOrderID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *OrderID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrderID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: OrderID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: OrderID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrderID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOrderID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthOrderID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MakerOwnableID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrderID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOrderID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthOrderID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MakerOwnableID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TakerOwnableID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrderID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOrderID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthOrderID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TakerOwnableID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RateID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrderID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOrderID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthOrderID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.RateID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CreationID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrderID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOrderID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthOrderID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CreationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MakerID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrderID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOrderID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthOrderID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MakerID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HashID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrderID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthOrderID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthOrderID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HashID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipOrderID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthOrderID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipOrderID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOrderID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOrderID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOrderID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthOrderID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupOrderID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthOrderID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthOrderID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowOrderID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupOrderID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/orders/internal/key/orderID_test.go b/modules/orders/internal/key/orderID_test.go deleted file mode 100644 index 2d7c03253..000000000 --- a/modules/orders/internal/key/orderID_test.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants" - baseTraits "github.com/persistenceOne/persistenceSDK/schema/traits/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" - "strings" - "testing" -) - -func Test_OrderID_Methods(t *testing.T) { - - classificationID := base.NewID("classificationID") - makerOwnableID := base.NewID("makerOwnableID") - takerOwnableID := base.NewID("takerOwnableID") - makerID := base.NewID("makerID") - defaultImmutableProperties := base.NewProperties(base.NewProperty(base.NewID("ID1"), base.NewFact(base.NewStringData("ImmutableData")))) - rateID := base.NewID(sdkTypes.OneDec().String()) - creationID := base.NewID("100") - immutableProperties := base.NewProperties(base.NewProperty(base.NewID("ID1"), base.NewFact(base.NewStringData("ImmutableData")))) - - testOrderID := NewOrderID(classificationID, makerOwnableID, takerOwnableID, rateID, creationID, makerID, immutableProperties).(orderID) - testOrderID2 := NewOrderID(classificationID, makerOwnableID, takerOwnableID, base.NewID(sdkTypes.MustNewDecFromStr("2.3").String()), base.NewID("creation"), makerID, base.NewProperties()).(orderID) - require.Equal(t, testOrderID, orderID{ClassificationID: classificationID, MakerOwnableID: makerOwnableID, TakerOwnableID: takerOwnableID, RateID: rateID, CreationID: creationID, MakerID: makerID, HashID: baseTraits.HasImmutables{Properties: immutableProperties}.GenerateHashID()}) - require.Equal(t, true, testOrderID.Equals(testOrderID)) - require.Equal(t, false, testOrderID.Compare(base.NewID("")) == 0) - require.Equal(t, strings.Join([]string{classificationID.String(), makerOwnableID.String(), takerOwnableID.String(), rateID.String(), creationID.String(), makerID.String(), baseTraits.HasImmutables{Properties: defaultImmutableProperties}.GenerateHashID().String()}, constants.SecondOrderCompositeIDSeparator), testOrderID.String()) - require.Equal(t, false, testOrderID.IsPartial()) - require.Equal(t, true, testOrderID.Equals(testOrderID)) - require.Equal(t, false, testOrderID.Equals(testOrderID2)) - require.Equal(t, false, testOrderID.Equals(FromID(base.NewID("")))) - require.Equal(t, testOrderID, FromID(testOrderID)) - require.Equal(t, orderID{ClassificationID: base.NewID(""), MakerOwnableID: base.NewID(""), TakerOwnableID: base.NewID(""), RateID: base.NewID(""), CreationID: base.NewID(""), MakerID: base.NewID(""), HashID: base.NewID("")}, FromID(base.NewID(""))) - require.Equal(t, testOrderID, FromID(base.NewID(classificationID.String()+constants.SecondOrderCompositeIDSeparator+makerOwnableID.String()+constants.SecondOrderCompositeIDSeparator+takerOwnableID.String()+constants.SecondOrderCompositeIDSeparator+rateID.String()+constants.SecondOrderCompositeIDSeparator+creationID.String()+constants.SecondOrderCompositeIDSeparator+makerID.String()+constants.SecondOrderCompositeIDSeparator+baseTraits.HasImmutables{Properties: defaultImmutableProperties}.GenerateHashID().String()))) - require.Equal(t, classificationID, ReadClassificationID(testOrderID)) - require.Equal(t, makerOwnableID, ReadMakerOwnableID(testOrderID)) - require.Equal(t, takerOwnableID, ReadTakerOwnableID(testOrderID)) - require.Equal(t, rateID, ReadRateID(testOrderID)) - require.Equal(t, creationID, ReadCreationID(testOrderID)) - require.Equal(t, makerID, ReadMakerID(testOrderID)) - require.Equal(t, true, FromID(base.NewID("")).IsPartial()) - -} diff --git a/modules/orders/internal/key/utilities.go b/modules/orders/internal/key/utilities.go deleted file mode 100644 index 8906a2196..000000000 --- a/modules/orders/internal/key/utilities.go +++ /dev/null @@ -1,82 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "strconv" - "strings" -) - -func readOrderID(orderIDString string) OrderID { - idList := strings.Split(orderIDString, constants.SecondOrderCompositeIDSeparator) - - if len(idList) == 7 { - exchangeRate, Error := sdkTypes.NewDecFromStr(idList[3]) - if Error != nil { - return OrderID{ClassificationID: base.NewID(""), MakerOwnableID: base.NewID(""), TakerOwnableID: base.NewID(""), RateID: base.NewID(""), CreationID: base.NewID(""), MakerID: base.NewID(""), HashID: base.NewID("")} - } - - height, Error := strconv.ParseInt(idList[4], 10, 64) - if Error != nil { - return OrderID{ClassificationID: base.NewID(""), MakerOwnableID: base.NewID(""), TakerOwnableID: base.NewID(""), RateID: base.NewID(""), CreationID: base.NewID(""), MakerID: base.NewID(""), HashID: base.NewID("")} - } - - return OrderID{ - ClassificationID: base.NewID(idList[0]), - MakerOwnableID: base.NewID(idList[1]), - TakerOwnableID: base.NewID(idList[2]), - RateID: base.NewID(exchangeRate.String()), - CreationID: base.NewID(strconv.FormatInt(height, 10)), - MakerID: base.NewID(idList[5]), - HashID: base.NewID(idList[6]), - } - } - - return OrderID{ClassificationID: base.NewID(""), MakerOwnableID: base.NewID(""), TakerOwnableID: base.NewID(""), RateID: base.NewID(""), CreationID: base.NewID(""), MakerID: base.NewID(""), HashID: base.NewID("")} -} -func orderIDFromInterface(i interface{}) OrderID { - switch value := i.(type) { - case OrderID: - return value - case types.ID: - return orderIDFromInterface(readOrderID(value.String())) - default: - panic(i) - } -} - -func ReadClassificationID(orderID types.ID) types.ID { - return orderIDFromInterface(orderID).ClassificationID -} - -func ReadRateID(orderID types.ID) types.ID { - return orderIDFromInterface(orderID).RateID -} - -func ReadCreationID(orderID types.ID) types.ID { - return orderIDFromInterface(orderID).CreationID -} - -func ReadMakerOwnableID(orderID types.ID) types.ID { - return orderIDFromInterface(orderID).MakerOwnableID -} - -func ReadTakerOwnableID(orderID types.ID) types.ID { - return orderIDFromInterface(orderID).TakerOwnableID -} - -func ReadMakerID(orderID types.ID) types.ID { - return orderIDFromInterface(orderID).MakerID -} - -func FromID(id types.ID) helpers.Key { - return orderIDFromInterface(id) -} diff --git a/modules/orders/internal/mappable/mappable.go b/modules/orders/internal/mappable/mappable.go new file mode 100644 index 000000000..4b2bc0645 --- /dev/null +++ b/modules/orders/internal/mappable/mappable.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mappable + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +type mappable struct { + documents.Order +} + +var _ helpers.Mappable = (*mappable)(nil) + +func (mappable mappable) GetKey() helpers.Key { + return key.NewKey(baseIDs.NewOrderID(mappable.GetClassificationID(), mappable.GetImmutables())) +} +func (mappable) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, mappable{}) +} + +func NewMappable(order documents.Order) helpers.Mappable { + return mappable{Order: order} +} + +func Prototype() helpers.Mappable { + return mappable{} +} diff --git a/modules/orders/internal/mappable/mappable_test.go b/modules/orders/internal/mappable/mappable_test.go index 94236d2bd..8bf559076 100644 --- a/modules/orders/internal/mappable/mappable_test.go +++ b/modules/orders/internal/mappable/mappable_test.go @@ -4,6 +4,12 @@ package mappable import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/stretchr/testify/require" + "github.com/AssetMantle/modules/modules/orders/internal/key" baseData "github.com/AssetMantle/modules/schema/data/base" "github.com/AssetMantle/modules/schema/documents" @@ -13,10 +19,6 @@ import ( baseLists "github.com/AssetMantle/modules/schema/lists/base" baseProperties "github.com/AssetMantle/modules/schema/properties/base" baseQualified "github.com/AssetMantle/modules/schema/qualified/base" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/stretchr/testify/require" - "reflect" - "testing" ) var ( @@ -24,7 +26,7 @@ var ( mutables = baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) classificationID = baseIds.NewClassificationID(immutables, mutables) testOrder = baseDocuments.NewOrder(classificationID, immutables, mutables) - //testIdentity = baseDocuments.NewIdentity(classificationID, immutables, mutables) + // testIdentity = baseDocuments.NewIdentity(classificationID, immutables, mutables) ) func TestNewMappable(t *testing.T) { diff --git a/modules/orders/internal/mappable/order.go b/modules/orders/internal/mappable/order.go deleted file mode 100644 index 2fe8e7b62..000000000 --- a/modules/orders/internal/mappable/order.go +++ /dev/null @@ -1,124 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import ( - "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/mappables" - "github.com/persistenceOne/persistenceSDK/schema/traits" - baseTraits "github.com/persistenceOne/persistenceSDK/schema/traits/base" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - baseTypes "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "strconv" -) - -var _ mappables.Order = (*Order)(nil) - -func (order Order) GetStructReference() codec.ProtoMarshaler { - return &order -} -func (order Order) GetID() types.ID { - return &order.ID -} -func (order Order) GetClassificationID() types.ID { - return key.ReadClassificationID(&order.ID) -} -func (order Order) GetImmutableProperties() types.Properties { - return order.HasImmutables.GetImmutableProperties() -} - -func (order Order) GenerateHashID() types.ID { - return order.HasImmutables.GenerateHashID() -} - -func (order Order) GetMutableProperties() types.Properties { - return order.HasMutables.GetMutableProperties() -} - -func (order Order) Mutate(propertyList ...types.Property) traits.HasMutables { - return order.HasMutables.Mutate(propertyList...) -} -func (order Order) GetRateID() types.ID { - return key.ReadRateID(&order.ID) -} -func (order Order) GetCreationID() types.ID { - return key.ReadCreationID(&order.ID) -} -func (order Order) GetMakerOwnableID() types.ID { - return key.ReadMakerOwnableID(&order.ID) -} -func (order Order) GetTakerOwnableID() types.ID { - return key.ReadTakerOwnableID(&order.ID) -} -func (order Order) GetMakerID() types.ID { - return key.ReadMakerID(&order.ID) -} -func (order Order) GetCreation() types.MetaProperty { - heightValue, Error := strconv.ParseInt(key.ReadCreationID(&order.ID).String(), 10, 64) - if Error != nil { - return base.NewMetaProperty(base.NewID(properties.Creation), base.NewMetaFact(base.NewHeightData(base.NewHeight(0)))) - } - - return base.NewMetaProperty(base.NewID(properties.Creation), base.NewMetaFact(base.NewHeightData(base.NewHeight(heightValue)))) -} -func (order Order) GetExchangeRate() types.MetaProperty { - decValue, Error := sdkTypes.NewDecFromStr(key.ReadRateID(&order.ID).String()) - if Error != nil { - return base.NewMetaProperty(base.NewID(properties.ExchangeRate), base.NewMetaFact(base.NewDecData(sdkTypes.ZeroDec()))) - } - - return base.NewMetaProperty(base.NewID(properties.ExchangeRate), base.NewMetaFact(base.NewDecData(decValue))) -} -func (order Order) GetTakerID() types.Property { - if takerID := order.HasImmutables.GetImmutableProperties().Get(base.NewID(properties.TakerID)); takerID != nil { - return takerID - } else if takerID := order.HasMutables.GetMutableProperties().Get(base.NewID(properties.TakerID)); takerID != nil { - return takerID - } else { - data, _ := base.ReadIDData("") - return base.NewProperty(base.NewID(properties.TakerID), base.NewFact(data)) - } -} -func (order Order) GetExpiry() types.Property { - if property := order.HasImmutables.GetImmutableProperties().Get(base.NewID(properties.Expiry)); property != nil { - return property - } else if property := order.HasMutables.GetMutableProperties().Get(base.NewID(properties.Expiry)); property != nil { - return property - } else { - return base.NewProperty(base.NewID(properties.Expiry), base.NewFact(base.NewHeightData(base.NewHeight(-1)))) - } -} -func (order Order) GetMakerOwnableSplit() types.Property { - if split := order.HasImmutables.GetImmutableProperties().Get(base.NewID(properties.MakerOwnableSplit)); split != nil { - return split - } else if split := order.HasMutables.GetMutableProperties().Get(base.NewID(properties.MakerOwnableSplit)); split != nil { - return split - } else { - data, _ := base.ReadDecData("") - return base.NewProperty(base.NewID(properties.MakerOwnableSplit), base.NewFact(data)) - } -} -func (order Order) GetKey() helpers.Key { - return key.FromID(&order.ID) -} -func (Order) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Order{}) -} - -func NewOrder(orderID types.ID, immutableProperties types.Properties, mutableProperties types.Properties) mappables.Order { - return &Order{ - ID: *base.NewID(orderID.String()), - HasImmutables: baseTraits.HasImmutables{Properties: *baseTypes.NewProperties(immutableProperties.GetList()...)}, - HasMutables: baseTraits.HasMutables{Properties: *baseTypes.NewProperties(mutableProperties.GetList()...)}, - } -} diff --git a/modules/orders/internal/mappable/order.pb.go b/modules/orders/internal/mappable/order.pb.go deleted file mode 100644 index fac2c7e13..000000000 --- a/modules/orders/internal/mappable/order.pb.go +++ /dev/null @@ -1,417 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/mappable/order.proto - -package mappable - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base1 "github.com/persistenceOne/persistenceSDK/schema/traits/base" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Order struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - HasImmutables base1.HasImmutables `protobuf:"bytes,2,opt,name=has_immutables,json=hasImmutables,proto3" json:"has_immutables"` - HasMutables base1.HasMutables `protobuf:"bytes,3,opt,name=has_mutables,json=hasMutables,proto3" json:"has_mutables"` -} - -func (m *Order) Reset() { *m = Order{} } -func (m *Order) String() string { return proto.CompactTextString(m) } -func (*Order) ProtoMessage() {} -func (*Order) Descriptor() ([]byte, []int) { - return fileDescriptor_619aa3db73f03a59, []int{0} -} -func (m *Order) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Order) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Order.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Order) XXX_Merge(src proto.Message) { - xxx_messageInfo_Order.Merge(m, src) -} -func (m *Order) XXX_Size() int { - return m.Size() -} -func (m *Order) XXX_DiscardUnknown() { - xxx_messageInfo_Order.DiscardUnknown(m) -} - -var xxx_messageInfo_Order proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Order)(nil), "persistence_sdk.modules.orders.internal.mappable.Order") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/orders/internal/mappable/order.proto", fileDescriptor_619aa3db73f03a59) -} - -var fileDescriptor_619aa3db73f03a59 = []byte{ - // 333 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x29, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x2f, 0x4a, 0x49, 0x2d, 0x2a, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, - 0xca, 0x4b, 0xcc, 0xd1, 0xcf, 0x4d, 0x2c, 0x28, 0x48, 0x4c, 0xca, 0x49, 0x85, 0x48, 0xe8, 0x15, - 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0x19, 0xa0, 0xe9, 0xd6, 0x83, 0xea, 0xd6, 0x83, 0xe8, 0xd6, 0x83, - 0xe9, 0xd6, 0x83, 0xe9, 0x96, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x6b, 0xd6, 0x07, 0xb1, 0x20, - 0xe6, 0x48, 0x99, 0xa1, 0xbb, 0xa2, 0x38, 0x39, 0x23, 0x35, 0x37, 0x51, 0xbf, 0xa4, 0x28, 0x31, - 0xb3, 0xa4, 0x58, 0x3f, 0x29, 0xb1, 0x38, 0x55, 0x3f, 0x23, 0xb1, 0xd8, 0x33, 0x37, 0xb7, 0xb4, - 0x04, 0x64, 0x4c, 0x31, 0x54, 0x9f, 0x09, 0x71, 0xfa, 0x7c, 0x51, 0x75, 0x69, 0xe1, 0xd2, 0x55, - 0x59, 0x90, 0x0a, 0xd5, 0x94, 0x99, 0x02, 0x51, 0xab, 0xd4, 0xca, 0xc4, 0xc5, 0xea, 0x0f, 0xf2, - 0x8c, 0x90, 0x0d, 0x17, 0x73, 0x66, 0x7c, 0x8a, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0xaa, - 0x1e, 0xba, 0xcf, 0x21, 0x66, 0xe8, 0x81, 0xcd, 0xd0, 0x03, 0x99, 0xa1, 0xe7, 0xe9, 0xe2, 0xc4, - 0x72, 0xe2, 0x9e, 0x3c, 0x43, 0x10, 0x53, 0xa6, 0x8b, 0x50, 0x1c, 0x17, 0x5f, 0x46, 0x62, 0x71, - 0x7c, 0x26, 0xdc, 0x07, 0x12, 0x4c, 0x60, 0x83, 0x0c, 0x71, 0x1a, 0x04, 0xf6, 0x02, 0xc4, 0x24, - 0x0f, 0x64, 0xaf, 0x43, 0x0d, 0xe5, 0x45, 0x09, 0x0f, 0xa1, 0x08, 0x2e, 0x1e, 0x90, 0xf9, 0x70, - 0xd3, 0x99, 0xc1, 0xa6, 0xeb, 0x13, 0x69, 0xba, 0x2f, 0xaa, 0xd9, 0xdc, 0x48, 0x61, 0x66, 0xc5, - 0xd2, 0xb1, 0x40, 0x9e, 0xc1, 0x29, 0xf9, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, - 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, - 0xa2, 0x3c, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x91, 0x6c, 0xf3, - 0xcf, 0x4b, 0x45, 0xe6, 0x06, 0xbb, 0x78, 0x13, 0x4c, 0x5a, 0x49, 0x6c, 0xe0, 0x30, 0x37, 0x06, - 0x04, 0x00, 0x00, 0xff, 0xff, 0x57, 0xcb, 0xd3, 0xc9, 0x95, 0x02, 0x00, 0x00, -} - -func (m *Order) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Order) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Order) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.HasMutables.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintOrder(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.HasImmutables.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintOrder(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintOrder(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintOrder(dAtA []byte, offset int, v uint64) int { - offset -= sovOrder(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Order) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovOrder(uint64(l)) - l = m.HasImmutables.Size() - n += 1 + l + sovOrder(uint64(l)) - l = m.HasMutables.Size() - n += 1 + l + sovOrder(uint64(l)) - return n -} - -func sovOrder(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozOrder(x uint64) (n int) { - return sovOrder(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Order) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrder - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Order: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Order: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrder - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthOrder - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthOrder - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HasImmutables", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrder - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthOrder - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthOrder - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HasImmutables.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HasMutables", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrder - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthOrder - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthOrder - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HasMutables.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipOrder(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthOrder - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipOrder(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOrder - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOrder - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOrder - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthOrder - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupOrder - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthOrder - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthOrder = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowOrder = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupOrder = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/orders/internal/mappable/order_test.go b/modules/orders/internal/mappable/order_test.go deleted file mode 100644 index 40856d836..000000000 --- a/modules/orders/internal/mappable/order_test.go +++ /dev/null @@ -1,93 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - baseTraits "github.com/persistenceOne/persistenceSDK/schema/traits/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" - "testing" -) - -func Test_Order_Methods(t *testing.T) { - - classificationID := base.NewID("classificationID") - makerOwnableID := base.NewID("makerOwnableID") - takerOwnableID := base.NewID("takerOwnableID") - makerID := base.NewID("makerID") - rateID := base.NewID(sdkTypes.OneDec().String()) - creationID := base.NewID("100") - - takerIDImmutableProperty := base.NewProperty(base.NewID(properties.TakerID), base.NewFact(base.NewStringData("takerIDImmutableProperty"))) - exchangeRateImmutableProperty := base.NewMetaProperty(base.NewID(properties.ExchangeRate), base.NewMetaFact(base.NewDecData(sdkTypes.OneDec()))) - creationImmutableProperty := base.NewMetaProperty(base.NewID(properties.Creation), base.NewMetaFact(base.NewHeightData(base.NewHeight(100)))) - expiryImmutableProperty := base.NewProperty(base.NewID(properties.Expiry), base.NewFact(base.NewStringData("expiryImmutableProperty"))) - makerOwnableSplitImmutableProperty := base.NewProperty(base.NewID(properties.MakerOwnableSplit), base.NewFact(base.NewStringData("makerOwnableSplitImmutableProperty"))) - - takerIDMutableProperty := base.NewProperty(base.NewID(properties.TakerID), base.NewFact(base.NewStringData("takerIDMutableProperty"))) - exchangeRateMutableProperty := base.NewProperty(base.NewID(properties.ExchangeRate), base.NewFact(base.NewDecData(sdkTypes.OneDec()))) - creationMutableProperty := base.NewProperty(base.NewID(properties.Creation), base.NewFact(base.NewHeightData(base.NewHeight(100)))) - expiryMutableProperty := base.NewProperty(base.NewID(properties.Expiry), base.NewFact(base.NewStringData("expiryMutableProperty"))) - makerOwnableSplitMutableProperty := base.NewProperty(base.NewID(properties.MakerOwnableSplit), base.NewFact(base.NewStringData("makerOwnableSplitMutableProperty"))) - - immutableProperties := base.NewProperties(takerIDImmutableProperty, exchangeRateImmutableProperty.RemoveData(), creationImmutableProperty.RemoveData(), expiryImmutableProperty, makerOwnableSplitImmutableProperty) - mutableProperties := base.NewProperties(takerIDMutableProperty, exchangeRateMutableProperty, creationMutableProperty, expiryMutableProperty, makerOwnableSplitMutableProperty) - testOrderID := key.NewOrderID(classificationID, makerOwnableID, takerOwnableID, rateID, creationID, makerID, immutableProperties) - testOrder := NewOrder(testOrderID, immutableProperties, base.NewProperties()).(order) - testOrder2 := NewOrder(testOrderID, base.NewProperties(), mutableProperties).(order) - testOrder3 := NewOrder(testOrderID, base.NewProperties(), base.NewProperties()).(order) - - data, _ := base.ReadIDData("") - defaultTakerProperty := base.NewProperty(base.NewID(properties.TakerID), base.NewFact(data)) - defaultExchangeRateProperty := base.NewProperty(base.NewID(properties.ExchangeRate), base.NewFact(base.NewDecData(sdkTypes.OneDec()))) - data, _ = base.ReadHeightData("100") - defaultCreationProperty := base.NewProperty(base.NewID(properties.Creation), base.NewFact(data)) - data, _ = base.ReadHeightData("-1") - defaultExpiryProperty := base.NewProperty(base.NewID(properties.Expiry), base.NewFact(data)) - data, _ = base.ReadDecData("") - defaultMakerOwnableSplitProperty := base.NewProperty(base.NewID(properties.MakerOwnableSplit), base.NewFact(data)) - - require.Equal(t, order{ID: testOrderID, HasImmutables: baseTraits.HasImmutables{Properties: immutableProperties}, HasMutables: baseTraits.HasMutables{Properties: base.NewProperties()}}, testOrder) - require.Equal(t, testOrderID, testOrder.GetID()) - require.Equal(t, testOrderID, testOrder.GetKey()) - require.Equal(t, classificationID, testOrder.GetClassificationID()) - require.Equal(t, makerOwnableID, testOrder.GetMakerOwnableID()) - require.Equal(t, takerOwnableID, testOrder.GetTakerOwnableID()) - require.Equal(t, makerID, testOrder.GetMakerID()) - - //GetTakerID - require.Equal(t, takerIDImmutableProperty, testOrder.GetTakerID()) - require.Equal(t, takerIDMutableProperty, testOrder2.GetTakerID()) - require.Equal(t, defaultTakerProperty, testOrder3.GetTakerID()) - //GetExchangeRate - require.Equal(t, exchangeRateImmutableProperty, testOrder.GetExchangeRate()) - require.Equal(t, exchangeRateMutableProperty, testOrder2.GetExchangeRate().RemoveData()) - require.Equal(t, defaultExchangeRateProperty, testOrder3.GetExchangeRate().RemoveData()) - - //GetCreation - require.Equal(t, creationImmutableProperty, testOrder.GetCreation()) - require.Equal(t, creationMutableProperty, testOrder2.GetCreation().RemoveData()) - require.Equal(t, defaultCreationProperty, testOrder3.GetCreation().RemoveData()) - - //GetExpiry - require.Equal(t, expiryImmutableProperty, testOrder.GetExpiry()) - require.Equal(t, expiryMutableProperty, testOrder2.GetExpiry()) - require.Equal(t, defaultExpiryProperty, testOrder3.GetExpiry()) - - //GetMakerOwnableSplit - require.Equal(t, makerOwnableSplitImmutableProperty, testOrder.GetMakerOwnableSplit()) - require.Equal(t, makerOwnableSplitMutableProperty, testOrder2.GetMakerOwnableSplit()) - require.Equal(t, defaultMakerOwnableSplitProperty, testOrder3.GetMakerOwnableSplit()) - - require.Equal(t, immutableProperties, testOrder.GetImmutableProperties()) - require.Equal(t, mutableProperties, testOrder2.GetMutableProperties()) - require.Equal(t, testOrderID, testOrder2.GetID()) - require.Equal(t, testOrderID, testOrder2.GetKey()) - -} diff --git a/modules/orders/internal/mappable/prototype.go b/modules/orders/internal/mappable/prototype.go deleted file mode 100644 index 3849acb55..000000000 --- a/modules/orders/internal/mappable/prototype.go +++ /dev/null @@ -1,12 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import "github.com/persistenceOne/persistenceSDK/schema/helpers" - -func Prototype() helpers.Mappable { - return &Order{} -} diff --git a/modules/orders/internal/mapper/prototype.go b/modules/orders/internal/mapper/prototype.go new file mode 100644 index 000000000..799f38ec5 --- /dev/null +++ b/modules/orders/internal/mapper/prototype.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mapper + +import ( + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Mapper { + return baseHelpers.NewMapper(key.Prototype, mappable.Prototype) +} diff --git a/modules/orders/internal/module/constants.go b/modules/orders/internal/module/constants.go new file mode 100644 index 000000000..126c0401e --- /dev/null +++ b/modules/orders/internal/module/constants.go @@ -0,0 +1,23 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package module + +import ( + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + constantProperties "github.com/AssetMantle/modules/schema/properties/constants" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + qualifiedConstants "github.com/AssetMantle/modules/schema/qualified/constants" +) + +const Name = "orders" + +var StoreKeyPrefix = constants.OrdersStoreKeyPrefix + +// TODO move to common constants +var NubClassificationID = baseIDs.NewClassificationID(qualifiedConstants.NubImmutables, qualifiedConstants.NubMutables) +var ModuleIdentityID = baseIDs.NewIdentityID(NubClassificationID, baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(constantProperties.NubIDProperty.GetKey(), baseData.NewStringData(Name))))) diff --git a/modules/orders/internal/parameters/dummy/constants.go b/modules/orders/internal/parameters/dummy/constants.go new file mode 100644 index 000000000..770f437dc --- /dev/null +++ b/modules/orders/internal/parameters/dummy/constants.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package dummy + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +var ID = baseIDs.NewStringID("dummy") + +var DefaultData = baseData.NewDecData(sdkTypes.SmallestDec()) diff --git a/modules/orders/internal/parameters/dummy/parameter.go b/modules/orders/internal/parameters/dummy/parameter.go index e78fdc8d0..5ffc0eaf5 100644 --- a/modules/orders/internal/parameters/dummy/parameter.go +++ b/modules/orders/internal/parameters/dummy/parameter.go @@ -1,59 +1,10 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "encoding/json" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" ) -var _ types.Parameter = (*DummyParameter)(nil) - -func (dummyParameter DummyParameter) String() string { - bytes, Error := json.Marshal(dummyParameter) - if Error != nil { - return Error.Error() - } - return string(bytes) -} - -func (dummyParameter DummyParameter) Equal(compareParameter types.Parameter) bool { - if compareParameter == nil { - return false - } - return dummyParameter.Data.Compare(compareParameter.GetData()) == 0 -} - -func (dummyParameter DummyParameter) Validate() error { - return validator(dummyParameter) -} - -func (dummyParameter DummyParameter) GetID() types.ID { - return &dummyParameter.ID -} - -func (dummyParameter DummyParameter) GetData() types.Data { - return &dummyParameter.Data -} - -func (dummyParameter DummyParameter) GetValidator() func(interface{}) error { - return validator -} - -func (dummyParameter DummyParameter) Mutate(data types.Data) types.Parameter { - decData, _ := data.AsDec() - dummyParameter.Data = *base.NewDummyDecData(decData) - return &dummyParameter -} - -func NewParameter(id types.ID, data types.Data) *DummyParameter { - decData, _ := data.AsDec() - return &DummyParameter{ - ID: *base.NewID(id.String()), - Data: *base.NewDummyDecData(decData), - } -} +var Parameter = baseTypes.NewParameter(ID, DefaultData, validator) diff --git a/modules/orders/internal/parameters/dummy/parameter.pb.go b/modules/orders/internal/parameters/dummy/parameter.pb.go deleted file mode 100644 index c6b7f179c..000000000 --- a/modules/orders/internal/parameters/dummy/parameter.pb.go +++ /dev/null @@ -1,367 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/parameters/dummy/parameter.proto - -package dummy - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type DummyParameter struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - Data base.DecData `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` -} - -func (m *DummyParameter) Reset() { *m = DummyParameter{} } -func (*DummyParameter) ProtoMessage() {} -func (*DummyParameter) Descriptor() ([]byte, []int) { - return fileDescriptor_4187567937e47c6b, []int{0} -} -func (m *DummyParameter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DummyParameter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DummyParameter.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DummyParameter) XXX_Merge(src proto.Message) { - xxx_messageInfo_DummyParameter.Merge(m, src) -} -func (m *DummyParameter) XXX_Size() int { - return m.Size() -} -func (m *DummyParameter) XXX_DiscardUnknown() { - xxx_messageInfo_DummyParameter.DiscardUnknown(m) -} - -var xxx_messageInfo_DummyParameter proto.InternalMessageInfo - -func init() { - proto.RegisterType((*DummyParameter)(nil), "persistence_sdk.modules.orders.internal.parameters.dummy.DummyParameter") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/orders/internal/parameters/dummy/parameter.proto", fileDescriptor_4187567937e47c6b) -} - -var fileDescriptor_4187567937e47c6b = []byte{ - // 302 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xf2, 0x28, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0xcf, 0x2f, 0x4a, 0x49, 0x2d, 0x2a, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, - 0xca, 0x4b, 0xcc, 0xd1, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x4d, 0x2d, 0x01, 0x89, 0xa5, 0x94, 0xe6, - 0xe6, 0x56, 0x22, 0x04, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x2c, 0xd0, 0x4c, 0xd2, 0x83, - 0x9a, 0xa4, 0x07, 0x31, 0x49, 0x0f, 0x66, 0x92, 0x1e, 0xc2, 0x24, 0x3d, 0xb0, 0x49, 0x52, 0x22, - 0xe9, 0xf9, 0xe9, 0xf9, 0x60, 0x43, 0xf4, 0x41, 0x2c, 0x88, 0x79, 0x52, 0xfa, 0xe8, 0x2e, 0x2b, - 0x4e, 0xce, 0x48, 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, - 0xd5, 0x4f, 0x49, 0x4d, 0x76, 0x49, 0x2c, 0x49, 0x84, 0x6a, 0xd0, 0x22, 0xac, 0x21, 0x33, 0x05, - 0xa2, 0x56, 0x69, 0x1e, 0x23, 0x17, 0x9f, 0x0b, 0xc8, 0xf2, 0x00, 0x98, 0x63, 0x84, 0x6c, 0xb8, - 0x98, 0x33, 0xe3, 0x53, 0x24, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0x54, 0xf5, 0xd0, 0x7d, 0x03, - 0x31, 0x4c, 0x0f, 0x6c, 0x98, 0x1e, 0xc8, 0x30, 0x3d, 0x4f, 0x17, 0x27, 0x96, 0x13, 0xf7, 0xe4, - 0x19, 0x82, 0x98, 0x32, 0x5d, 0x84, 0x5c, 0xb8, 0x58, 0x52, 0x12, 0x4b, 0x12, 0x25, 0x98, 0xc0, - 0xda, 0xb5, 0x88, 0xd0, 0xee, 0x02, 0x71, 0x3c, 0xd4, 0x0c, 0xb0, 0x6e, 0x2b, 0x8e, 0x8e, 0x05, - 0xf2, 0x0c, 0x33, 0x16, 0xc8, 0x33, 0x38, 0x65, 0x9f, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, - 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, 0x78, 0x2c, 0xc7, 0x70, 0xe3, 0xb1, - 0x1c, 0x43, 0x54, 0x60, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0x2e, 0x72, 0x10, - 0xf9, 0xe7, 0xa5, 0x22, 0x73, 0x83, 0x5d, 0xbc, 0x89, 0x8e, 0xca, 0x24, 0x36, 0x70, 0xa0, 0x18, - 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x62, 0x1c, 0xf9, 0x0d, 0x0d, 0x02, 0x00, 0x00, -} - -func (m *DummyParameter) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DummyParameter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DummyParameter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Data.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintParameter(dAtA []byte, offset int, v uint64) int { - offset -= sovParameter(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *DummyParameter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovParameter(uint64(l)) - l = m.Data.Size() - n += 1 + l + sovParameter(uint64(l)) - return n -} - -func sovParameter(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParameter(x uint64) (n int) { - return sovParameter(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *DummyParameter) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DummyParameter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DummyParameter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParameter(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParameter - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParameter(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParameter - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParameter - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParameter - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParameter = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParameter = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParameter = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/orders/internal/parameters/dummy/prototype.go b/modules/orders/internal/parameters/dummy/prototype.go deleted file mode 100644 index b390a673e..000000000 --- a/modules/orders/internal/parameters/dummy/prototype.go +++ /dev/null @@ -1,3 +0,0 @@ -package dummy - -var Parameter = NewParameter(ID, DefaultData) diff --git a/modules/orders/internal/parameters/dummy/validator.go b/modules/orders/internal/parameters/dummy/validator.go index cc0d80a52..2bb100018 100644 --- a/modules/orders/internal/parameters/dummy/validator.go +++ b/modules/orders/internal/parameters/dummy/validator.go @@ -1,32 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/parameters" ) func validator(i interface{}) error { switch value := i.(type) { - case DummyParameter: - data, Error := value.GetData().AsDec() - if Error != nil || value.GetID().Compare(ID) != 0 || data.IsNegative() { - return errors.InvalidParameter + case parameters.Parameter: + if value.GetID().Compare(ID) != 0 || value.GetData().(data.DecData).Get().IsNegative() { + return constants.InvalidParameter } return nil - case types.Data: - data, Error := value.AsDec() - if Error != nil || data.IsNegative() { - return errors.InvalidParameter + case data.DecData: + if value.Get().IsNegative() { + return constants.InvalidParameter } return nil default: - return errors.IncorrectFormat + return constants.IncorrectFormat } } diff --git a/modules/orders/internal/parameters/dummy/validator_test.go b/modules/orders/internal/parameters/dummy/validator_test.go new file mode 100644 index 000000000..6915a0b78 --- /dev/null +++ b/modules/orders/internal/parameters/dummy/validator_test.go @@ -0,0 +1,21 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package dummy + +import ( + "testing" + + "github.com/stretchr/testify/require" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/errors/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" +) + +func Test_Validator(t *testing.T) { + require.Equal(t, constants.IncorrectFormat, validator(baseIDs.NewStringID(""))) + require.Equal(t, nil, validator(Parameter)) + require.Equal(t, constants.InvalidParameter, validator(baseTypes.NewParameter(baseIDs.NewStringID(""), baseData.NewStringData(""), validator))) +} diff --git a/modules/orders/internal/parameters/prototype.go b/modules/orders/internal/parameters/prototype.go new file mode 100644 index 000000000..e005e2832 --- /dev/null +++ b/modules/orders/internal/parameters/prototype.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package parameters + +import ( + "github.com/AssetMantle/modules/modules/orders/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Parameters { + return baseHelpers.NewParameters(dummy.Parameter) +} diff --git a/modules/orders/internal/queries/order/grpc_query.go b/modules/orders/internal/queries/order/grpc_query.go deleted file mode 100644 index e098a1e17..000000000 --- a/modules/orders/internal/queries/order/grpc_query.go +++ /dev/null @@ -1,29 +0,0 @@ -package order - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type queryServer struct { - queryKeeper -} - -var _ QueryServer = queryServer{} - -func (queryServer queryServer) Enquire(ctx context.Context, queryRequest *QueryRequest) (*QueryResponse, error) { - cntx := sdkTypes.UnwrapSDKContext(ctx) - - keyr := key.FromID(base.NewID(queryRequest.OrderID.String())) - - collection := queryServer.queryKeeper.mapper.NewCollection(cntx) - response := newQueryResponse(collection.Fetch(keyr), nil) - return &response, response.GetError() - -} - -func NewQueryServerImpl(keeper queryKeeper) QueryServer { - return &queryServer{keeper} -} diff --git a/modules/orders/internal/queries/order/keeper.go b/modules/orders/internal/queries/order/keeper.go new file mode 100644 index 000000000..e62b16fc6 --- /dev/null +++ b/modules/orders/internal/queries/order/keeper.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package order + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/schema/helpers" +) + +type queryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.QueryKeeper = (*queryKeeper)(nil) + +func (queryKeeper queryKeeper) Enquire(context sdkTypes.Context, queryRequest helpers.QueryRequest) helpers.QueryResponse { + return newQueryResponse(queryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(queryRequestFromInterface(queryRequest).OrderID)), nil) +} + +func (queryKeeper queryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + queryKeeper.mapper = mapper + return queryKeeper +} + +func keeperPrototype() helpers.QueryKeeper { + return queryKeeper{} +} diff --git a/modules/orders/internal/queries/order/keeper_test.go b/modules/orders/internal/queries/order/keeper_test.go index 86a447ece..034da3bc4 100644 --- a/modules/orders/internal/queries/order/keeper_test.go +++ b/modules/orders/internal/queries/order/keeper_test.go @@ -1,55 +1,49 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package order import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "testing" + + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" ) -func CreateTestInput2(t *testing.T) (sdkTypes.Context, helpers.Keeper) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +type TestKeepers struct { + QueryKeeper helpers.QueryKeeper +} + +func CreateTestInputForQueries(t *testing.T) (types.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") - memDB := tendermintDB.NewMemDB() - commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) - - context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ - ChainID: "test", - }, false, log.NewNopLogger()) - - mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + storeKey := types.NewKVStoreKey("test") + paramsStoreKey := types.NewKVStoreKey("testParams") + paramsTransientStoreKeys := types.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) paramsKeeper := params.NewKeeper( Codec, paramsStoreKey, @@ -57,30 +51,101 @@ func CreateTestInput2(t *testing.T) (sdkTypes.Context, helpers.Keeper) { ) Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) - testQueryKeeper := keeperPrototype().Initialize(mapper, Parameters, []interface{}{}) - - return context, testQueryKeeper -} + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, types.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) -func Test_Query_Keeper_Order(t *testing.T) { + context := types.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) - context, keepers := CreateTestInput2(t) - immutableProperties, Error := base.ReadProperties("defaultImmutable1:S|defaultImmutable1") - require.Equal(t, nil, Error) - mutableProperties, Error2 := base.ReadProperties("burn:S|100") - require.Equal(t, nil, Error2) + keepers := TestKeepers{ + QueryKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.QueryKeeper), + } - classificationID := base.NewID("classificationID") - makerOwnableID := base.NewID("makerOwnableID") - takerOwnableID := base.NewID("takerOwnableID") - exchangeRateID := base.NewID(sdkTypes.OneDec().String()) - creationHeightID := base.NewID("0") - makerID := base.NewID("makerID") + return context, keepers, Mapper, Parameters +} - orderID := key.NewOrderID(classificationID, makerOwnableID, takerOwnableID, exchangeRateID, creationHeightID, makerID, immutableProperties) - keepers.(queryKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(orderID, immutableProperties, mutableProperties)) +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryKeeper + }{ + {"+ve", queryKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - testQueryRequest := newQueryRequest(classificationID) - require.Equal(t, queryResponse{Success: true, Error: nil, List: keepers.(queryKeeper).mapper.NewCollection(context).Fetch(key.FromID(orderID)).GetList()}, keepers.(queryKeeper).LegacyEnquire(context, testQueryRequest)) +func Test_queryKeeper_Enquire(t *testing.T) { + context, keepers, Mapper, _ := CreateTestInputForQueries(t) + testOrder := baseDocuments.NewOrder(testClassificationID, immutables, mutables) + keepers.QueryKeeper.(queryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testOrder)) + type fields struct { + mapper helpers.Mapper + } + type args struct { + context types.Context + queryRequest helpers.QueryRequest + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryResponse + }{ + {"+ve", fields{Mapper}, args{context, newQueryRequest(testOrderID)}, newQueryResponse(keepers.QueryKeeper.(queryKeeper).mapper.NewCollection(context).Fetch(key.NewKey(testOrderID)), nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryKeeper := queryKeeper{ + mapper: tt.fields.mapper, + } + if got := queryKeeper.Enquire(tt.args.context, tt.args.queryRequest); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Enquire() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_queryKeeper_Initialize(t *testing.T) { + context, keepers, Mapper, Parameters := CreateTestInputForQueries(t) + testOrder := baseDocuments.NewOrder(testClassificationID, immutables, mutables) + keepers.QueryKeeper.(queryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testOrder)) + type fields struct { + mapper helpers.Mapper + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + in2 []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve with nil", fields{}, args{}, queryKeeper{}}, + {"+ve", fields{Mapper}, args{Mapper, Parameters, []interface{}{}}, queryKeeper{Mapper}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryKeeper := queryKeeper{ + mapper: tt.fields.mapper, + } + if got := queryKeeper.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/queries/order/query.go b/modules/orders/internal/queries/order/query.go new file mode 100644 index 000000000..c10da8b07 --- /dev/null +++ b/modules/orders/internal/queries/order/query.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package order + +import ( + "github.com/AssetMantle/modules/modules/orders/internal/module" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Query = baseHelpers.NewQuery( + "orders", + "", + "", + + module.Name, + + requestPrototype, + responsePrototype, + keeperPrototype, + + constants.OrderID, +) diff --git a/modules/orders/internal/queries/order/query.pb.go b/modules/orders/internal/queries/order/query.pb.go deleted file mode 100644 index 00a317077..000000000 --- a/modules/orders/internal/queries/order/query.pb.go +++ /dev/null @@ -1,673 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/queries/order/query.proto - -package order - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - github_com_persistenceOne_persistenceSDK_schema_helpers "github.com/persistenceOne/persistenceSDK/schema/helpers" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type QueryRequest struct { - OrderID base.ID `protobuf:"bytes,1,opt,name=order_i_d,json=orderID,proto3" json:"order_i_d" valid:"required~required OrderID missing"` -} - -func (m *QueryRequest) Reset() { *m = QueryRequest{} } -func (m *QueryRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRequest) ProtoMessage() {} -func (*QueryRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_51602469a6390915, []int{0} -} -func (m *QueryRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRequest.Merge(m, src) -} -func (m *QueryRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRequest proto.InternalMessageInfo - -type QueryResponse struct { - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` - List []github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable `protobuf:"bytes,3,rep,name=list,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable" json:"list"` -} - -func (m *QueryResponse) Reset() { *m = QueryResponse{} } -func (m *QueryResponse) String() string { return proto.CompactTextString(m) } -func (*QueryResponse) ProtoMessage() {} -func (*QueryResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_51602469a6390915, []int{1} -} -func (m *QueryResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryResponse.Merge(m, src) -} -func (m *QueryResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryRequest)(nil), "persistence_sdk.modules.orders.internal.queries.order.QueryRequest") - proto.RegisterType((*QueryResponse)(nil), "persistence_sdk.modules.orders.internal.queries.order.QueryResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/orders/internal/queries/order/query.proto", fileDescriptor_51602469a6390915) -} - -var fileDescriptor_51602469a6390915 = []byte{ - // 464 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0x31, 0x8b, 0xd4, 0x40, - 0x14, 0xc7, 0x33, 0x77, 0x9e, 0x7b, 0x1b, 0xb5, 0x09, 0x57, 0xac, 0xab, 0x24, 0x31, 0x20, 0xac, - 0x16, 0x33, 0x78, 0x62, 0x73, 0x95, 0xae, 0x2b, 0x78, 0x88, 0x1e, 0xc6, 0x4e, 0x84, 0x65, 0x36, - 0x79, 0x64, 0x07, 0xb3, 0x33, 0xd9, 0x79, 0x13, 0xe1, 0x1a, 0x0b, 0x2b, 0x2b, 0x11, 0xfc, 0x02, - 0xd7, 0xf9, 0x11, 0xac, 0xed, 0xae, 0x3c, 0xb0, 0x11, 0x8b, 0x45, 0x76, 0x2d, 0xac, 0xfd, 0x04, - 0x92, 0xc9, 0x06, 0x97, 0xad, 0x16, 0xaf, 0xca, 0xfc, 0xdf, 0x84, 0x5f, 0x7e, 0xef, 0xcd, 0xc4, - 0x7d, 0x50, 0x80, 0x46, 0x81, 0x06, 0x64, 0x02, 0x43, 0x4c, 0x5f, 0xb3, 0x89, 0x4a, 0xcb, 0x1c, - 0x90, 0x29, 0x9d, 0x82, 0x46, 0x26, 0xa4, 0x01, 0x2d, 0x79, 0xce, 0xa6, 0x25, 0x68, 0xd1, 0xd4, - 0x6d, 0x3a, 0xa6, 0x85, 0x56, 0x46, 0x79, 0xf7, 0xd6, 0x10, 0x74, 0x89, 0xa0, 0x35, 0x82, 0x36, - 0x08, 0xba, 0x44, 0xd4, 0xf5, 0xee, 0x5e, 0xa6, 0x32, 0x65, 0x09, 0xac, 0x5a, 0xd5, 0xb0, 0xee, - 0xf5, 0x4c, 0xa9, 0x2c, 0x07, 0xc6, 0x0b, 0xc1, 0xb8, 0x94, 0xca, 0x70, 0x23, 0x94, 0xc4, 0xe5, - 0xee, 0xed, 0x75, 0x5b, 0x4c, 0xc6, 0x30, 0xe1, 0xcc, 0x1c, 0x17, 0x80, 0x6c, 0xc4, 0x11, 0x98, - 0x48, 0xeb, 0x77, 0xa3, 0x0f, 0xc4, 0xbd, 0xfc, 0xbc, 0xd2, 0x8c, 0x61, 0x5a, 0x02, 0x1a, 0xcf, - 0xb8, 0x6d, 0xfb, 0xe5, 0xa1, 0x18, 0xa6, 0x1d, 0x12, 0x92, 0xde, 0xa5, 0xfd, 0x9b, 0x74, 0xdd, - 0xbd, 0x06, 0x52, 0x0b, 0xa4, 0x15, 0x90, 0x1e, 0x0e, 0xfa, 0x77, 0x4e, 0x67, 0x81, 0xf3, 0x67, - 0x16, 0xdc, 0x7a, 0xc3, 0x73, 0x91, 0x1e, 0x44, 0x1a, 0xa6, 0xa5, 0xd0, 0x90, 0xbe, 0x6d, 0x16, - 0xe1, 0x51, 0x05, 0x3e, 0x1c, 0x84, 0x13, 0x81, 0x28, 0x64, 0x16, 0xc5, 0x2d, 0x55, 0x57, 0x0e, - 0x76, 0xdf, 0x9f, 0x04, 0xce, 0xef, 0x93, 0xc0, 0x89, 0x3e, 0x13, 0xf7, 0xca, 0x52, 0x08, 0x0b, - 0x25, 0x11, 0xbc, 0x8e, 0xdb, 0xc2, 0x32, 0x49, 0x00, 0xd1, 0xfa, 0xec, 0xc6, 0x4d, 0xf4, 0xf6, - 0xdc, 0x1d, 0xd0, 0x5a, 0xe9, 0xce, 0x56, 0x48, 0x7a, 0xed, 0xb8, 0x0e, 0xde, 0x2b, 0xf7, 0x42, - 0x2e, 0xd0, 0x74, 0xb6, 0xc3, 0xed, 0x5e, 0xbb, 0xff, 0xb8, 0xb2, 0xfa, 0x31, 0x0b, 0xee, 0x67, - 0xc2, 0x8c, 0xcb, 0x11, 0x4d, 0xd4, 0x84, 0xad, 0xb4, 0x73, 0x24, 0x61, 0x35, 0xbe, 0x18, 0x3c, - 0x69, 0xa6, 0x35, 0x86, 0xbc, 0xda, 0xa0, 0x4f, 0x79, 0x51, 0xf0, 0x51, 0x0e, 0xb1, 0xa5, 0xfe, - 0x33, 0xdd, 0xff, 0x4a, 0xdc, 0x1d, 0x6b, 0xea, 0x7d, 0x21, 0x6e, 0xeb, 0x91, 0xb4, 0x4d, 0x7a, - 0x0f, 0xe9, 0x7f, 0x1d, 0x34, 0x5d, 0x3d, 0x84, 0xee, 0xe0, 0x7c, 0x90, 0x7a, 0x70, 0xd1, 0x8d, - 0x77, 0xdf, 0x7e, 0x7d, 0xda, 0xba, 0xe6, 0x5d, 0x5d, 0xed, 0xb0, 0xb9, 0xb2, 0xf6, 0xd1, 0x1f, - 0x9f, 0xce, 0x7d, 0x72, 0x36, 0xf7, 0xc9, 0xcf, 0xb9, 0x4f, 0x3e, 0x2e, 0x7c, 0xe7, 0x6c, 0xe1, - 0x3b, 0xdf, 0x17, 0xbe, 0xf3, 0xf2, 0xd9, 0xc6, 0xf3, 0xda, 0xe8, 0x5f, 0x18, 0x5d, 0xb4, 0xf7, - 0xed, 0xee, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x5e, 0x79, 0xa0, 0xd8, 0x4b, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) { - out := new(QueryResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.orders.internal.queries.order.Query/Enquire", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - Enquire(context.Context, *QueryRequest) (*QueryResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Enquire(ctx context.Context, req *QueryRequest) (*QueryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Enquire not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Enquire_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Enquire(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.orders.internal.queries.order.Query/Enquire", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Enquire(ctx, req.(*QueryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.orders.internal.queries.order.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Enquire", - Handler: _Query_Enquire_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/orders/internal/queries/order/query.proto", -} - -func (m *QueryRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.OrderID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.List) > 0 { - for iNdEx := len(m.List) - 1; iNdEx >= 0; iNdEx-- { - { - size := m.List[iNdEx].Size() - i -= size - if _, err := m.List[iNdEx].MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Error) > 0 { - i -= len(m.Error) - copy(dAtA[i:], m.Error) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Error))) - i-- - dAtA[i] = 0x12 - } - if m.Success { - i-- - if m.Success { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.OrderID.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Success { - n += 2 - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.List) > 0 { - for _, e := range m.List { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OrderID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OrderID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Success = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field List", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var v github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable - m.List = append(m.List, v) - if err := m.List[len(m.List)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/orders/internal/queries/order/query.pb.gw.go b/modules/orders/internal/queries/order/query.pb.gw.go deleted file mode 100644 index 702a51c9a..000000000 --- a/modules/orders/internal/queries/order/query.pb.gw.go +++ /dev/null @@ -1,166 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/queries/order/query.proto - -/* -Package order is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package order - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage - -var ( - filter_Query_Enquire_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Enquire(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Enquire(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features (such as grpc.SendHeader, etc) to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Enquire_0(rctx, inboundMarshaler, server, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Enquire_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Enquire_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"persistence", "orders", "order"}, "", runtime.AssumeColonVerbOpt(true))) -) - -var ( - forward_Query_Enquire_0 = runtime.ForwardResponseMessage -) diff --git a/modules/orders/internal/queries/order/request.go b/modules/orders/internal/queries/order/request.go index f9964a8f5..d9180bb96 100644 --- a/modules/orders/internal/queries/order/request.go +++ b/modules/orders/internal/queries/order/request.go @@ -1,81 +1,74 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package order import ( "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/cosmos/cosmos-sdk/client/context" + + "github.com/AssetMantle/modules/modules/orders/internal/common" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" ) -var _ helpers.QueryRequest = (*QueryRequest)(nil) +type queryRequest struct { + ids.OrderID `json:"orderID" valid:"required~required field orderID missing"` +} + +var _ helpers.QueryRequest = (*queryRequest)(nil) -// QueryRequest godoc +// Validate godoc // @Summary Query order using order id -// @Descrption Able to query the order +// @Description Able to query the order // @Accept json // @Produce json // @Tags Orders // @Param orderID path string true "order ID" -// @Success 200 {object} queryResponse "A successful query response" -// @Failure default {object} queryResponse "An unexpected error response." +// @Success 200 {object} queryResponse "Message for a successful response" +// @Failure default {object} queryResponse "Message for an unexpected error response." // @Router /orders/orders/{orderID} [get] -func (queryRequest QueryRequest) Validate() error { - _, Error := govalidator.ValidateStruct(queryRequest) - return Error -} - -func (queryRequest QueryRequest) FromCLI(cliCommand helpers.CLICommand, _ client.Context) helpers.QueryRequest { - return newQueryRequest(base.NewID(cliCommand.ReadString(flags.OrderID))) -} - -func (queryRequest QueryRequest) FromMap(vars map[string]string) helpers.QueryRequest { - return newQueryRequest(base.NewID(vars[Query.GetName()])) +func (queryRequest queryRequest) Validate() error { + _, err := govalidator.ValidateStruct(queryRequest) + return err } -func (queryRequest QueryRequest) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryRequest) +func (queryRequest) FromCLI(cliCommand helpers.CLICommand, _ context.CLIContext) (helpers.QueryRequest, error) { + if orderID, err := baseIDs.ReadOrderID(cliCommand.ReadString(constants.OrderID)); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(orderID), nil + } } - -func (queryRequest QueryRequest) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryRequest, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest) FromMap(vars map[string]string) (helpers.QueryRequest, error) { + if orderID, err := baseIDs.ReadOrderID(vars[Query.GetName()]); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(orderID), nil } - - return queryRequest, nil } - -func (queryRequest QueryRequest) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryRequest) +func (queryRequest queryRequest) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryRequest) } - -func (queryRequest QueryRequest) LegacyAminoDecode(bytes []byte) (helpers.QueryRequest, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest queryRequest) Decode(bytes []byte) (helpers.QueryRequest, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryRequest); err != nil { + return nil, err } return queryRequest, nil } func requestPrototype() helpers.QueryRequest { - return QueryRequest{} + return queryRequest{} } - -func queryRequestFromInterface(request helpers.QueryRequest) QueryRequest { +func queryRequestFromInterface(request helpers.QueryRequest) queryRequest { switch value := request.(type) { - case QueryRequest: + case queryRequest: return value default: - return QueryRequest{} + return queryRequest{} } } - -func newQueryRequest(orderID types.ID) helpers.QueryRequest { - return QueryRequest{OrderID: *base.NewID(orderID.String())} +func newQueryRequest(orderID ids.OrderID) helpers.QueryRequest { + return queryRequest{OrderID: orderID} } diff --git a/modules/orders/internal/queries/order/request_test.go b/modules/orders/internal/queries/order/request_test.go index 9ddeb58e1..b454274d0 100644 --- a/modules/orders/internal/queries/order/request_test.go +++ b/modules/orders/internal/queries/order/request_test.go @@ -1,58 +1,258 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package order import ( - "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/common" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/spf13/viper" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/orders/internal/common" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + base2 "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" ) -func Test_Order_Request(t *testing.T) { +var ( + immutables = baseQualified.NewImmutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables = baseQualified.NewMutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() + testClassificationID = baseIDs.NewClassificationID(immutables, mutables) + testFromID = baseIDs.NewIdentityID(testClassificationID, immutables) + testOrderID = baseIDs.NewOrderID(testClassificationID, immutables) + testOrderID1 = baseIDs.PrototypeOrderID() +) - testOrderID := base.NewID("OrderID") - testQueryRequest := newQueryRequest(testOrderID) - require.Equal(t, nil, testQueryRequest.Validate()) - require.Equal(t, queryRequest{}, requestPrototype()) +func Test_newQueryRequest(t *testing.T) { + type args struct { + orderID ids.OrderID + } + tests := []struct { + name string + args args + want helpers.QueryRequest + }{ + {"+ve", args{testOrderID}, newQueryRequest(testOrderID)}, + {"+ve with nil", args{testOrderID1}, newQueryRequest(testOrderID1)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newQueryRequest(tt.args.orderID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newQueryRequest() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequestFromInterface(t *testing.T) { + type args struct { + request helpers.QueryRequest + } + tests := []struct { + name string + args args + want queryRequest + }{ + {"+ve", args{newQueryRequest(testOrderID)}, queryRequest{testOrderID}}, + {"+ve with nil", args{newQueryRequest(testOrderID1)}, queryRequest{testOrderID1}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := queryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("queryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.OrderID}) - cliContext := context.NewCLIContext().WithCodec(Codec) - require.Equal(t, newQueryRequest(base.NewID("")), queryRequest{}.FromCLI(cliCommand, cliContext)) +func Test_queryRequest_Decode(t *testing.T) { + encodedReq, err := common.Codec.MarshalJSON(newQueryRequest(testOrderID)) + require.NoError(t, err) + encodedReq1, err1 := common.Codec.MarshalJSON(newQueryRequest(testOrderID1)) + require.NoError(t, err1) + type fields struct { + OrderID ids.OrderID + } + type args struct { + bytes []byte + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testOrderID}, args{encodedReq}, newQueryRequest(testOrderID), false}, + {"+ve", fields{testOrderID1}, args{encodedReq1}, newQueryRequest(testOrderID1), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + OrderID: tt.fields.OrderID, + } + got, err := queryRequest.Decode(tt.args.bytes) + if (err != nil) != tt.wantErr { + t.Errorf("Decode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Decode() got = %v, want %v", got, tt.want) + } + }) + } +} +func Test_queryRequest_Encode(t *testing.T) { + encodedReq, err := common.Codec.MarshalJSON(newQueryRequest(testOrderID)) + require.NoError(t, err) + encodedReq1, err1 := common.Codec.MarshalJSON(newQueryRequest(testOrderID1)) + require.NoError(t, err1) + type fields struct { + OrderID ids.OrderID + } + tests := []struct { + name string + fields fields + want []byte + wantErr bool + }{ + {"+ve", fields{testOrderID}, encodedReq, false}, + {"+ve", fields{testOrderID1}, encodedReq1, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + OrderID: tt.fields.OrderID, + } + got, err := queryRequest.Encode() + if (err != nil) != tt.wantErr { + t.Errorf("Encode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Encode() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequest_FromCLI(t *testing.T) { + cliCommand := base2.NewCLICommand("", "", "", []helpers.CLIFlag{constants.OrderID}) + viper.Set(constants.OrderID.GetName(), testOrderID.String()) + type fields struct { + OrderID ids.OrderID + } + type args struct { + cliCommand helpers.CLICommand + in1 context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testOrderID}, args{cliCommand, context.NewCLIContext()}, newQueryRequest(testOrderID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + OrderID: tt.fields.OrderID, + } + got, err := qu.FromCLI(tt.args.cliCommand, tt.args.in1) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequest_FromMap(t *testing.T) { vars := make(map[string]string) - vars["orders"] = "randomString" - require.Equal(t, newQueryRequest(base.NewID("randomString")), queryRequest{}.FromMap(vars)) - - encodedRequest, Error := testQueryRequest.LegacyAminoEncode() - encodedResult, _ := common.LegacyAminoCodec.MarshalJSON(testQueryRequest) - require.Equal(t, encodedResult, encodedRequest) - require.Nil(t, Error) - - decodedRequest, Error := queryRequest{}.LegacyAminoDecode(encodedRequest) - require.Equal(t, testQueryRequest, decodedRequest) - require.Equal(t, nil, Error) - - randomDecode, _ := queryRequest{}.LegacyAminoDecode(base.NewID("").Bytes()) - require.Equal(t, nil, randomDecode) - require.Equal(t, testQueryRequest, queryRequestFromInterface(testQueryRequest)) - require.Equal(t, queryRequest{}, queryRequestFromInterface(nil)) + vars[Query.GetName()] = testOrderID.String() + type fields struct { + OrderID ids.OrderID + } + type args struct { + vars map[string]string + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testOrderID}, args{vars}, newQueryRequest(testOrderID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + OrderID: tt.fields.OrderID, + } + got, err := qu.FromMap(tt.args.vars) + if (err != nil) != tt.wantErr { + t.Errorf("FromMap() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromMap() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequest_Validate(t *testing.T) { + type fields struct { + OrderID ids.OrderID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testOrderID}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + OrderID: tt.fields.OrderID, + } + if err := queryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryRequest + }{ + {"+ve", queryRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/queries/order/response.go b/modules/orders/internal/queries/order/response.go index 6e9d6a875..bcd2a3e59 100644 --- a/modules/orders/internal/queries/order/response.go +++ b/modules/orders/internal/queries/order/response.go @@ -1,64 +1,49 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package order import ( - "errors" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/orders/internal/common" + "github.com/AssetMantle/modules/schema/helpers" ) -var _ helpers.QueryResponse = (*QueryResponse)(nil) +type queryResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` + List []helpers.Mappable `json:"list"` +} + +var _ helpers.QueryResponse = (*queryResponse)(nil) -func (queryResponse QueryResponse) IsSuccessful() bool { +func (queryResponse queryResponse) IsSuccessful() bool { return queryResponse.Success } -func (queryResponse QueryResponse) GetError() error { - return errors.New(queryResponse.Error) +func (queryResponse queryResponse) GetError() error { + return queryResponse.Error } -func (queryResponse QueryResponse) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryResponse) +func (queryResponse queryResponse) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryResponse) } -func (queryResponse QueryResponse) LegacyAminoDecode(bytes []byte) (helpers.QueryResponse, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error +func (queryResponse queryResponse) Decode(bytes []byte) (helpers.QueryResponse, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryResponse); err != nil { + return nil, err } - return &queryResponse, nil -} -func (queryResponse QueryResponse) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryResponse) -} - -func (queryResponse QueryResponse) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryResponse, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error - } - return &queryResponse, nil + return queryResponse, nil } - func responsePrototype() helpers.QueryResponse { - return &QueryResponse{} + return queryResponse{} } - -func newQueryResponse(collection helpers.Collection, error error) QueryResponse { +func newQueryResponse(collection helpers.Collection, error error) helpers.QueryResponse { success := true if error != nil { success = false - return QueryResponse{ - Success: success, - Error: "yes", - List: collection.GetList(), - } } - return QueryResponse{ + + return queryResponse{ Success: success, - Error: "no", + Error: error, List: collection.GetList(), } - } diff --git a/modules/orders/internal/queries/order/response_test.go b/modules/orders/internal/queries/order/response_test.go index f5f95fbbb..bb607c3c7 100644 --- a/modules/orders/internal/queries/order/response_test.go +++ b/modules/orders/internal/queries/order/response_test.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package order @@ -17,17 +15,17 @@ import ( "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mapper" - "github.com/persistenceOne/persistenceSDK/schema" + "github.com/AssetMantle/modules/modules/orders/internal/common" + "github.com/AssetMantle/modules/modules/orders/internal/mapper" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/errors/constants" ) func CreateTestInput(t *testing.T) sdkTypes.Context { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() @@ -56,21 +54,21 @@ func Test_Order_Response(t *testing.T) { collection := mapper.Prototype().NewCollection(context) testQueryResponse := newQueryResponse(collection, nil) - testQueryResponseWithError := newQueryResponse(collection, errors.IncorrectFormat) + testQueryResponseWithError := newQueryResponse(collection, constants.IncorrectFormat) require.Equal(t, true, testQueryResponse.IsSuccessful()) require.Equal(t, false, testQueryResponseWithError.IsSuccessful()) require.Equal(t, nil, testQueryResponse.GetError()) - require.Equal(t, errors.IncorrectFormat, testQueryResponseWithError.GetError()) + require.Equal(t, constants.IncorrectFormat, testQueryResponseWithError.GetError()) - encodedResponse, _ := testQueryResponse.LegacyAminoEncode() - bytes, _ := common.LegacyAminoCodec.MarshalJSON(testQueryResponse) + encodedResponse, _ := testQueryResponse.Encode() + bytes, _ := common.Codec.MarshalJSON(testQueryResponse) require.Equal(t, bytes, encodedResponse) - decodedResponse, _ := queryResponse{}.LegacyAminoDecode(bytes) + decodedResponse, _ := queryResponse{}.Decode(bytes) require.Equal(t, testQueryResponse, decodedResponse) - decodedResponse2, _ := queryResponse{}.LegacyAminoDecode([]byte{}) + decodedResponse2, _ := queryResponse{}.Decode([]byte{}) require.Equal(t, nil, decodedResponse2) require.Equal(t, queryResponse{}, responsePrototype()) diff --git a/modules/orders/internal/queries/prototype.go b/modules/orders/internal/queries/prototype.go new file mode 100644 index 000000000..477571ce0 --- /dev/null +++ b/modules/orders/internal/queries/prototype.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queries + +import ( + "github.com/AssetMantle/modules/modules/orders/internal/queries/order" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Queries { + return baseHelpers.NewQueries( + order.Query, + ) +} diff --git a/modules/orders/internal/queries/prototype_test.go b/modules/orders/internal/queries/prototype_test.go new file mode 100644 index 000000000..c931a7ed7 --- /dev/null +++ b/modules/orders/internal/queries/prototype_test.go @@ -0,0 +1,19 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queries + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/orders/internal/queries/order" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Get("orders").GetName(), baseHelpers.NewQueries( + order.Query, + ).Get("orders").GetName()) +} diff --git a/modules/orders/internal/simulator/constants.go b/modules/orders/internal/simulator/constants.go new file mode 100644 index 000000000..0e23f0a61 --- /dev/null +++ b/modules/orders/internal/simulator/constants.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +const OpWeightSubmitTextProposal = "op_weight_submit_text_proposal" +const DefaultWeightTextProposal = 1 + +const OpWeightMsg = "OpWeightMsg" +const DefaultWeightMsg = 1 diff --git a/modules/orders/internal/simulator/genesis.go b/modules/orders/internal/simulator/genesis.go new file mode 100644 index 000000000..2b827a1cc --- /dev/null +++ b/modules/orders/internal/simulator/genesis.go @@ -0,0 +1,51 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "math/rand" + + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + + "github.com/AssetMantle/modules/modules/orders/internal/common" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + ordersModule "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/modules/orders/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/data" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + parametersSchema "github.com/AssetMantle/modules/schema/parameters" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseSimulation "github.com/AssetMantle/modules/simulation/schema/types/base" +) + +func (simulator) RandomizedGenesisState(simulationState *module.SimulationState) { + var Data data.Data + + simulationState.AppParams.GetOrGenerate( + simulationState.Cdc, + dummy.ID.String(), + &Data, + simulationState.Rand, + func(rand *rand.Rand) { Data = baseData.NewDecData(sdkTypes.NewDecWithPrec(int64(rand.Intn(99)), 2)) }, + ) + + mappableList := make([]helpers.Mappable, simulationState.Rand.Intn(99)) + + for i := range mappableList { + immutables := baseQualified.NewImmutables(baseSimulation.GenerateRandomPropertyList(simulationState.Rand)) + mutables := baseQualified.NewMutables(baseSimulation.GenerateRandomPropertyList(simulationState.Rand)) + mappableList[i] = mappable.NewMappable(base.NewOrder(baseIDs.NewClassificationID(immutables, mutables), immutables, mutables)) + } + + genesisState := baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, nil, parameters.Prototype().GetList()).Initialize(mappableList, []parametersSchema.Parameter{dummy.Parameter.Mutate(Data)}) + + simulationState.GenState[ordersModule.Name] = common.Codec.MustMarshalJSON(genesisState) +} diff --git a/modules/orders/internal/simulator/operations.go b/modules/orders/internal/simulator/operations.go index e97b97359..3c3884187 100644 --- a/modules/orders/internal/simulator/operations.go +++ b/modules/orders/internal/simulator/operations.go @@ -1,20 +1,18 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( + "math/rand" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" - sdkModuleSimulation "github.com/cosmos/cosmos-sdk/x/simulation" - "math/rand" + "github.com/cosmos/cosmos-sdk/x/simulation" ) -func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec.JSONMarshaler) simulation.WeightedOperation { +func (simulator) WeightedOperations(appParams simulation.AppParams, codec *codec.Codec) simulation.WeightedOperations { var weightMsg int appParams.GetOrGenerate(codec, OpWeightMsg, &weightMsg, nil, @@ -23,10 +21,12 @@ func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec. }, ) - return sdkModuleSimulation.NewWeightedOperation( - weightMsg, - simulateMsg(), - ) + return simulation.WeightedOperations{ + simulation.NewWeightedOperation( + weightMsg, + simulateMsg(), + ), + } } func simulateMsg() simulation.Operation { diff --git a/modules/orders/internal/simulator/params.go b/modules/orders/internal/simulator/params.go index cca76eb21..3cfde38ce 100644 --- a/modules/orders/internal/simulator/params.go +++ b/modules/orders/internal/simulator/params.go @@ -1,29 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - simTypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "math/rand" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cosmos/cosmos-sdk/x/simulation" + + "github.com/AssetMantle/modules/modules/orders/internal/common" + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/modules/orders/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/data/base" ) -func (simulator) ParamChangeList(_ *rand.Rand) []simTypes.ParamChange { - return []simTypes.ParamChange{ +func (simulator) ParamChangeList(_ *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange(module.Name, dummy.ID.String(), func(r *rand.Rand) string { - bytes, Error := common.LegacyAminoCodec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdkTypes.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) - if Error != nil { - panic(Error) + bytes, err := common.Codec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdk.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) + if err != nil { + panic(err) } return string(bytes) }), diff --git a/modules/orders/internal/simulator/proposals.go b/modules/orders/internal/simulator/proposals.go index e12b080e4..ce4efd54f 100644 --- a/modules/orders/internal/simulator/proposals.go +++ b/modules/orders/internal/simulator/proposals.go @@ -1,33 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( + "math/rand" + sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" - simulation2 "github.com/cosmos/cosmos-sdk/x/simulation" - "math/rand" + "github.com/cosmos/cosmos-sdk/x/simulation" ) func (simulator) WeightedProposalContentList() []simulation.WeightedProposalContent { return []simulation.WeightedProposalContent{ - simulation2.NewWeightedProposalContent( - OpWeightSubmitTextProposal, - DefaultWeightTextProposal, - contentSimulatorFunc(), - ), + { + AppParamsKey: OpWeightSubmitTextProposal, + DefaultWeight: DefaultWeightTextProposal, + ContentSimulatorFn: simulateTextProposalContent, + }, } } -func contentSimulatorFunc() simulation.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) simulation.Content { - return types.NewTextProposal( - simulation.RandStringOfLength(r, 140), - simulation.RandStringOfLength(r, 5000), - ) - } +func simulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Account) types.Content { + return types.NewTextProposal( + simulation.RandStringOfLength(r, 140), + simulation.RandStringOfLength(r, 5000), + ) } diff --git a/modules/orders/internal/simulator/prototype.go b/modules/orders/internal/simulator/prototype.go new file mode 100644 index 000000000..3da39d69f --- /dev/null +++ b/modules/orders/internal/simulator/prototype.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +func Prototype() helpers.Simulator { + return newSimulator() +} diff --git a/modules/orders/internal/simulator/prototype_test.go b/modules/orders/internal/simulator/prototype_test.go new file mode 100644 index 000000000..4352a8d45 --- /dev/null +++ b/modules/orders/internal/simulator/prototype_test.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype(), newSimulator()) +} diff --git a/modules/orders/internal/simulator/simulator.go b/modules/orders/internal/simulator/simulator.go new file mode 100644 index 000000000..d963561c2 --- /dev/null +++ b/modules/orders/internal/simulator/simulator.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +type simulator struct{} + +var _ helpers.Simulator = (*simulator)(nil) + +func newSimulator() helpers.Simulator { + return simulator{} +} diff --git a/modules/orders/internal/transactions/cancel/keeper.go b/modules/orders/internal/transactions/cancel/keeper.go new file mode 100644 index 000000000..78b2b6ece --- /dev/null +++ b/modules/orders/internal/transactions/cancel/keeper.go @@ -0,0 +1,80 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package cancel + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + "github.com/AssetMantle/modules/schema/documents" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + orders := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.OrderID)) + + Mappable := orders.Get(key.NewKey(message.OrderID)) + if Mappable == nil { + return newTransactionResponse(errorConstants.EntityNotFound) + } + order := Mappable.(documents.Order) + + if message.FromID.Compare(order.GetMakerID()) != 0 { + return newTransactionResponse(errorConstants.NotAuthorized) + } + + if auxiliaryResponse := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, message.FromID, order.GetMakerOwnableID(), order.GetMakerOwnableSplit())); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + orders.Remove(mappable.NewMappable(order)) + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, externalKeeper := range auxiliaries { + switch value := externalKeeper.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case supplement.Auxiliary.GetName(): + transactionKeeper.supplementAuxiliary = value + case transfer.Auxiliary.GetName(): + transactionKeeper.transferAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/orders/internal/transactions/cancel/keeper_test.go b/modules/orders/internal/transactions/cancel/keeper_test.go index b23e41069..384716583 100644 --- a/modules/orders/internal/transactions/cancel/keeper_test.go +++ b/modules/orders/internal/transactions/cancel/keeper_test.go @@ -1,55 +1,64 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package cancel import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" - cryptoCodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/store" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/constants/test" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/transfer" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +var ( + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary ) type TestKeepers struct { - OrdersKeeper helpers.TransactionKeeper + CancelKeeper helpers.TransactionKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func CreateTestInput(t *testing.T) (types.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + storeKey := types.NewKVStoreKey("test") + paramsStoreKey := types.NewKVStoreKey("testParams") + paramsTransientStoreKeys := types.NewTransientStoreKey("testParamsTransient") Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) paramsKeeper := params.NewKeeper( Codec, @@ -60,103 +69,144 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + commitMultiStore.MountStoreWithDB(storeKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, types.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) - context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + supplementAuxiliary = supplement.AuxiliaryMock.Initialize(Mapper, Parameters) + transferAuxiliary = transfer.AuxiliaryMock.Initialize(Mapper, Parameters) + + context := types.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) - transferAuxiliary := transfer.AuxiliaryMock.Initialize(Mapper, Parameters) - verifyAuxiliary := verify.AuxiliaryMock.Initialize(Mapper, Parameters) - supplementAuxiliary := supplement.AuxiliaryMock.Initialize(Mapper, Parameters) keepers := TestKeepers{ - OrdersKeeper: keeperPrototype().Initialize(Mapper, Parameters, - []interface{}{verifyAuxiliary, - transferAuxiliary, supplementAuxiliary}).(helpers.TransactionKeeper), + CancelKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), } - return context, keepers + return context, keepers, Mapper, Parameters } -func Test_transactionKeeper_Transact(t *testing.T) { - - context, keepers := CreateTestInput(t) - verifyMockErrorAddress := sdkTypes.AccAddress("verifyError") - defaultAddr := sdkTypes.AccAddress("addr") - defaultIdentityID := base.NewID("fromID") - classificationID := base.NewID("classificationID") - makerOwnableID := base.NewID("makerOwnableID") - takerOwnableID := base.NewID("takerOwnableID") - rateID := base.NewID(sdkTypes.MustNewDecFromStr("0.001").String()) - creationID := base.NewID("100") - makerID := base.NewID("makerID") - metaProperties, Error := base.ReadMetaProperties(properties.MakerOwnableSplit + ":D|0.000000000000000001" + - "," + properties.TakerID + ":I|fromID" + "," + - properties.ExchangeRate + ":D|0.000000000000000001") - require.Equal(t, nil, Error) - orderID := key.NewOrderID( - classificationID, - makerOwnableID, - takerOwnableID, - rateID, - creationID, - makerID, - base.NewProperties(), - ) +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(orderID, base.NewProperties(), metaProperties.RemoveData())) - - t.Run("PositiveCase", func(t *testing.T) { - want := newTransactionResponse(nil) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, makerID, orderID)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - Identity mock error", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(verifyMockErrorAddress, defaultIdentityID, orderID)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - Cancel not existing order", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(errors.EntityNotFound) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, base.NewID("orderID"))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - Cancel with different makerID", func(t *testing.T) { - t.Parallel() - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(orderID, base.NewProperties(), metaProperties.RemoveData())) - want := newTransactionResponse(errors.NotAuthorized) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, base.NewID("id"), orderID)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - transferMock Error", func(t *testing.T) { - t.Parallel() - transferErrorID := key.NewOrderID(classificationID, - base.NewID("transferError"), - takerOwnableID, base.NewID("1.0"), - base.NewID("1"), - makerID, - base.NewProperties(), - ) - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(transferErrorID, base.NewProperties(), metaProperties.RemoveData())) - - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, makerID, transferErrorID)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := CreateTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve with nil", fields{}, args{}, transactionKeeper{}}, + {"+ve", fields{Mapper, Parameters, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + supplementAuxiliary: tt.fields.supplementAuxiliary, + transferAuxiliary: tt.fields.transferAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters := CreateTestInput(t) + mutableMetaProperties := baseLists.NewPropertyList( + baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())), + baseProperties.NewMetaProperty(baseIDs.NewStringID("exchangeRate"), baseData.NewDecData(types.NewDec(10))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerOwnableID"), baseData.NewIDData(baseIDs.NewOwnableID(baseIDs.NewStringID("makerID")))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("creationHeight"), baseData.NewHeightData(baseTypes.NewHeight(1))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("takerOwnableID"), baseData.NewIDData(baseIDs.NewOwnableID(baseIDs.NewStringID("takerID")))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(baseIDs.PrototypeIdentityID())), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(baseIDs.PrototypeIdentityID())), + ) + immutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + immutablesMeta := baseQualified.NewImmutables(immutableMetaProperties) + mutablesMeta := baseQualified.NewMutables(mutableMetaProperties) + testClassificationID := baseIDs.NewClassificationID(immutablesMeta, mutablesMeta) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutablesMeta) + testFromID2 := baseIDs.PrototypeIdentityID() + mutableMetaProperties.Mutate( + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(testFromID)), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(testFromID))) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + testIdentity := baseDocuments.NewIdentity(testClassificationID, immutablesMeta, mutablesMeta) + testIdentity.ProvisionAddress([]types.AccAddress{fromAccAddress}...) + testOrder := baseDocuments.NewOrder(testClassificationID, immutablesMeta, mutablesMeta) + testOrderID := baseIDs.NewOrderID(testClassificationID, immutablesMeta) + testOrderID2 := baseIDs.NewOrderID(testClassificationID, immutablesMeta) + keepers.CancelKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testOrder)) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + context types.Context + msg types.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve Not Authorized", fields{Mapper, Parameters, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}, args{context, newMessage(fromAccAddress, testFromID2, testOrderID)}, newTransactionResponse(constants.NotAuthorized)}, + {"+ve", fields{Mapper, Parameters, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}, args{context, newMessage(fromAccAddress, testFromID, testOrderID)}, newTransactionResponse(nil)}, + {"+ve entity Not Found", fields{Mapper, Parameters, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}, args{context, newMessage(fromAccAddress, testFromID, testOrderID2)}, newTransactionResponse(constants.EntityNotFound)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + supplementAuxiliary: tt.fields.supplementAuxiliary, + transferAuxiliary: tt.fields.transferAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/cancel/message.go b/modules/orders/internal/transactions/cancel/message.go index 9388123e5..6ec369e48 100644 --- a/modules/orders/internal/transactions/cancel/message.go +++ b/modules/orders/internal/transactions/cancel/message.go @@ -1,69 +1,64 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package cancel import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ids.OrderID `json:"orderID" valid:"required~required field orderID missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, orderID types.ID) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - OrderID: *base.NewID(orderID.String()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, orderID ids.OrderID) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + OrderID: orderID, } } diff --git a/modules/orders/internal/transactions/cancel/message.pb.go b/modules/orders/internal/transactions/cancel/message.pb.go deleted file mode 100644 index aa3d4eebe..000000000 --- a/modules/orders/internal/transactions/cancel/message.pb.go +++ /dev/null @@ -1,629 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/transactions/cancel/message.proto - -package cancel - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - OrderID base.ID `protobuf:"bytes,3,opt,name=order_i_d,json=orderID,proto3" json:"order_i_d" valid:"required~required field OrderID missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_8e0073811c6d95ba, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_8e0073811c6d95ba, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.orders.internal.transactions.cancel.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.orders.internal.transactions.cancel.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/orders/internal/transactions/cancel/message.proto", fileDescriptor_8e0073811c6d95ba) -} - -var fileDescriptor_8e0073811c6d95ba = []byte{ - // 440 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0x41, 0x6b, 0x13, 0x41, - 0x14, 0xc7, 0x77, 0x8c, 0xa4, 0xed, 0x78, 0x5b, 0x15, 0x4a, 0x0e, 0xbb, 0xcb, 0x82, 0x50, 0x44, - 0x66, 0xa0, 0x82, 0x42, 0x3d, 0x35, 0x46, 0x21, 0x48, 0xa9, 0xd4, 0x9e, 0xbc, 0x84, 0xc9, 0xcc, - 0xcb, 0x76, 0x70, 0x77, 0x26, 0xce, 0xdb, 0x28, 0x0a, 0x7a, 0xf6, 0xa8, 0x77, 0x0f, 0xc5, 0xa3, - 0x9f, 0xa4, 0xc7, 0x1e, 0xc5, 0x43, 0x90, 0xe4, 0xe2, 0xb9, 0x9f, 0x40, 0x76, 0x36, 0xa5, 0x4b, - 0x14, 0x6c, 0xc9, 0x69, 0x67, 0x1f, 0xcb, 0xef, 0xf7, 0x67, 0xdf, 0x7f, 0x68, 0x7f, 0x0c, 0x0e, - 0x35, 0x96, 0x60, 0x24, 0x0c, 0x50, 0xbd, 0xe2, 0x85, 0x55, 0x93, 0x1c, 0x90, 0x5b, 0xa7, 0xc0, - 0x21, 0xd7, 0xa6, 0x04, 0x67, 0x44, 0xce, 0x4b, 0x27, 0x0c, 0x0a, 0x59, 0x6a, 0x6b, 0x90, 0x4b, - 0x61, 0x24, 0xe4, 0xbc, 0x00, 0x44, 0x91, 0x01, 0x1b, 0x3b, 0x5b, 0xda, 0xf0, 0xd1, 0x12, 0x8a, - 0x2d, 0x50, 0xac, 0x46, 0xb1, 0x73, 0x14, 0x6b, 0xa2, 0x58, 0x8d, 0xea, 0xdc, 0xca, 0x6c, 0x66, - 0x3d, 0x87, 0x57, 0xa7, 0x1a, 0xd9, 0xb9, 0xbb, 0x9c, 0x0e, 0xe5, 0x11, 0x14, 0x82, 0x97, 0xef, - 0xc6, 0x80, 0x7c, 0x28, 0x10, 0xb8, 0x56, 0xf5, 0xb7, 0xe9, 0xd7, 0x16, 0x5d, 0xdb, 0xab, 0x03, - 0x85, 0x5f, 0x08, 0xbd, 0x3e, 0x72, 0xb6, 0xd8, 0x24, 0x09, 0xd9, 0xda, 0xe8, 0x7e, 0x38, 0x99, - 0xc6, 0xc1, 0xcf, 0x69, 0xfc, 0x24, 0xd3, 0xe5, 0xd1, 0x64, 0xc8, 0xa4, 0x2d, 0x78, 0x83, 0xbc, - 0x6f, 0xa0, 0xf9, 0xfa, 0xa2, 0xf7, 0xec, 0x6f, 0x0f, 0xdb, 0x95, 0x72, 0x57, 0x29, 0x07, 0x88, - 0x67, 0xd3, 0xf8, 0xde, 0x1b, 0x91, 0x6b, 0xb5, 0x93, 0x3a, 0x78, 0x3d, 0xd1, 0x0e, 0xd4, 0xc7, - 0xf3, 0x43, 0x32, 0xd2, 0x90, 0xab, 0xe4, 0xa9, 0xb3, 0x45, 0x52, 0x68, 0x44, 0x6d, 0xb2, 0xf4, - 0xc0, 0x47, 0x09, 0xdf, 0xd2, 0xf5, 0xea, 0x39, 0xd0, 0x03, 0xb5, 0x79, 0x2d, 0x21, 0x5b, 0x37, - 0xb6, 0xef, 0xb0, 0xe5, 0x3f, 0x56, 0x6b, 0x99, 0xd7, 0x32, 0xaf, 0xed, 0xf7, 0xba, 0x0f, 0xaa, - 0xf4, 0x67, 0xd3, 0x98, 0x5d, 0x42, 0xda, 0xef, 0x5d, 0x68, 0xdb, 0x23, 0x3f, 0x08, 0xdf, 0xd3, - 0x0d, 0xbf, 0x01, 0x6f, 0x6e, 0x5d, 0xc5, 0xfc, 0x70, 0x61, 0xe6, 0xff, 0x31, 0xef, 0x57, 0xf8, - 0xa6, 0x7a, 0xcd, 0xd6, 0x93, 0x9d, 0xf5, 0x4f, 0xc7, 0x71, 0xf0, 0xfb, 0x38, 0x0e, 0xd2, 0xdb, - 0xf4, 0xe6, 0xe1, 0xc5, 0xde, 0x0f, 0x00, 0xc7, 0xd6, 0x20, 0x6c, 0x7f, 0x27, 0xb4, 0xb5, 0x87, - 0x59, 0xf8, 0x8d, 0xd0, 0xf6, 0x63, 0x5f, 0x85, 0xb0, 0xc7, 0x56, 0x28, 0x12, 0x5b, 0x54, 0xa0, - 0xf3, 0x7c, 0x25, 0xca, 0x3f, 0xa2, 0xa6, 0x41, 0xd7, 0x9c, 0xcc, 0x22, 0x72, 0x3a, 0x8b, 0xc8, - 0xaf, 0x59, 0x44, 0x3e, 0xcf, 0xa3, 0xe0, 0x74, 0x1e, 0x05, 0x3f, 0xe6, 0x51, 0xf0, 0xf2, 0xf0, - 0xd2, 0xcd, 0xba, 0xc2, 0xfd, 0x1a, 0xb6, 0x7d, 0xb3, 0xef, 0xff, 0x09, 0x00, 0x00, 0xff, 0xff, - 0xd8, 0xb9, 0xc3, 0x0e, 0xa5, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Cancel(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Cancel(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.orders.internal.transactions.cancel.Msg/Cancel", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Cancel(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Cancel(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Cancel not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Cancel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Cancel(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.orders.internal.transactions.cancel.Msg/Cancel", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Cancel(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.orders.internal.transactions.cancel.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Cancel", - Handler: _Msg_Cancel_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/orders/internal/transactions/cancel/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.OrderID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.OrderID.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OrderID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OrderID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/orders/internal/transactions/cancel/message_test.go b/modules/orders/internal/transactions/cancel/message_test.go index adfb2704b..67d830444 100644 --- a/modules/orders/internal/transactions/cancel/message_test.go +++ b/modules/orders/internal/transactions/cancel/message_test.go @@ -1,39 +1,279 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package cancel import ( + "reflect" "testing" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/orders/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Cancel_Message(t *testing.T) { - testOrderID := base.NewID("orderID") - testFromID := base.NewID("fromID") +func CreateTestInputForMessages(t *testing.T) (ids.OrderID, ids.IdentityID, sdkTypes.AccAddress, sdkTypes.Msg) { + // testOrderID := baseIDs.NewStringID("orderID") + immutables := baseQualified.NewImmutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + // mutables2 := baseQualified.NewMutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID"), baseData.NewStringData("")))) + + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) + testOrderID := baseIDs.NewOrderID(testClassificationID, immutables) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) require.Nil(t, err) testMessage := newMessage(fromAccAddress, testFromID, testOrderID) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, OrderID: testOrderID}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) + return testOrderID, testFromID, fromAccAddress, testMessage +} + +func Test_messageFromInterface(t *testing.T) { + testOrderID, testFromID, fromAccAddress, testMessage := CreateTestInputForMessages(t) + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{testMessage}, message{fromAccAddress, testFromID, testOrderID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + testOrderID, testFromID, fromAccAddress, testMessage := CreateTestInputForMessages(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + OrderID ids.OrderID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, testFromID, testOrderID}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(testMessage))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + testOrderID, testFromID, fromAccAddress, _ := CreateTestInputForMessages(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + OrderID ids.OrderID + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, testFromID, testOrderID}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + testOrderID, testFromID, fromAccAddress, _ := CreateTestInputForMessages(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + OrderID ids.OrderID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, testFromID, testOrderID}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + testOrderID, testFromID, fromAccAddress, _ := CreateTestInputForMessages(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + OrderID ids.OrderID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testOrderID}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + testOrderID, testFromID, fromAccAddress, _ := CreateTestInputForMessages(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + OrderID ids.OrderID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testOrderID}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + testOrderID, testFromID, fromAccAddress, _ := CreateTestInputForMessages(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + OrderID ids.OrderID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, testFromID, testOrderID}, false}, + {"-ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_newMessage(t *testing.T) { + testOrderID, testFromID, fromAccAddress, _ := CreateTestInputForMessages(t) + + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + orderID ids.OrderID + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, testFromID, testOrderID}, message{fromAccAddress, testFromID, testOrderID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.orderID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/cancel/msg_server.go b/modules/orders/internal/transactions/cancel/msg_server.go deleted file mode 100644 index d46b211d8..000000000 --- a/modules/orders/internal/transactions/cancel/msg_server.go +++ /dev/null @@ -1,66 +0,0 @@ -package cancel - -import ( - "context" - "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/transfer" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -func (msgServer msgServer) Cancel(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := types.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - orders := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(&message.OrderID)) - - order := orders.Get(key.FromID(&message.OrderID)) - if order == nil { - return nil, errors.EntityNotFound - } - - if message.FromID.Compare(order.(mappables.Order).GetMakerID()) != 0 { - return nil, errors.NotAuthorized - } - - metaProperties, Error := supplement.GetMetaPropertiesFromResponse(msgServer.transactionKeeper.supplementAuxiliary.GetKeeper().Help(ctx, supplement.NewAuxiliaryRequest(order.(mappables.Order).GetMakerOwnableSplit()))) - if Error != nil { - return nil, Error - } - - makerOwnableSplitProperty := metaProperties.Get(base.NewID(properties.MakerOwnableSplit)) - if makerOwnableSplitProperty == nil { - return nil, errors.MetaDataError - } - - makerOwnableSplit, Error := makerOwnableSplitProperty.GetMetaFact().GetData().AsDec() - if Error != nil { - return nil, Error - } - - if auxiliaryResponse := msgServer.transactionKeeper.transferAuxiliary.GetKeeper().Help(ctx, transfer.NewAuxiliaryRequest(base.NewID(module.Name), &message.FromID, order.(mappables.Order).GetMakerOwnableID(), makerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - orders.Remove(order) - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} - -var _ MsgServer = msgServer{} diff --git a/modules/orders/internal/transactions/cancel/request.go b/modules/orders/internal/transactions/cancel/request.go index 48cd2b02a..cb63f823c 100644 --- a/modules/orders/internal/transactions/cancel/request.go +++ b/modules/orders/internal/transactions/cancel/request.go @@ -1,22 +1,21 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package cancel import ( "encoding/json" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -27,30 +26,30 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc +// Validate godoc // @Summary cancel order transaction -// @Descrption cancel order transaction +// @Description cancel order transaction // @Accept text/plain // @Produce json // @Tags Orders -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body transactionRequest true "Request body to cancel order" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /orders/cancel [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.OrderID), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.OrderID), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -59,24 +58,33 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + orderID, err := baseIDs.ReadOrderID(transactionRequest.OrderID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.OrderID), + fromID, + orderID, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} } - func newTransactionRequest(baseReq rest.BaseReq, fromID string, orderID string) helpers.TransactionRequest { return transactionRequest{ BaseReq: baseReq, diff --git a/modules/orders/internal/transactions/cancel/request_test.go b/modules/orders/internal/transactions/cancel/request_test.go index 43677682f..d6d8d537d 100644 --- a/modules/orders/internal/transactions/cancel/request_test.go +++ b/modules/orders/internal/transactions/cancel/request_test.go @@ -1,71 +1,282 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package cancel import ( "encoding/json" + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/spf13/viper" "github.com/stretchr/testify/require" - "testing" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + basehelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" ) -func Test_Cancel_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.OrderID}) - cliContext := context.NewCLIContext().WithCodec(Codec) +var ( + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = types.AccAddressFromBech32(fromAddress) + immutables = baseQualified.NewImmutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables = baseQualified.NewMutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) + testClassificationID = baseIDs.NewClassificationID(immutables, mutables) + testFromID = baseIDs.NewIdentityID(testClassificationID, immutables) + testOrderID = baseIDs.NewOrderID(testClassificationID, immutables) + testOrderID1 = baseIDs.PrototypeOrderID() + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} +) - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "orderID") +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + orderID string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, testFromID.String(), testOrderID.String()}, newTransactionRequest(testBaseRequest, testFromID.String(), testOrderID.String())}, + {"+ve", args{testBaseRequest, testFromID.String(), testOrderID1.String()}, newTransactionRequest(testBaseRequest, testFromID.String(), testOrderID1.String())}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.orderID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", OrderID: "orderID"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", OrderID: ""}, requestFromCLI) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := basehelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.OrderID, constants.FromID}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.FromID.GetName(), testFromID.String()) + viper.Set(constants.OrderID.GetName(), testOrderID.String()) + type fields struct { + BaseReq rest.BaseReq + FromID string + OrderID string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testOrderID.String()}, args{cliCommand, cliContext}, newTransactionRequest(testBaseRequest, testFromID.String(), testOrderID.String()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_transactionRequest_FromJSON(t *testing.T) { + jsonMessage, err := json.Marshal(newTransactionRequest(testBaseRequest, testFromID.String(), testOrderID.String())) + require.NoError(t, err) + jsonMessage1, err := json.Marshal(newTransactionRequest(testBaseRequest, testFromID.String(), testOrderID1.String())) + require.NoError(t, err) - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) + type fields struct { + BaseReq rest.BaseReq + FromID string + OrderID string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testOrderID.String()}, args{jsonMessage}, transactionRequest{testBaseRequest, testFromID.String(), testOrderID.String()}, false}, + {"+ve with nil", fields{testBaseRequest, testFromID.String(), testOrderID1.String()}, args{jsonMessage1}, transactionRequest{testBaseRequest, testFromID.String(), testOrderID1.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + OrderID string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testOrderID.String()}, testBaseRequest}, + {"+ve with nil", fields{testBaseRequest, testFromID.String(), testOrderID1.String()}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("orderID")), msg) - require.Nil(t, Error) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + OrderID string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testOrderID.String()}, newMessage(fromAccAddress, testFromID, testOrderID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error := newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", "orderID").MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + OrderID string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testOrderID.String()}, args{codec.New()}}, + {"+ve with nil", fields{testBaseRequest, testFromID.String(), testOrderID1.String()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + OrderID string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testOrderID.String()}, false}, + {"+ve with nil", fields{testBaseRequest, testFromID.String(), testOrderID1.String()}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/orders/internal/transactions/cancel/response.go b/modules/orders/internal/transactions/cancel/response.go new file mode 100644 index 000000000..3308a7f06 --- /dev/null +++ b/modules/orders/internal/transactions/cancel/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package cancel + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/orders/internal/transactions/cancel/transaction.go b/modules/orders/internal/transactions/cancel/transaction.go new file mode 100644 index 000000000..2c881186e --- /dev/null +++ b/modules/orders/internal/transactions/cancel/transaction.go @@ -0,0 +1,21 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package cancel + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "cancel", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + constants.OrderID, + constants.FromID, +) diff --git a/modules/orders/internal/transactions/define/keeper.go b/modules/orders/internal/transactions/define/keeper.go new file mode 100644 index 000000000..29be9f807 --- /dev/null +++ b/modules/orders/internal/transactions/define/keeper.go @@ -0,0 +1,74 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/define" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/super" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties/constants" + "github.com/AssetMantle/modules/schema/qualified/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + defineAuxiliary helpers.Auxiliary + superAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + immutables := base.NewImmutables(baseLists.NewPropertyList(append(append(message.ImmutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...), constants.ExchangeRateProperty, constants.CreationHeightProperty, constants.MakerOwnableIDProperty, constants.TakerOwnableIDProperty, constants.MakerIDProperty, constants.TakerIDProperty)...)) + + mutables := base.NewMutables(baseLists.NewPropertyList(append(append(message.MutableMetaProperties.GetList(), message.MutableProperties.GetList()...), constants.ExpiryHeightProperty, constants.MakerOwnableSplitProperty)...)) + + classificationID, err := define.GetClassificationIDFromResponse(transactionKeeper.defineAuxiliary.GetKeeper().Help(context, define.NewAuxiliaryRequest(immutables, mutables))) + if err != nil { + return newTransactionResponse(err) + } + + if auxiliaryResponse := transactionKeeper.superAuxiliary.GetKeeper().Help(context, super.NewAuxiliaryRequest(classificationID, message.FromID, mutables)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case define.Auxiliary.GetName(): + transactionKeeper.defineAuxiliary = value + case super.Auxiliary.GetName(): + transactionKeeper.superAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/orders/internal/transactions/define/keeper_test.go b/modules/orders/internal/transactions/define/keeper_test.go index 49d2d42ce..fffbff11c 100644 --- a/modules/orders/internal/transactions/define/keeper_test.go +++ b/modules/orders/internal/transactions/define/keeper_test.go @@ -1,54 +1,62 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/test" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/define" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/super" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/define" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/super" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +var ( + defineAuxiliary helpers.Auxiliary + superAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary ) type TestKeepers struct { - OrdersKeeper helpers.TransactionKeeper + DefineKeeper helpers.TransactionKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func CreateTestInput(t *testing.T) (types.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + storeKey := types.NewKVStoreKey("test") + paramsStoreKey := types.NewKVStoreKey("testParams") + paramsTransientStoreKeys := types.NewTransientStoreKey("testParamsTransient") Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) paramsKeeper := params.NewKeeper( Codec, @@ -59,105 +67,130 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + commitMultiStore.MountStoreWithDB(storeKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, types.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) - context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + defineAuxiliary = define.AuxiliaryMock.Initialize(Mapper, Parameters) + superAuxiliary = super.AuxiliaryMock.Initialize(Mapper, Parameters) + + context := types.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) - scrubAuxiliary := scrub.AuxiliaryMock.Initialize(Mapper, Parameters) - defineAuxiliary := define.AuxiliaryMock.Initialize(Mapper, Parameters) - superAuxiliary := super.AuxiliaryMock.Initialize(Mapper, Parameters) - verifyAuxiliary := verify.AuxiliaryMock.Initialize(Mapper, Parameters) keepers := TestKeepers{ - OrdersKeeper: keeperPrototype().Initialize(Mapper, Parameters, - []interface{}{scrubAuxiliary, verifyAuxiliary, - defineAuxiliary, superAuxiliary}).(helpers.TransactionKeeper), + DefineKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), } - return context, keepers + return context, keepers, Mapper, Parameters } -func Test_transactionKeeper_Transact(t *testing.T) { +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - context, keepers := CreateTestInput(t) - immutableMetaProperties, Error := base.ReadMetaProperties("defaultImmutableMeta1:S|defaultImmutableMeta1") - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties("defaultImmutable1:S|defaultImmutable1") - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties("defaultMutableMeta1:S|defaultMutableMeta1") - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties("defaultMutable1:S|defaultMutable1") - require.Equal(t, nil, Error) - superMockErrorProperties, Error := base.ReadMetaProperties("superError:S|mockError") - require.Equal(t, nil, Error) - scrubMockErrorProperties, Error := base.ReadMetaProperties("scrubError:S|mockError") - require.Equal(t, nil, Error) - gt22Properties, Error := base.ReadMetaProperties("0:S|0,1:S|1,2:S|2,3:S|3,4:S|4,5:S|5,6:S|6,7:S|7,8:S|8,9:S|9,10:S|10,11:S|11,12:S|12,13:S|13,14:S|14,15:S|15,16:S|16,17:S|17,18:S|18,19:S|19,20:S|20,21:S|21") - require.Equal(t, nil, Error) - verifyMockErrorAddress := sdkTypes.AccAddress("verifyError") - defaultAddr := sdkTypes.AccAddress("addr") - defaultIdentityID := base.NewID("fromID") - rateID := base.NewID(sdkTypes.OneDec().String()) - creationID := base.NewID("0") - orderID := key.NewOrderID(base.NewID("classificationID"), base.NewID("makerOwnableID"), base.NewID("takerOwnableID"), rateID, creationID, defaultIdentityID, base.NewProperties()) - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(orderID, base.NewProperties(), base.NewProperties())) - - t.Run("PositiveCase", func(t *testing.T) { - want := newTransactionResponse(nil) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, immutableMetaProperties, - immutableProperties, mutableMetaProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - Identity mock error", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(verifyMockErrorAddress, defaultIdentityID, immutableMetaProperties, - immutableProperties, mutableMetaProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - immutable scrub error", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, scrubMockErrorProperties, - immutableProperties, mutableMetaProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - mutable scrub error", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, immutableMetaProperties, - immutableProperties, scrubMockErrorProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - conform error", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(errors.InvalidRequest) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, immutableMetaProperties, - immutableProperties, gt22Properties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - super error", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, immutableMetaProperties, - immutableProperties, superMockErrorProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := CreateTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + defineAuxiliary helpers.Auxiliary + superAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve with nil", fields{}, args{}, transactionKeeper{}}, + {"+ve", fields{Mapper, Parameters, defineAuxiliary, superAuxiliary, authenticateAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, defineAuxiliary, superAuxiliary, authenticateAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + defineAuxiliary: tt.fields.defineAuxiliary, + superAuxiliary: tt.fields.superAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters := CreateTestInput(t) + mutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + mutableProperties := baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + immutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + immutableProperties := baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + immutablesMeta := baseQualified.NewImmutables(immutableMetaProperties) + mutablesMeta := baseQualified.NewMutables(mutableMetaProperties) + testClassificationID := baseIDs.NewClassificationID(immutablesMeta, mutablesMeta) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutablesMeta) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + testIdentity := baseDocuments.NewIdentity(testClassificationID, immutablesMeta, mutablesMeta) + testIdentity.ProvisionAddress([]types.AccAddress{fromAccAddress}...) + testOrder := baseDocuments.NewOrder(testClassificationID, immutablesMeta, mutablesMeta) + keepers.DefineKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testOrder)) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + defineAuxiliary helpers.Auxiliary + superAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + context types.Context + msg types.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, Parameters, defineAuxiliary, superAuxiliary, authenticateAuxiliary}, args{context, newMessage(fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)}, newTransactionResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + defineAuxiliary: tt.fields.defineAuxiliary, + superAuxiliary: tt.fields.superAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/define/message.go b/modules/orders/internal/transactions/define/message.go index a5c499f79..7270e14a0 100644 --- a/modules/orders/internal/transactions/define/message.go +++ b/modules/orders/internal/transactions/define/message.go @@ -1,72 +1,84 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ImmutableMetaProperties lists.PropertyList `json:"immutableMetaProperties" valid:"required~required field immutableMetaProperties missing"` + ImmutableProperties lists.PropertyList `json:"immutableProperties" valid:"required~required field immutableProperties missing"` + MutableMetaProperties lists.PropertyList `json:"mutableMetaProperties" valid:"required~required field mutableMetaProperties missing"` + MutableProperties lists.PropertyList `json:"mutableProperties" valid:"required~required field mutableProperties missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + if len(message.ImmutableMetaProperties.GetList()) == 0 { + message.ImmutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.ImmutableProperties.GetList()) == 0 { + message.ImmutableProperties = base.NewPropertyList(nil) + } + if len(message.MutableMetaProperties.GetList()) == 0 { + message.MutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.MutableProperties.GetList()) == 0 { + message.MutableProperties = base.NewPropertyList(nil) + } + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, immutableMetaProperties types.MetaProperties, immutableProperties types.Properties, mutableMetaProperties types.MetaProperties, mutableProperties types.Properties) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - ImmutableMetaProperties: *base.NewMetaProperties(immutableMetaProperties.GetList()...), - ImmutableProperties: *base.NewProperties(immutableProperties.GetList()...), - MutableMetaProperties: *base.NewMetaProperties(mutableMetaProperties.GetList()...), - MutableProperties: *base.NewProperties(mutableProperties.GetList()...), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, immutableMetaProperties lists.PropertyList, immutableProperties lists.PropertyList, mutableMetaProperties lists.PropertyList, mutableProperties lists.PropertyList) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + ImmutableMetaProperties: immutableMetaProperties, + ImmutableProperties: immutableProperties, + MutableMetaProperties: mutableMetaProperties, + MutableProperties: mutableProperties, } } diff --git a/modules/orders/internal/transactions/define/message.pb.go b/modules/orders/internal/transactions/define/message.pb.go deleted file mode 100644 index 3c07e3f1c..000000000 --- a/modules/orders/internal/transactions/define/message.pb.go +++ /dev/null @@ -1,775 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/transactions/define/message.proto - -package define - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - ImmutableMetaProperties base.MetaProperties `protobuf:"bytes,3,opt,name=immutable_meta_properties,json=immutableMetaProperties,proto3" json:"immutable_meta_properties" valid:"required~required field ImmutableMetaProperties missing"` - ImmutableProperties base.Properties `protobuf:"bytes,4,opt,name=immutable_properties,json=immutableProperties,proto3" json:"immutable_properties" valid:"required~required field ImmutableProperties missing"` - MutableMetaProperties base.MetaProperties `protobuf:"bytes,5,opt,name=mutable_meta_properties,json=mutableMetaProperties,proto3" json:"mutable_meta_properties" valid:"required~required field MutableMetaProperties missing"` - MutableProperties base.Properties `protobuf:"bytes,6,opt,name=mutable_properties,json=mutableProperties,proto3" json:"mutable_properties" valid:"required~required field MutableProperties missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_1e2ca568711bc072, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1e2ca568711bc072, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.orders.internal.transactions.define.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.orders.internal.transactions.define.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/orders/internal/transactions/define/message.proto", fileDescriptor_1e2ca568711bc072) -} - -var fileDescriptor_1e2ca568711bc072 = []byte{ - // 565 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x95, 0x31, 0x6f, 0xd3, 0x40, - 0x1c, 0xc5, 0x7d, 0xb4, 0xa4, 0xe5, 0x98, 0x70, 0x5b, 0x35, 0x64, 0xb0, 0xa3, 0x48, 0x48, 0x15, - 0x82, 0x3b, 0x11, 0xa4, 0x4a, 0xb4, 0x42, 0x28, 0x21, 0x05, 0x45, 0x28, 0xa2, 0x2a, 0x9d, 0x58, - 0x22, 0xc7, 0xf7, 0x8f, 0x7b, 0x22, 0xf6, 0x99, 0xbb, 0x0b, 0x88, 0x01, 0x66, 0x46, 0xf8, 0x04, - 0x54, 0x48, 0x2c, 0x4c, 0x4c, 0x7c, 0x86, 0x8e, 0x9d, 0x10, 0x62, 0x88, 0x50, 0xb2, 0x30, 0xf7, - 0x13, 0xa0, 0x38, 0x8e, 0xe2, 0x26, 0x86, 0xb8, 0xed, 0x94, 0x8b, 0xfd, 0xff, 0xbf, 0xf7, 0xf3, - 0xb3, 0xf4, 0x8c, 0xeb, 0x21, 0x48, 0xc5, 0x95, 0x86, 0xc0, 0x85, 0xa6, 0x62, 0x2f, 0xa8, 0x2f, - 0x58, 0xb7, 0x03, 0x8a, 0x0a, 0xc9, 0x40, 0x2a, 0xca, 0x03, 0x0d, 0x32, 0x70, 0x3a, 0x54, 0x4b, - 0x27, 0x50, 0x8e, 0xab, 0xb9, 0x08, 0x14, 0x65, 0xd0, 0xe6, 0x01, 0x50, 0x1f, 0x94, 0x72, 0x3c, - 0x20, 0xa1, 0x14, 0x5a, 0x98, 0xdb, 0x53, 0x52, 0x24, 0x96, 0x22, 0x23, 0x29, 0x32, 0x96, 0x22, - 0x49, 0x29, 0x32, 0x92, 0x2a, 0xac, 0x7a, 0xc2, 0x13, 0x91, 0x0e, 0x1d, 0x9e, 0x46, 0x92, 0x85, - 0x9b, 0xd3, 0x74, 0xca, 0x3d, 0x00, 0xdf, 0xa1, 0xfa, 0x4d, 0x08, 0x8a, 0xb6, 0x1c, 0x05, 0x94, - 0xb3, 0x78, 0xb6, 0x3c, 0x7f, 0x36, 0x94, 0x22, 0x04, 0xa9, 0x39, 0xa8, 0x78, 0x67, 0x73, 0xfe, - 0x8e, 0x0f, 0xda, 0xd9, 0x9d, 0xda, 0x2b, 0xfd, 0x58, 0xc2, 0x4b, 0x8d, 0xd1, 0xc3, 0x9b, 0x1f, - 0x11, 0x5e, 0x6c, 0x4b, 0xe1, 0xe7, 0x51, 0x11, 0x6d, 0x5c, 0xa9, 0xbe, 0x3d, 0xea, 0xd9, 0xc6, - 0xaf, 0x9e, 0xbd, 0xe3, 0x71, 0x7d, 0xd0, 0x6d, 0x11, 0x57, 0xf8, 0x34, 0xe1, 0xf2, 0x34, 0x80, - 0xe4, 0xdf, 0x67, 0xb5, 0x27, 0xb3, 0x9e, 0xa4, 0xe2, 0xba, 0x15, 0xc6, 0x24, 0x28, 0x75, 0xd2, - 0xb3, 0x6f, 0xbd, 0x72, 0x3a, 0x9c, 0x6d, 0x95, 0x24, 0xbc, 0xec, 0x72, 0x09, 0xec, 0xdd, 0xf8, - 0x50, 0x6c, 0x73, 0xe8, 0xb0, 0xe2, 0x23, 0x29, 0xfc, 0xa2, 0xcf, 0x95, 0xe2, 0x81, 0x57, 0xda, - 0x8b, 0x50, 0xcc, 0xd7, 0x78, 0x79, 0xf8, 0xdb, 0xe4, 0x4d, 0x96, 0xbf, 0x54, 0x44, 0x1b, 0x57, - 0xcb, 0x37, 0xc8, 0xf4, 0xdb, 0x19, 0xd9, 0x92, 0xc8, 0x96, 0x44, 0xb6, 0xf5, 0x5a, 0x75, 0x73, - 0x48, 0x7f, 0xd2, 0xb3, 0x49, 0x06, 0xd3, 0x7a, 0x6d, 0x62, 0x9b, 0x6b, 0x47, 0x17, 0xcc, 0xef, - 0x08, 0x5f, 0xe7, 0xbe, 0xdf, 0xd5, 0x4e, 0xab, 0x03, 0xcd, 0x61, 0x76, 0xcd, 0x49, 0xe8, 0xf9, - 0x85, 0x08, 0xe5, 0x4e, 0x06, 0x94, 0xc6, 0xa9, 0xd4, 0xab, 0x8f, 0x63, 0xac, 0x07, 0x73, 0xb0, - 0xea, 0x63, 0xeb, 0xd3, 0xfb, 0x13, 0xce, 0x75, 0x9e, 0x3e, 0x61, 0x7e, 0x41, 0x78, 0x75, 0x02, - 0x9e, 0x60, 0x5e, 0x8c, 0x98, 0x6f, 0x67, 0x60, 0x4e, 0xf0, 0x3e, 0x8c, 0x79, 0xb7, 0xb3, 0xf2, - 0xa6, 0xb1, 0xae, 0xf0, 0xd9, 0xbb, 0xe6, 0x37, 0x84, 0xd7, 0xff, 0x15, 0xef, 0xe5, 0xf3, 0xc6, - 0xbb, 0x13, 0xe3, 0xde, 0x9f, 0x83, 0xdb, 0xf8, 0x7f, 0xb8, 0x6b, 0xe9, 0xd1, 0x7e, 0x42, 0xd8, - 0x4c, 0x09, 0x36, 0x77, 0x9e, 0x60, 0x2b, 0x31, 0xe9, 0xbd, 0x6c, 0xa4, 0x69, 0x94, 0xd7, 0x66, - 0x42, 0xdd, 0x5a, 0x7e, 0x7f, 0x68, 0x1b, 0x7f, 0x0e, 0x6d, 0xa3, 0xb4, 0x86, 0x57, 0xf6, 0x27, - 0xed, 0xb4, 0x07, 0x2a, 0x14, 0x81, 0x82, 0xf2, 0x57, 0x84, 0x17, 0x1a, 0xca, 0x33, 0x3f, 0x23, - 0x9c, 0xab, 0x45, 0x85, 0x65, 0xd6, 0xc8, 0x05, 0xea, 0x8e, 0xc4, 0xe5, 0x51, 0xd8, 0xbd, 0x90, - 0x4a, 0x0a, 0x6a, 0xc9, 0xa8, 0x06, 0x47, 0x7d, 0x0b, 0x1d, 0xf7, 0x2d, 0xf4, 0xbb, 0x6f, 0xa1, - 0x0f, 0x03, 0xcb, 0x38, 0x1e, 0x58, 0xc6, 0xcf, 0x81, 0x65, 0x3c, 0xdf, 0xcf, 0xdc, 0x49, 0x67, - 0xf8, 0x0a, 0xb4, 0x72, 0x51, 0x27, 0xde, 0xfd, 0x1b, 0x00, 0x00, 0xff, 0xff, 0x17, 0x84, 0xcf, - 0x9d, 0x4b, 0x06, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Define(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Define(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.orders.internal.transactions.define.Msg/Define", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Define(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Define(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Define not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Define_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Define(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.orders.internal.transactions.define.Msg/Define", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Define(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.orders.internal.transactions.define.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Define", - Handler: _Msg_Define_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/orders/internal/transactions/define/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.MutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.ImmutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ImmutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/orders/internal/transactions/define/message_test.go b/modules/orders/internal/transactions/define/message_test.go index b177fbbfc..357b817d5 100644 --- a/modules/orders/internal/transactions/define/message_test.go +++ b/modules/orders/internal/transactions/define/message_test.go @@ -1,46 +1,284 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/AssetMantle/modules/utilities/transaction" + + "github.com/cosmos/cosmos-sdk/codec" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" ) -func Test_Define_Message(t *testing.T) { - - testFromID := base.NewID("fromID") - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - immutableMetaProperties, Error := base.ReadMetaProperties("defaultImmutableMeta1:S|defaultImmutableMeta1") - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties("defaultImmutable1:S|defaultImmutable1") - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties("defaultMutableMeta1:S|defaultMutableMeta1") - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties("defaultMutable1:S|defaultMutable1") - require.Equal(t, nil, Error) - - testMessage := newMessage(fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, ImmutableMetaProperties: immutableMetaProperties, ImmutableProperties: immutableProperties, MutableMetaProperties: mutableMetaProperties, MutableProperties: mutableProperties}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +var ( + testMessage = newMessage(fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties) +) + +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{testMessage}, message{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(testMessage))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, false}, + {"-ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + immutableMetaProperties lists.PropertyList + immutableProperties lists.PropertyList + mutableMetaProperties lists.PropertyList + mutableProperties lists.PropertyList + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, message{fromAccAddress, testFromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/define/msg_server.go b/modules/orders/internal/transactions/define/msg_server.go deleted file mode 100644 index 706e31da0..000000000 --- a/modules/orders/internal/transactions/define/msg_server.go +++ /dev/null @@ -1,53 +0,0 @@ -package define - -import ( - "context" - "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/define" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/super" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -func (msgServer msgServer) Define(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := types.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - immutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(message.ImmutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - immutableProperties := base.NewProperties(append(immutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...)...) - - mutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(message.MutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - mutableProperties := base.NewProperties(append(mutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...) - - classificationID, Error := define.GetClassificationIDFromResponse(msgServer.transactionKeeper.defineAuxiliary.GetKeeper().Help(ctx, define.NewAuxiliaryRequest(immutableProperties, mutableProperties))) - if Error != nil { - return nil, Error - } - - if auxiliaryResponse := msgServer.transactionKeeper.superAuxiliary.GetKeeper().Help(ctx, super.NewAuxiliaryRequest(classificationID, &message.FromID, mutableProperties)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} - -var _ MsgServer = msgServer{} diff --git a/modules/orders/internal/transactions/define/request.go b/modules/orders/internal/transactions/define/request.go index 632bcff58..b21eeeca2 100644 --- a/modules/orders/internal/transactions/define/request.go +++ b/modules/orders/internal/transactions/define/request.go @@ -1,22 +1,22 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define import ( "encoding/json" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -30,33 +30,33 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary define order transaction -// @Descrption define order transaction +// Validate godoc +// @Summary Define order transaction +// @Description Define order transaction // @Accept text/plain // @Produce json // @Tags Orders -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body body transactionRequest true "Request body to define an order" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /orders/define [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ImmutableMetaProperties), - cliCommand.ReadString(flags.ImmutableProperties), - cliCommand.ReadString(flags.MutableMetaProperties), - cliCommand.ReadString(flags.MutableProperties), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ImmutableMetaProperties), + cliCommand.ReadString(constants.ImmutableProperties), + cliCommand.ReadString(constants.MutableMetaProperties), + cliCommand.ReadString(constants.MutableProperties), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -65,47 +65,53 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err } - immutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.ImmutableMetaProperties) - if Error != nil { - return nil, Error + immutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableMetaProperties) + if err != nil { + return nil, err } - immutableProperties, Error := base.ReadProperties(transactionRequest.ImmutableProperties) - if Error != nil { - return nil, Error + immutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableProperties) + if err != nil { + return nil, err } + immutableProperties = immutableProperties.ScrubData() - mutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.MutableMetaProperties) - if Error != nil { - return nil, Error + mutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableMetaProperties) + if err != nil { + return nil, err } - mutableProperties, Error := base.ReadProperties(transactionRequest.MutableProperties) - if Error != nil { - return nil, Error + mutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableProperties) + if err != nil { + return nil, err + } + mutableProperties = mutableProperties.ScrubData() + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), + fromID, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} } - func newTransactionRequest(baseReq rest.BaseReq, fromID string, immutableMetaProperties string, immutableProperties string, mutableMetaProperties string, mutableProperties string) helpers.TransactionRequest { return transactionRequest{ BaseReq: baseReq, diff --git a/modules/orders/internal/transactions/define/request_test.go b/modules/orders/internal/transactions/define/request_test.go index a96b52d4c..5ab0c1761 100644 --- a/modules/orders/internal/transactions/define/request_test.go +++ b/modules/orders/internal/transactions/define/request_test.go @@ -1,102 +1,320 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package define import ( "encoding/json" + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/spf13/viper" "github.com/stretchr/testify/require" - "testing" -) - -func Test_Define_Request(t *testing.T) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.ImmutableMetaProperties, flags.ImmutableProperties, flags.MutableMetaProperties, flags.MutableProperties}) - cliContext := context.NewCLIContext().WithCodec(Codec) - - immutableMetaPropertiesString := "defaultImmutableMeta1:S|defaultImmutableMeta1" - immutablePropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" - mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" - mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - - immutableMetaProperties, Error := base.ReadMetaProperties(immutableMetaPropertiesString) - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties(immutablePropertiesString) - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties(mutableMetaPropertiesString) - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties(mutablePropertiesString) - require.Equal(t, nil, Error) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString) - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) - - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ImmutableMetaProperties: "", ImmutableProperties: "", MutableMetaProperties: "", MutableProperties: ""}, requestFromCLI) + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + "github.com/AssetMantle/modules/schema/qualified/base" +) - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +var ( + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = types.AccAddressFromBech32(fromAddress) - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) + immutableMetaPropertiesString = "defaultImmutableMeta1:S|defaultImmutableMeta1" + immutablePropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" + mutableMetaPropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" + mutablePropertiesString = "defaultMutable1:S|defaultMutable1" + immutableMetaProperties, _ = utilities.ReadMetaPropertyList(immutableMetaPropertiesString) + immutableProperties, _ = utilities.ReadMetaPropertyList(immutablePropertiesString) + mutableMetaProperties, _ = utilities.ReadMetaPropertyList(mutableMetaPropertiesString) + mutableProperties, _ = utilities.ReadMetaPropertyList(mutablePropertiesString) + immutables = base.NewImmutables(immutableProperties) + mutables = base.NewMutables(mutableProperties) + testClassificationID = baseIDs.NewClassificationID(immutables, mutables) + testFromID = baseIDs.NewIdentityID(testClassificationID, immutables) + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} +) - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + immutableMetaProperties string + immutableProperties string + mutableMetaProperties string + mutableProperties string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, testFromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, newTransactionRequest(testBaseRequest, testFromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties), msg) - require.Nil(t, Error) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.ImmutableProperties, constants.FromID, constants.ImmutableMetaProperties, constants.MutableMetaProperties, constants.MutableProperties}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.ImmutableProperties.GetName(), immutablePropertiesString) + viper.Set(constants.ImmutableMetaProperties.GetName(), immutableMetaPropertiesString) + viper.Set(constants.MutableMetaProperties.GetName(), mutableMetaPropertiesString) + viper.Set(constants.MutableProperties.GetName(), mutablePropertiesString) + viper.Set(constants.FromID.GetName(), testFromID.String()) + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, cliContext}, newTransactionRequest(testBaseRequest, testFromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "randomString", immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_FromJSON(t *testing.T) { + jsonMessage, err := json.Marshal(newTransactionRequest(testBaseRequest, testFromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString)) + require.NoError(t, err) + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{jsonMessage}, transactionRequest{testBaseRequest, testFromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", immutableMetaPropertiesString, "randomString", mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", immutableMetaPropertiesString, immutablePropertiesString, "randomString", mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, newMessage(fromAccAddress, testFromID, immutableMetaProperties, immutableProperties.ScrubData(), mutableMetaProperties, mutableProperties.ScrubData()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, "randomString").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/orders/internal/transactions/define/response.go b/modules/orders/internal/transactions/define/response.go new file mode 100644 index 000000000..bd134e694 --- /dev/null +++ b/modules/orders/internal/transactions/define/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/orders/internal/transactions/define/transaction.go b/modules/orders/internal/transactions/define/transaction.go new file mode 100644 index 000000000..f4c9961d7 --- /dev/null +++ b/modules/orders/internal/transactions/define/transaction.go @@ -0,0 +1,25 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package define + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "define", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.ImmutableMetaProperties, + constants.ImmutableProperties, + constants.MutableMetaProperties, + constants.MutableProperties, +) diff --git a/modules/orders/internal/transactions/deputize/keeper.go b/modules/orders/internal/transactions/deputize/keeper.go new file mode 100644 index 000000000..d72f4b712 --- /dev/null +++ b/modules/orders/internal/transactions/deputize/keeper.go @@ -0,0 +1,57 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/deputize" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + deputizeAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + if auxiliaryResponse := transactionKeeper.deputizeAuxiliary.GetKeeper().Help(context, deputize.NewAuxiliaryRequest(message.FromID, message.ToID, message.ClassificationID, message.MaintainedProperties, message.CanMintAsset, message.CanBurnAsset, message.CanRenumerateAsset, message.CanAddMaintainer, message.CanRemoveMaintainer, message.CanMutateMaintainer)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + return newTransactionResponse(nil) +} +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case deputize.Auxiliary.GetName(): + transactionKeeper.deputizeAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(constants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/orders/internal/transactions/deputize/keeper_test.go b/modules/orders/internal/transactions/deputize/keeper_test.go index 76365a04d..c4edcf6e3 100644 --- a/modules/orders/internal/transactions/deputize/keeper_test.go +++ b/modules/orders/internal/transactions/deputize/keeper_test.go @@ -1,51 +1,60 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/test" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/deputize" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/deputize" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +var ( + authenticateAuxiliary helpers.Auxiliary + deputizeAuxiliary helpers.Auxiliary ) type TestKeepers struct { - OrdersKeeper helpers.TransactionKeeper + DeputizeKeeper helpers.TransactionKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func CreateTestInput(t *testing.T) (types.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + storeKey := types.NewKVStoreKey("test") + paramsStoreKey := types.NewKVStoreKey("testParams") + paramsTransientStoreKeys := types.NewTransientStoreKey("testParamsTransient") Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) paramsKeeper := params.NewKeeper( Codec, @@ -56,61 +65,128 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + commitMultiStore.MountStoreWithDB(storeKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, types.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + deputizeAuxiliary = deputize.AuxiliaryMock.Initialize(Mapper, Parameters) - context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + context := types.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) - verifyAuxiliary := verify.AuxiliaryMock.Initialize(Mapper, Parameters) - deputizeAuxiliary := deputize.AuxiliaryMock.Initialize(Mapper, Parameters) keepers := TestKeepers{ - OrdersKeeper: keeperPrototype().Initialize(Mapper, Parameters, - []interface{}{deputizeAuxiliary, verifyAuxiliary}).(helpers.TransactionKeeper), + DeputizeKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), } - return context, keepers + return context, keepers, Mapper, Parameters } -func Test_transactionKeeper_Transact(t *testing.T) { +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := CreateTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + deputizeAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve with nil", fields{}, args{}, transactionKeeper{}}, + {"+ve", fields{Mapper, Parameters, authenticateAuxiliary, deputizeAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, authenticateAuxiliary, deputizeAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + deputizeAuxiliary: tt.fields.deputizeAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} - context, keepers := CreateTestInput(t) - maintainedProperties, Error := base.ReadProperties("maintainedProperties:S|maintainedProperties") - require.Equal(t, nil, Error) - conformMockErrorProperties, Error := base.ReadProperties("deputizeError:S|mockError") - require.Equal(t, nil, Error) - defaultAddr := sdkTypes.AccAddress("addr") - verifyMockErrorAddress := sdkTypes.AccAddress("verifyError") - defaultIdentityID := base.NewID("fromIdentityID") - toID := base.NewID("toID") - toID2 := base.NewID("toID2") - classificationID := base.NewID("ClassificationID") - - t.Run("PositiveCase", func(t *testing.T) { - want := newTransactionResponse(nil) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, toID, classificationID, - maintainedProperties, true, true, true)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - verify identity fail", func(t *testing.T) { - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(verifyMockErrorAddress, defaultIdentityID, toID, classificationID, - maintainedProperties, true, true, true)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - conform mock error", func(t *testing.T) { - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, toID2, classificationID, - conformMockErrorProperties, true, true, true)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters := CreateTestInput(t) + mutableMetaProperties := baseLists.NewPropertyList( + baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())), + ) + immutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + immutablesMeta := baseQualified.NewImmutables(immutableMetaProperties) + mutablesMeta := baseQualified.NewMutables(mutableMetaProperties) + testClassificationID := baseIDs.NewClassificationID(immutablesMeta, mutablesMeta) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutablesMeta) + mutableMetaProperties.Mutate( + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(testFromID)), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(testFromID))) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + testIdentity := baseDocuments.NewIdentity(testClassificationID, immutablesMeta, mutablesMeta) + testIdentity.ProvisionAddress([]types.AccAddress{fromAccAddress}...) + testOrder := baseDocuments.NewOrder(testClassificationID, immutablesMeta, mutablesMeta) + keepers.DeputizeKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testOrder)) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + deputizeAuxiliary helpers.Auxiliary + } + type args struct { + context types.Context + msg types.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, Parameters, authenticateAuxiliary, deputizeAuxiliary}, args{context, newMessage(fromAccAddress, testFromID, testFromID, testClassificationID, mutableMetaProperties, true, true, true, true, true, true)}, newTransactionResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + deputizeAuxiliary: tt.fields.deputizeAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/deputize/message.go b/modules/orders/internal/transactions/deputize/message.go index ccedbc774..ba5479779 100644 --- a/modules/orders/internal/transactions/deputize/message.go +++ b/modules/orders/internal/transactions/deputize/message.go @@ -1,74 +1,85 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ToID ids.IdentityID `json:"toID" valid:"required~required field toID missing"` + ids.ClassificationID `json:"classificationID" valid:"required~required field classificationID missing"` + MaintainedProperties lists.PropertyList `json:"maintainedProperties" valid:"required~required field maintainedProperties missing"` + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + if len(message.MaintainedProperties.GetList()) == 0 { + message.MaintainedProperties = base.NewPropertyList(nil) + } + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, toID types.ID, classificationID types.ID, maintainedProperties types.Properties, addMaintainer bool, removeMaintainer bool, mutateMaintainer bool) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - ToID: *base.NewID(toID.String()), - ClassificationID: *base.NewID(classificationID.String()), - MaintainedProperties: *base.NewProperties(maintainedProperties.GetList()...), - AddMaintainer: addMaintainer, - RemoveMaintainer: removeMaintainer, - MutateMaintainer: mutateMaintainer, +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, toID ids.IdentityID, classificationID ids.ClassificationID, maintainedProperties lists.PropertyList, canMintAsset bool, canBurnAsset bool, canRenumerateAsset bool, canAddMaintainer bool, canRemoveMaintainer bool, canMutateMaintainer bool) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + ToID: toID, + ClassificationID: classificationID, + MaintainedProperties: maintainedProperties, + CanMintAsset: canMintAsset, + CanBurnAsset: canBurnAsset, + CanRenumerateAsset: canRenumerateAsset, + CanAddMaintainer: canAddMaintainer, + CanRemoveMaintainer: canRemoveMaintainer, + CanMutateMaintainer: canMutateMaintainer, } } diff --git a/modules/orders/internal/transactions/deputize/message.pb.go b/modules/orders/internal/transactions/deputize/message.pb.go deleted file mode 100644 index 561525d86..000000000 --- a/modules/orders/internal/transactions/deputize/message.pb.go +++ /dev/null @@ -1,832 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/transactions/deputize/message.proto - -package deputize - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - ToID base.ID `protobuf:"bytes,3,opt,name=to_i_d,json=toID,proto3" json:"to_i_d" valid:"required~required field ToID missing"` - ClassificationID base.ID `protobuf:"bytes,4,opt,name=classification_i_d,json=classificationID,proto3" json:"classification_i_d" valid:"required~required field ClassificationID missing"` - MaintainedProperties base.Properties `protobuf:"bytes,5,opt,name=maintained_properties,json=maintainedProperties,proto3" json:"maintained_properties" valid:"required~required field MaintainedProperties missing"` - AddMaintainer bool `protobuf:"varint,6,opt,name=add_maintainer,json=addMaintainer,proto3" json:"add_maintainer,omitempty"` - RemoveMaintainer bool `protobuf:"varint,7,opt,name=remove_maintainer,json=removeMaintainer,proto3" json:"remove_maintainer,omitempty"` - MutateMaintainer bool `protobuf:"varint,8,opt,name=mutate_maintainer,json=mutateMaintainer,proto3" json:"mutate_maintainer,omitempty"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_65df680d26cf9839, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_65df680d26cf9839, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.orders.internal.transactions.deputize.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.orders.internal.transactions.deputize.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/orders/internal/transactions/deputize/message.proto", fileDescriptor_65df680d26cf9839) -} - -var fileDescriptor_65df680d26cf9839 = []byte{ - // 586 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x94, 0xcf, 0x6b, 0x13, 0x4f, - 0x18, 0xc6, 0x77, 0xbf, 0xed, 0x37, 0x8d, 0x2b, 0x4a, 0x5d, 0x5b, 0x08, 0x3d, 0xec, 0x2e, 0x81, - 0x42, 0xf0, 0xc7, 0x2c, 0x44, 0x11, 0x29, 0x0a, 0x36, 0xae, 0x85, 0x50, 0x82, 0x12, 0x8b, 0x07, - 0x2f, 0x61, 0xb2, 0xf3, 0x66, 0x3b, 0x98, 0xd9, 0xd9, 0xce, 0x4c, 0x2a, 0x0a, 0x7a, 0xf6, 0xa8, - 0x07, 0xef, 0x3d, 0x7a, 0xf4, 0xcf, 0xe8, 0xb1, 0x37, 0xc5, 0x43, 0x90, 0xe4, 0xe2, 0xb9, 0x7f, - 0x81, 0x64, 0x77, 0x93, 0xdd, 0xc4, 0x42, 0x12, 0x7a, 0xca, 0x64, 0xdf, 0x67, 0x9e, 0xcf, 0x33, - 0xc3, 0xbc, 0xaf, 0xb1, 0x1f, 0x81, 0x90, 0x54, 0x2a, 0x08, 0x7d, 0x68, 0x49, 0xf2, 0xc6, 0x65, - 0x9c, 0xf4, 0xba, 0x20, 0x5d, 0x2e, 0x08, 0x08, 0xe9, 0xd2, 0x50, 0x81, 0x08, 0x71, 0xd7, 0x55, - 0x02, 0x87, 0x12, 0xfb, 0x8a, 0xf2, 0x50, 0xba, 0x04, 0xa2, 0x9e, 0xa2, 0xef, 0xc1, 0x65, 0x20, - 0x25, 0x0e, 0x00, 0x45, 0x82, 0x2b, 0x6e, 0x3e, 0x9e, 0x31, 0x43, 0xa9, 0x19, 0x4a, 0xcc, 0xd0, - 0xd8, 0x0c, 0xe5, 0xcd, 0xd0, 0xd8, 0x6c, 0x6b, 0x23, 0xe0, 0x01, 0x8f, 0x9d, 0xdc, 0xd1, 0x2a, - 0x31, 0xdd, 0xba, 0x35, 0x9b, 0x50, 0xfa, 0x87, 0xc0, 0xb0, 0xab, 0xde, 0x45, 0x20, 0xdd, 0x36, - 0x96, 0xe0, 0x52, 0x92, 0x6a, 0xab, 0xf3, 0xb5, 0x91, 0xe0, 0x11, 0x08, 0x45, 0x41, 0x26, 0x7b, - 0xca, 0x3f, 0x0a, 0xc6, 0x5a, 0x23, 0x39, 0x86, 0xf9, 0x45, 0x37, 0x56, 0x3b, 0x82, 0xb3, 0x92, - 0xee, 0xe8, 0x95, 0x2b, 0xb5, 0x0f, 0xa7, 0x7d, 0x5b, 0xfb, 0xd5, 0xb7, 0x9f, 0x05, 0x54, 0x1d, - 0xf6, 0xda, 0xc8, 0xe7, 0xcc, 0xcd, 0x11, 0x9e, 0x87, 0x90, 0xff, 0xfb, 0xd2, 0xdb, 0xff, 0x97, - 0x87, 0x76, 0x7d, 0x7f, 0x97, 0x10, 0x01, 0x52, 0x9e, 0xf7, 0xed, 0x3b, 0xc7, 0xb8, 0x4b, 0xc9, - 0x4e, 0x59, 0xc0, 0x51, 0x8f, 0x0a, 0x20, 0x1f, 0xc7, 0x0b, 0xa7, 0x43, 0xa1, 0x4b, 0x9c, 0x3d, - 0xc1, 0x99, 0xc3, 0xa8, 0x94, 0x34, 0x0c, 0xca, 0xcd, 0x38, 0x8a, 0xf9, 0xd6, 0x28, 0x8e, 0x7e, - 0x5b, 0xb4, 0x45, 0x4a, 0xff, 0x39, 0x7a, 0xe5, 0x6a, 0x75, 0x1b, 0xcd, 0xde, 0x73, 0x82, 0x45, - 0x31, 0x16, 0xc5, 0xd8, 0xba, 0x57, 0x7b, 0x30, 0x4a, 0x7f, 0xde, 0xb7, 0xd1, 0x02, 0xd0, 0xba, - 0x97, 0x61, 0x0b, 0x9d, 0xf8, 0x83, 0x79, 0x64, 0x14, 0x14, 0x8f, 0xb1, 0x2b, 0xcb, 0x60, 0xef, - 0xa7, 0xd8, 0x79, 0x67, 0x3d, 0xe0, 0x79, 0xe8, 0xaa, 0xe2, 0x75, 0xcf, 0xfc, 0xaa, 0x1b, 0xa6, - 0xdf, 0xc5, 0x52, 0xd2, 0x0e, 0xf5, 0xf1, 0xe8, 0x79, 0xc4, 0xfc, 0xd5, 0x65, 0xf8, 0x4f, 0x52, - 0xfe, 0xc3, 0x39, 0xfc, 0xa7, 0x53, 0x9c, 0x7c, 0x96, 0x75, 0x7f, 0xa6, 0x64, 0x7e, 0xd3, 0x8d, - 0x4d, 0x86, 0x69, 0xa8, 0x30, 0x0d, 0x81, 0xb4, 0xb2, 0x37, 0x54, 0xfa, 0x3f, 0x8e, 0x76, 0x77, - 0x81, 0x68, 0x2f, 0x26, 0x9b, 0x6a, 0x5e, 0x1a, 0xf1, 0xd1, 0x9c, 0x88, 0x8d, 0x09, 0x32, 0xdb, - 0x9c, 0xc5, 0xdc, 0x60, 0x17, 0x94, 0xcd, 0x6d, 0xe3, 0x3a, 0x26, 0xa4, 0x35, 0xa9, 0x89, 0x52, - 0xc1, 0xd1, 0x2b, 0xc5, 0xe6, 0x35, 0x4c, 0xc8, 0xc4, 0x4f, 0x98, 0xb7, 0x8d, 0x1b, 0x02, 0x18, - 0x3f, 0x86, 0xbc, 0x72, 0x2d, 0x56, 0xae, 0x27, 0x85, 0x69, 0x31, 0xeb, 0x29, 0xac, 0xa6, 0xc4, - 0xc5, 0x44, 0x9c, 0x14, 0x32, 0xf1, 0x4e, 0xf1, 0xd3, 0x89, 0xad, 0xfd, 0x39, 0xb1, 0xb5, 0xf2, - 0xa6, 0x71, 0xf3, 0x20, 0x6b, 0xf4, 0x26, 0xc8, 0x88, 0x87, 0x12, 0xaa, 0xdf, 0x75, 0x63, 0xa5, - 0x21, 0x83, 0xd1, 0xa5, 0x16, 0xbd, 0xb4, 0xf7, 0xcd, 0x3d, 0x74, 0xa9, 0xd9, 0x81, 0xd2, 0x0e, - 0xde, 0x6a, 0x5e, 0xd2, 0xe7, 0x82, 0xc0, 0x65, 0xad, 0x16, 0x9d, 0x0e, 0x2c, 0xfd, 0x6c, 0x60, - 0xe9, 0xbf, 0x07, 0x96, 0xfe, 0x79, 0x68, 0x69, 0x67, 0x43, 0x4b, 0xfb, 0x39, 0xb4, 0xb4, 0xd7, - 0xaf, 0x16, 0x1e, 0x0d, 0x4b, 0x0d, 0xd6, 0x76, 0x21, 0x1e, 0x4e, 0xf7, 0xfe, 0x06, 0x00, 0x00, - 0xff, 0xff, 0x0b, 0xf1, 0x09, 0x52, 0xa0, 0x05, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Deputize(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Deputize(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.orders.internal.transactions.deputize.Msg/Deputize", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Deputize(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Deputize(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Deputize not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Deputize_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Deputize(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.orders.internal.transactions.deputize.Msg/Deputize", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Deputize(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.orders.internal.transactions.deputize.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Deputize", - Handler: _Msg_Deputize_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/orders/internal/transactions/deputize/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.MutateMaintainer { - i-- - if m.MutateMaintainer { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x40 - } - if m.RemoveMaintainer { - i-- - if m.RemoveMaintainer { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x38 - } - if m.AddMaintainer { - i-- - if m.AddMaintainer { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x30 - } - { - size, err := m.MaintainedProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.ClassificationID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ToID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ToID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ClassificationID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MaintainedProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - if m.AddMaintainer { - n += 2 - } - if m.RemoveMaintainer { - n += 2 - } - if m.MutateMaintainer { - n += 2 - } - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ToID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ToID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaintainedProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MaintainedProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AddMaintainer", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.AddMaintainer = bool(v != 0) - case 7: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field RemoveMaintainer", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.RemoveMaintainer = bool(v != 0) - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MutateMaintainer", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.MutateMaintainer = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/orders/internal/transactions/deputize/message_test.go b/modules/orders/internal/transactions/deputize/message_test.go index 82eb33c97..6fe9499a8 100644 --- a/modules/orders/internal/transactions/deputize/message_test.go +++ b/modules/orders/internal/transactions/deputize/message_test.go @@ -1,43 +1,391 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( + "reflect" + "testing" + + "github.com/AssetMantle/modules/schema/lists/utilities" + + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" "github.com/stretchr/testify/require" - "testing" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Deputize_Message(t *testing.T) { +func CreateTestInputForMessage(t *testing.T) (ids.IdentityID, ids.IdentityID, ids.ClassificationID, sdkTypes.AccAddress, lists.PropertyList, sdkTypes.Msg) { + immutables := baseQualified.NewImmutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables := baseQualified.NewMutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) + mutables2 := baseQualified.NewMutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID"), baseData.NewStringData("Data3")))) + + testClassificationID := baseIDs.NewClassificationID(immutables, mutables) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutables) - testFromID := base.NewID("fromID") - testToID := base.NewID("toID") - testClassificationID := base.NewID("classificationID") + testClassificationID2 := baseIDs.NewClassificationID(immutables, mutables2) + testToID := baseIDs.NewIdentityID(testClassificationID2, immutables) fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) maintainedProperty := "maintainedProperty:S|maintainedProperty" - maintainedProperties, Error := base.ReadProperties(maintainedProperty) - require.Equal(t, nil, Error) - - testMessage := newMessage(fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, true, true, true) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, ToID: testToID, ClassificationID: testClassificationID, MaintainedProperties: maintainedProperties, AddMaintainer: true, RemoveMaintainer: true, MutateMaintainer: true}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) + maintainedProperties, err := utilities.ReadMetaPropertyList(maintainedProperty) + require.Equal(t, nil, err) + + testMessage := newMessage(fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, true, true, true, true, true, true) + + return testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties, testMessage +} + +func Test_messageFromInterface(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties, testMessage := CreateTestInputForMessage(t) + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{testMessage}, message{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, true, true, true, true, true, true}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties, testMessage := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, true, true, true, true, true, true}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(testMessage))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, true, true, true, true, true, true}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, true, true, true, true, true, true}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, true, true, true, true, true, true}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, true, true, true, true, true, true}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties, _ := CreateTestInputForMessage(t) + + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + MaintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, true, true, true, true, true, true}, false}, + {"-ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_newMessage(t *testing.T) { + testFromID, testToID, testClassificationID, fromAccAddress, maintainedProperties, _ := CreateTestInputForMessage(t) + type args struct { + from sdkTypes.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + maintainedProperties lists.PropertyList + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, true, true, true, true, true, true}, message{fromAccAddress, testFromID, testToID, testClassificationID, maintainedProperties, true, true, true, true, true, true}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.FromID, tt.args.ToID, tt.args.ClassificationID, tt.args.maintainedProperties, tt.args.CanMintAsset, tt.args.CanBurnAsset, tt.args.CanRenumerateAsset, tt.args.CanAddMaintainer, tt.args.CanRemoveMaintainer, tt.args.CanMutateMaintainer); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/deputize/msg_server.go b/modules/orders/internal/transactions/deputize/msg_server.go deleted file mode 100644 index 52c9d8442..000000000 --- a/modules/orders/internal/transactions/deputize/msg_server.go +++ /dev/null @@ -1,31 +0,0 @@ -package deputize - -import ( - "context" - "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/deputize" -) - -type msgServer struct { - transactionKeeper -} - -func (msgServer msgServer) Deputize(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := types.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - if auxiliaryResponse := msgServer.transactionKeeper.deputizeAuxiliary.GetKeeper().Help(ctx, deputize.NewAuxiliaryRequest(&message.FromID, &message.ToID, &message.ClassificationID, &message.MaintainedProperties, message.AddMaintainer, message.RemoveMaintainer, message.MutateMaintainer)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} - -var _ MsgServer = msgServer{} diff --git a/modules/orders/internal/transactions/deputize/request.go b/modules/orders/internal/transactions/deputize/request.go index e8e7982d8..b366fcb82 100644 --- a/modules/orders/internal/transactions/deputize/request.go +++ b/modules/orders/internal/transactions/deputize/request.go @@ -1,22 +1,22 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( "encoding/json" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -25,42 +25,48 @@ type transactionRequest struct { ToID string `json:"toID" valid:"required~required field toID missing, matches(^[A-Za-z0-9-_=.|]+$)~invalid field toID"` ClassificationID string `json:"classificationID" valid:"required~required field classificationID missing, matches(^[A-Za-z0-9-_=.]+$)~invalid field classificationID"` MaintainedProperties string `json:"maintainedProperties" valid:"required~required field maintainedProperties missing, matches(^.*$)~invalid field maintainedProperties"` - AddMaintainer bool `json:"addMaintainer"` - RemoveMaintainer bool `json:"removeMaintainer"` - MutateMaintainer bool `json:"mutateMaintainer"` + CanMintAsset bool `json:"canMintAsset"` + CanBurnAsset bool `json:"canBurnAsset"` + CanRenumerateAsset bool `json:"canRenumerateAsset"` + CanAddMaintainer bool `json:"canAddMaintainer"` + CanRemoveMaintainer bool `json:"canRemoveMaintainer"` + CanMutateMaintainer bool `json:"canMutateMaintainer"` } var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary deputize order transaction -// @Descrption deputize order transaction +// Validate godoc +// @Summary Deputize order transaction +// @Description Deputize order transaction // @Accept text/plain // @Produce json // @Tags Orders -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body body transactionRequest true "Request body to deputize an order" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /orders/deputize [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ToID), - cliCommand.ReadString(flags.ClassificationID), - cliCommand.ReadString(flags.MaintainedProperties), - cliCommand.ReadBool(flags.AddMaintainer), - cliCommand.ReadBool(flags.RemoveMaintainer), - cliCommand.ReadBool(flags.MutateMaintainer), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ToID), + cliCommand.ReadString(constants.ClassificationID), + cliCommand.ReadString(constants.MaintainedProperties), + cliCommand.ReadBool(constants.CanMintAsset), + cliCommand.ReadBool(constants.CanBurnAsset), + cliCommand.ReadBool(constants.CanRenumerateAsset), + cliCommand.ReadBool(constants.CanAddMaintainer), + cliCommand.ReadBool(constants.CanRemoveMaintainer), + cliCommand.ReadBool(constants.CanMutateMaintainer), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -69,43 +75,63 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err } - maintainedProperties, Error := base.ReadProperties(transactionRequest.MaintainedProperties) - if Error != nil { - return nil, Error + maintainedProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MaintainedProperties) + if err != nil { + return nil, err + } + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + toID, err := baseIDs.ReadIdentityID(transactionRequest.ToID) + if err != nil { + return nil, err + } + + classificationID, err := baseIDs.ReadClassificationID(transactionRequest.ClassificationID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.ToID), - base.NewID(transactionRequest.ClassificationID), + fromID, + toID, + classificationID, maintainedProperties, - transactionRequest.AddMaintainer, - transactionRequest.RemoveMaintainer, - transactionRequest.MutateMaintainer, + transactionRequest.CanMintAsset, + transactionRequest.CanBurnAsset, + transactionRequest.CanRenumerateAsset, + transactionRequest.CanAddMaintainer, + transactionRequest.CanRemoveMaintainer, + transactionRequest.CanMutateMaintainer, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} } - -func newTransactionRequest(baseReq rest.BaseReq, fromID string, toID string, classificationID string, maintainedProperties string, addMaintainer bool, removeMaintainer bool, mutateMaintainer bool) helpers.TransactionRequest { +func newTransactionRequest(baseReq rest.BaseReq, fromID string, toID string, classificationID string, maintainedProperties string, canMintAsset bool, canBurnAsset bool, canRenumerateAsset bool, canAddMaintainer bool, canRemoveMaintainer bool, canMutateMaintainer bool) helpers.TransactionRequest { return transactionRequest{ BaseReq: baseReq, FromID: fromID, ToID: toID, ClassificationID: classificationID, MaintainedProperties: maintainedProperties, - AddMaintainer: addMaintainer, - RemoveMaintainer: removeMaintainer, - MutateMaintainer: mutateMaintainer, + CanMintAsset: canMintAsset, + CanBurnAsset: canBurnAsset, + CanRenumerateAsset: canRenumerateAsset, + CanAddMaintainer: canAddMaintainer, + CanRemoveMaintainer: canRemoveMaintainer, + CanMutateMaintainer: canMutateMaintainer, } } diff --git a/modules/orders/internal/transactions/deputize/request_test.go b/modules/orders/internal/transactions/deputize/request_test.go index 8cfcbae63..173897ddb 100644 --- a/modules/orders/internal/transactions/deputize/request_test.go +++ b/modules/orders/internal/transactions/deputize/request_test.go @@ -1,79 +1,387 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( "encoding/json" + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/spf13/viper" "github.com/stretchr/testify/require" - "testing" -) -func Test_Deputize_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.ToID, flags.ClassificationID, flags.MaintainedProperties, flags.AddMaintainer, flags.RemoveMaintainer, flags.MutateMaintainer}) - cliContext := context.NewCLIContext().WithCodec(Codec) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - maintainedProperty := "maintainedProperties:S|maintainedProperties" - maintainedProperties, Error := base.ReadProperties(maintainedProperty) - require.Equal(t, nil, Error) + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID", maintainedProperty, false, false, false) +var ( + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = types.AccAddressFromBech32(fromAddress) + immutables = baseQualified.NewImmutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables = baseQualified.NewMutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ToID: "toID", ClassificationID: "classificationID", MaintainedProperties: maintainedProperty, AddMaintainer: false, RemoveMaintainer: false, MutateMaintainer: false}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) + testClassificationID = baseIDs.NewClassificationID(immutables, mutables) + testFromID = baseIDs.NewIdentityID(testClassificationID, immutables) + maintainedPropertyString = "maintainedProperty:S|maintainedProperty" + maintainedProperties, _ = utilities.ReadMetaPropertyList(maintainedPropertyString) + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} +) - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ToID: "", ClassificationID: "", MaintainedProperties: "", AddMaintainer: false, RemoveMaintainer: false, MutateMaintainer: false}, requestFromCLI) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + toID string + classificationID string + maintainedProperties string + canMintAsset bool + canBurnAsset bool + canRenumerateAsset bool + canAddMaintainer bool + canRemoveMaintainer bool + canMutateMaintainer bool + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String(), maintainedPropertyString, true, true, true, true, true, true}, newTransactionRequest(testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String(), maintainedPropertyString, true, true, true, true, true, true)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.toID, tt.args.classificationID, tt.args.maintainedProperties, tt.args.canMintAsset, tt.args.canBurnAsset, tt.args.canRenumerateAsset, tt.args.canAddMaintainer, tt.args.canRemoveMaintainer, tt.args.canMutateMaintainer); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.ToID, constants.ClassificationID, constants.MaintainedProperties, constants.CanMintAsset, constants.CanBurnAsset, constants.CanRenumerateAsset, constants.CanAddMaintainer, constants.CanRemoveMaintainer, constants.CanMutateMaintainer}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.FromID.GetName(), testFromID.String()) + viper.Set(constants.ToID.GetName(), testFromID.String()) + viper.Set(constants.ClassificationID.GetName(), testClassificationID.String()) + viper.Set(constants.MaintainedProperties.GetName(), maintainedPropertyString) + viper.Set(constants.CanMintAsset.GetName(), true) + viper.Set(constants.CanBurnAsset.GetName(), true) + viper.Set(constants.CanRenumerateAsset.GetName(), true) + viper.Set(constants.CanAddMaintainer.GetName(), true) + viper.Set(constants.CanRemoveMaintainer.GetName(), true) + viper.Set(constants.CanMutateMaintainer.GetName(), true) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String(), maintainedPropertyString, true, true, true, true, true, true}, args{cliCommand, cliContext}, newTransactionRequest(testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String(), maintainedPropertyString, true, true, true, true, true, true), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromJSON(t *testing.T) { + jsonMessage, err := json.Marshal(newTransactionRequest(testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String(), maintainedPropertyString, true, true, true, true, true, true)) + require.NoError(t, err) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String(), maintainedPropertyString, true, true, true, true, true, true}, args{jsonMessage}, newTransactionRequest(testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String(), maintainedPropertyString, true, true, true, true, true, true), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("toID"), base.NewID("classificationID"), maintainedProperties, false, false, false), msg) - require.Nil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String(), maintainedPropertyString, true, true, true, true, true, true}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error := newTransactionRequest(rest.BaseReq{From: "randomString", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "toID", "classificationID", maintainedProperty, false, false, false).MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String(), maintainedPropertyString, true, true, true, true, true, true}, newMessage(fromAccAddress, testFromID, testFromID, testClassificationID, maintainedProperties, true, true, true, true, true, true), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error = newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID", "randomString", false, false, false).MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String(), maintainedPropertyString, true, true, true, true, true, true}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + MaintainedProperties string + CanMintAsset bool + CanBurnAsset bool + CanRenumerateAsset bool + CanAddMaintainer bool + CanRemoveMaintainer bool + CanMutateMaintainer bool + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String(), maintainedPropertyString, true, true, true, true, true, true}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + MaintainedProperties: tt.fields.MaintainedProperties, + CanMintAsset: tt.fields.CanMintAsset, + CanBurnAsset: tt.fields.CanBurnAsset, + CanRenumerateAsset: tt.fields.CanRenumerateAsset, + CanAddMaintainer: tt.fields.CanAddMaintainer, + CanRemoveMaintainer: tt.fields.CanRemoveMaintainer, + CanMutateMaintainer: tt.fields.CanMutateMaintainer, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/orders/internal/transactions/deputize/response.go b/modules/orders/internal/transactions/deputize/response.go new file mode 100644 index 000000000..f6c13abcf --- /dev/null +++ b/modules/orders/internal/transactions/deputize/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/orders/internal/transactions/deputize/response_test.go b/modules/orders/internal/transactions/deputize/response_test.go index ec50e2681..349a64c2d 100644 --- a/modules/orders/internal/transactions/deputize/response_test.go +++ b/modules/orders/internal/transactions/deputize/response_test.go @@ -1,25 +1,84 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package deputize import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/stretchr/testify/require" + "reflect" "testing" -) -func Test_Deputize_Response(t *testing.T) { + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) - testTransactionResponse := newTransactionResponse(errors.IncorrectFormat) - testTransactionResponse2 := newTransactionResponse(nil) +func Test_newTransactionResponse(t *testing.T) { + type args struct { + error error + } + tests := []struct { + name string + args args + want helpers.TransactionResponse + }{ + {"+ve", args{nil}, transactionResponse{true, nil}}, + {"-ve", args{constants.IncorrectFormat}, transactionResponse{false, constants.IncorrectFormat}}} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionResponse(tt.args.error); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionResponse() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, transactionResponse{Success: false, Error: errors.IncorrectFormat}, testTransactionResponse) - require.Equal(t, false, testTransactionResponse.IsSuccessful()) - require.Equal(t, true, testTransactionResponse2.IsSuccessful()) +func Test_transactionResponse_GetError(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{Success: true, Error: nil}, false}, + {"-ve", fields{Success: false, Error: constants.IncorrectFormat}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if err := transactionResponse.GetError(); (err != nil) != tt.wantErr { + t.Errorf("GetError() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} - require.Equal(t, errors.IncorrectFormat, testTransactionResponse.GetError()) - require.Equal(t, nil, testTransactionResponse2.GetError()) +func Test_transactionResponse_IsSuccessful(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + want bool + }{ + {"+ve", fields{Success: true, Error: nil}, true}, + {"-ve", fields{Success: false, Error: constants.IncorrectFormat}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if got := transactionResponse.IsSuccessful(); got != tt.want { + t.Errorf("IsSuccessful() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/deputize/transaction.go b/modules/orders/internal/transactions/deputize/transaction.go new file mode 100644 index 000000000..ba0b78dd2 --- /dev/null +++ b/modules/orders/internal/transactions/deputize/transaction.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package deputize + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "deputize", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.ToID, + constants.ClassificationID, + constants.MaintainedProperties, + constants.CanMintAsset, + constants.CanBurnAsset, + constants.CanRenumerateAsset, + constants.CanAddMaintainer, + constants.CanRemoveMaintainer, + constants.CanMutateMaintainer, +) diff --git a/modules/orders/internal/transactions/immediate/keeper.go b/modules/orders/internal/transactions/immediate/keeper.go new file mode 100644 index 000000000..8ab5d7ddd --- /dev/null +++ b/modules/orders/internal/transactions/immediate/keeper.go @@ -0,0 +1,181 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package immediate + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/properties/constants" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + conformAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + if auxiliaryResponse := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(message.FromID, module.ModuleIdentityID, message.MakerOwnableID, message.MakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + immutableMetaProperties := message.ImmutableMetaProperties. + Add(baseProperties.NewMetaProperty(constants.ExchangeRateProperty.GetKey(), baseData.NewDecData(message.TakerOwnableSplit.QuoTruncate(sdkTypes.SmallestDec()).QuoTruncate(message.MakerOwnableSplit)))). + Add(baseProperties.NewMetaProperty(constants.CreationHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(context.BlockHeight())))). + Add(baseProperties.NewMetaProperty(constants.MakerOwnableIDProperty.GetKey(), baseData.NewIDData(message.MakerOwnableID))). + Add(baseProperties.NewMetaProperty(constants.TakerOwnableIDProperty.GetKey(), baseData.NewIDData(message.TakerOwnableID))). + Add(baseProperties.NewMetaProperty(constants.MakerIDProperty.GetKey(), baseData.NewIDData(message.FromID))). + Add(baseProperties.NewMetaProperty(constants.TakerIDProperty.GetKey(), baseData.NewIDData(message.TakerID))) + + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(append(immutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...)...)) + orderID := baseIDs.NewOrderID(message.ClassificationID, immutables) + orders := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(orderID)) + + if order := orders.Get(key.NewKey(orderID)); order != nil { + return newTransactionResponse(errorConstants.EntityAlreadyExists) + } + + mutableMetaProperties := message.MutableMetaProperties.Add(baseProperties.NewMetaProperty(constants.ExpiryHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(message.ExpiresIn.Get()+context.BlockHeight())))) + mutableMetaProperties = mutableMetaProperties.Add(baseProperties.NewMetaProperty(constants.MakerOwnableSplitProperty.GetKey(), baseData.NewDecData(message.MakerOwnableSplit))) + + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(append(mutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...)) + + if auxiliaryResponse := transactionKeeper.conformAuxiliary.GetKeeper().Help(context, conform.NewAuxiliaryRequest(message.ClassificationID, immutables, mutables)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + order := base.NewOrder(message.ClassificationID, immutables, mutables) + orders = orders.Add(mappable.NewMappable(order)) + + // Order execution + orderMutated := false + orderLeftOverMakerOwnableSplit := message.MakerOwnableSplit + + accumulator := func(mappableOrder helpers.Mappable) bool { + executableOrder := mappableOrder.(documents.Order) + + executableOrderTakerOwnableSplitDemanded := executableOrder.GetExchangeRate().MulTruncate(executableOrder.GetMakerOwnableSplit()).MulTruncate(sdkTypes.SmallestDec()) + + if order.GetExchangeRate().MulTruncate(executableOrder.GetExchangeRate()).MulTruncate(sdkTypes.SmallestDec()).MulTruncate(sdkTypes.SmallestDec()).LTE(sdkTypes.OneDec()) { + switch { + case orderLeftOverMakerOwnableSplit.GT(executableOrderTakerOwnableSplitDemanded): + // sending to buyer + if auxiliaryResponse := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, order.GetMakerID(), order.GetTakerOwnableID(), executableOrder.GetMakerOwnableSplit())); !auxiliaryResponse.IsSuccessful() { + panic(auxiliaryResponse.GetError()) + } + // sending to executableOrder + if auxiliaryResponse := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, executableOrder.GetMakerID(), order.GetMakerOwnableID(), executableOrderTakerOwnableSplitDemanded)); !auxiliaryResponse.IsSuccessful() { + panic(auxiliaryResponse.GetError()) + } + + orderLeftOverMakerOwnableSplit = orderLeftOverMakerOwnableSplit.Sub(executableOrderTakerOwnableSplitDemanded) + + orders.Remove(mappable.NewMappable(executableOrder)) + case orderLeftOverMakerOwnableSplit.LT(executableOrderTakerOwnableSplitDemanded): + // sending to buyer + sendToBuyer := orderLeftOverMakerOwnableSplit.QuoTruncate(sdkTypes.SmallestDec()).QuoTruncate(executableOrder.GetExchangeRate()) + if auxiliaryResponse := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, order.GetMakerID(), order.GetTakerOwnableID(), sendToBuyer)); !auxiliaryResponse.IsSuccessful() { + panic(auxiliaryResponse.GetError()) + } + // sending to executableOrder + if auxiliaryResponse := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, executableOrder.GetMakerID(), order.GetMakerOwnableID(), orderLeftOverMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { + panic(auxiliaryResponse.GetError()) + } + + mutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(constants.MakerOwnableSplitProperty.GetKey(), baseData.NewDecData(executableOrder.GetMakerOwnableSplit().Sub(sendToBuyer)))) + + orders.Mutate(mappable.NewMappable(base.NewOrder(executableOrder.GetClassificationID(), executableOrder.GetImmutables(), executableOrder.GetMutables().Mutate(mutableProperties.GetList()...)))) + + orderLeftOverMakerOwnableSplit = sdkTypes.ZeroDec() + default: + // case orderLeftOverMakerOwnableSplit.Equal(executableOrderTakerOwnableSplitDemanded): + // sending to buyer + if auxiliaryResponse := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, order.GetMakerID(), order.GetTakerOwnableID(), executableOrder.GetMakerOwnableSplit())); !auxiliaryResponse.IsSuccessful() { + panic(auxiliaryResponse.GetError()) + } + // sending to seller + if auxiliaryResponse := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, executableOrder.GetMakerID(), order.GetMakerOwnableID(), orderLeftOverMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { + panic(auxiliaryResponse.GetError()) + } + + orders.Remove(mappable.NewMappable(executableOrder)) + + orderLeftOverMakerOwnableSplit = sdkTypes.ZeroDec() + } + + orderMutated = true + } + + if orderLeftOverMakerOwnableSplit.Equal(sdkTypes.ZeroDec()) { + orders.Remove(mappable.NewMappable(order)) + return true + } + + return false + } + + orders.Iterate(mappable.NewMappable(order).GetKey(), accumulator) + + if !orderLeftOverMakerOwnableSplit.Equal(sdkTypes.ZeroDec()) && orderMutated { + mutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(constants.MakerOwnableSplitProperty.GetKey(), baseData.NewDecData(orderLeftOverMakerOwnableSplit))) + + orders.Mutate(mappable.NewMappable(base.NewOrder(order.GetClassificationID(), order.GetImmutables(), order.GetMutables().Mutate(mutableProperties.GetList()...)))) + } + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, externalKeeper := range auxiliaries { + switch value := externalKeeper.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case conform.Auxiliary.GetName(): + transactionKeeper.conformAuxiliary = value + case supplement.Auxiliary.GetName(): + transactionKeeper.supplementAuxiliary = value + case transfer.Auxiliary.GetName(): + transactionKeeper.transferAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/orders/internal/transactions/immediate/keeper_test.go b/modules/orders/internal/transactions/immediate/keeper_test.go index b1fefb8d6..db4cb9734 100644 --- a/modules/orders/internal/transactions/immediate/keeper_test.go +++ b/modules/orders/internal/transactions/immediate/keeper_test.go @@ -1,56 +1,65 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package immediate import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/test" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/conform" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/mint" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/transfer" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +var ( + conformAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary ) type TestKeepers struct { - OrdersKeeper helpers.TransactionKeeper + ImmediateKeeper helpers.TransactionKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func CreateTestInput(t *testing.T) (types.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + storeKey := types.NewKVStoreKey("test") + paramsStoreKey := types.NewKVStoreKey("testParams") + paramsTransientStoreKeys := types.NewTransientStoreKey("testParamsTransient") Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) paramsKeeper := params.NewKeeper( Codec, @@ -61,129 +70,156 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) - - context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + commitMultiStore.MountStoreWithDB(storeKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, types.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + supplementAuxiliary = supplement.AuxiliaryMock.Initialize(Mapper, Parameters) + transferAuxiliary = transfer.AuxiliaryMock.Initialize(Mapper, Parameters) + conformAuxiliary = conform.AuxiliaryMock.Initialize(Mapper, Parameters) + + context := types.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", - }, false, log.NewNopLogger()).WithBlockHeight(100) - - scrubAuxiliary := scrub.AuxiliaryMock.Initialize(Mapper, Parameters) - conformAuxiliary := conform.AuxiliaryMock.Initialize(Mapper, Parameters) - transferAuxiliary := transfer.AuxiliaryMock.Initialize(Mapper, Parameters) - verifyAuxiliary := verify.AuxiliaryMock.Initialize(Mapper, Parameters) - mintAuxiliary := mint.AuxiliaryMock.Initialize(Mapper, Parameters) - supplementAuxiliary := supplement.AuxiliaryMock.Initialize(Mapper, Parameters) + }, false, log.NewNopLogger()) + keepers := TestKeepers{ - OrdersKeeper: keeperPrototype().Initialize(Mapper, Parameters, - []interface{}{scrubAuxiliary, verifyAuxiliary, - conformAuxiliary, transferAuxiliary, mintAuxiliary, supplementAuxiliary}).(helpers.TransactionKeeper), + ImmediateKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), } - return context, keepers + return context, keepers, Mapper, Parameters } -func Test_transactionKeeper_Transact(t *testing.T) { +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - context, keepers := CreateTestInput(t) - immutableMetaProperties, Error := base.ReadMetaProperties("defaultImmutableMeta1:S|defaultImmutableMeta1") - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties("defaultImmutable1:S|defaultImmutable1") - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties("makerOwnableSplit:D|1") - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties("defaultMutable1:S|defaultMutable1") - require.Equal(t, nil, Error) - conformMockErrorProperties, Error := base.ReadProperties("conformError:S|mockError") - require.Equal(t, nil, Error) - scrubMockErrorProperties, Error := base.ReadMetaProperties("scrubError:S|mockError") - require.Equal(t, nil, Error) - verifyMockErrorAddress := sdkTypes.AccAddress("verifyError") - defaultAddr := sdkTypes.AccAddress("addr") - defaultIdentityID := base.NewID("fromID") - classificationID := base.NewID("classificationID") - makerOwnableID := base.NewID("makerOwnableID") - takerOwnableID := base.NewID("takerOwnableID") - makerOwnableSplit := sdkTypes.MustNewDecFromStr("1000") - orderID := key.NewOrderID( - classificationID, - makerOwnableID, - takerOwnableID, - base.NewID(sdkTypes.OneDec().String()), - base.NewID("100"), - defaultIdentityID, - base.NewProperties(), - ) - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(orderID, base.NewProperties(), base.NewProperties())) - - t.Run("PositiveCase Adding Order without execution", func(t *testing.T) { - want := newTransactionResponse(nil) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, classificationID, - makerOwnableID, takerOwnableID, base.NewHeight(0), makerOwnableSplit, sdkTypes.OneDec(), - immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - t.Run("NegativeCase - Order already exists", func(t *testing.T) { - want := newTransactionResponse(errors.EntityAlreadyExists) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, classificationID, - makerOwnableID, takerOwnableID, base.NewHeight(0), makerOwnableSplit, sdkTypes.OneDec(), - immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - Identity mock error", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(verifyMockErrorAddress, defaultIdentityID, classificationID, - makerOwnableID, takerOwnableID, base.NewHeight(0), sdkTypes.SmallestDec(), sdkTypes.OneDec(), - immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - conform mock fail", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, classificationID, - makerOwnableID, takerOwnableID, base.NewHeight(0), sdkTypes.SmallestDec(), sdkTypes.OneDec(), - immutableMetaProperties, immutableProperties, mutableMetaProperties, conformMockErrorProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - mutables scrub mock fail", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, classificationID, - makerOwnableID, takerOwnableID, base.NewHeight(0), sdkTypes.SmallestDec(), sdkTypes.OneDec(), - immutableMetaProperties, immutableProperties, scrubMockErrorProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - immutables scrub mock fail", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, classificationID, - makerOwnableID, takerOwnableID, base.NewHeight(0), sdkTypes.SmallestDec(), sdkTypes.OneDec(), - scrubMockErrorProperties, immutableProperties, mutableMetaProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - Transfer mock fail", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, classificationID, - base.NewID("transferError"), takerOwnableID, base.NewHeight(0), sdkTypes.SmallestDec(), sdkTypes.OneDec(), - immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := CreateTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + conformAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve with nil", fields{}, args{}, transactionKeeper{}}, + {"+ve", fields{Mapper, Parameters, conformAuxiliary, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, conformAuxiliary, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + conformAuxiliary: tt.fields.conformAuxiliary, + supplementAuxiliary: tt.fields.supplementAuxiliary, + transferAuxiliary: tt.fields.transferAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters := CreateTestInput(t) + mutableMetaProperties := baseLists.NewPropertyList( + baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())), + baseProperties.NewMetaProperty(baseIDs.NewStringID("exchangeRate"), baseData.NewDecData(types.NewDec(10))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerOwnableID"), baseData.NewIDData(baseIDs.NewOwnableID(baseIDs.NewStringID("makerID")))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("creationHeight"), baseData.NewHeightData(baseTypes.NewHeight(1))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("takerOwnableID"), baseData.NewIDData(baseIDs.NewOwnableID(baseIDs.NewStringID("takerID")))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(baseIDs.PrototypeIdentityID())), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(baseIDs.PrototypeIdentityID())), + ) + mutableProperties := baseLists.NewPropertyList( + baseProperties.NewMesaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())), + ) + immutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + immutableProperties := baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + immutablesMeta := baseQualified.NewImmutables(immutableMetaProperties) + mutablesMeta := baseQualified.NewMutables(mutableMetaProperties) + testClassificationID := baseIDs.NewClassificationID(immutablesMeta, mutablesMeta) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutablesMeta) + testTakerID := baseIDs.PrototypeIdentityID() + mutableMetaProperties.Mutate( + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(testFromID)), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(testFromID))) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + testIdentity := baseDocuments.NewIdentity(testClassificationID, immutablesMeta, mutablesMeta) + testIdentity.ProvisionAddress([]types.AccAddress{fromAccAddress}...) + testOrder := baseDocuments.NewOrder(testClassificationID, immutablesMeta, mutablesMeta) + // testOrderID := mappable.NewMappable(testOrder).GetKey() + testMakerOwnableID := baseIDs.NewOwnableID(baseIDs.NewStringID("makerID")) + testTakerOwnableID := baseIDs.NewOwnableID(baseIDs.NewStringID("takerID")) + testRate := types.NewDec(10) + testHeight := baseTypes.NewHeight(1) + // testOrderID := baseIDs.NewOrderID(testClassificationID, testMakerOwnableID, testTakerOwnableID, testRate, testHeight, testFromID, immutablesMeta) + // testOrderID2 := baseIDs.NewOrderID(testClassificationID, testTakerOwnableID, testTakerOwnableID, testRate, testHeight, testFromID, immutablesMeta) + keepers.ImmediateKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testOrder)) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + conformAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + context types.Context + msg types.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, Parameters, conformAuxiliary, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}, args{context, newMessage(fromAccAddress, testFromID, testClassificationID, testTakerID, testMakerOwnableID, testTakerOwnableID, testHeight, testRate, testRate, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)}, newTransactionResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + conformAuxiliary: tt.fields.conformAuxiliary, + supplementAuxiliary: tt.fields.supplementAuxiliary, + transferAuxiliary: tt.fields.transferAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/immediate/message.go b/modules/orders/internal/transactions/immediate/message.go index 2d4f9d953..1cf9bcdbf 100644 --- a/modules/orders/internal/transactions/immediate/message.go +++ b/modules/orders/internal/transactions/immediate/message.go @@ -1,86 +1,107 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package immediate import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/types" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ids.ClassificationID `json:"classificationID" valid:"required~required field classificationID missing"` + TakerID ids.IdentityID `json:"takerID" valid:"required~required field takerID missing"` + MakerOwnableID ids.OwnableID `json:"makerOwnableID" valid:"required~required field makerOwnableID missing"` + TakerOwnableID ids.OwnableID `json:"takerOwnableID" valid:"required~required field takerOwnableID missing"` + ExpiresIn types.Height `json:"expiresIn" valid:"required~required field expiresIn missing"` + MakerOwnableSplit sdkTypes.Dec `json:"makerOwnableSplit" valid:"required~required field makerOwnableSplit missing"` + TakerOwnableSplit sdkTypes.Dec `json:"takerOwnableSplit" valid:"required~required field takerOwnableSplit missing"` + ImmutableMetaProperties lists.PropertyList `json:"immutableMetaProperties" valid:"required~required field immutableMetaProperties missing"` + ImmutableProperties lists.PropertyList `json:"immutableProperties" valid:"required~required field immutableProperties missing"` + MutableMetaProperties lists.PropertyList `json:"mutableMetaProperties" valid:"required~required field mutableMetaProperties missing"` + MutableProperties lists.PropertyList `json:"mutableProperties" valid:"required~required field mutableProperties missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } - if message.MakerOwnableID.Compare(&message.TakerOwnableID) == 0 { - return errors.Wrap(xprtErrors.IncorrectMessage, "") + if message.MakerOwnableID.Compare(message.TakerOwnableID) == 0 { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, "") } if message.TakerOwnableSplit.LTE(sdkTypes.ZeroDec()) || message.MakerOwnableSplit.LTE(sdkTypes.ZeroDec()) { - return errors.Wrap(xprtErrors.IncorrectMessage, "") + return sdkErrors.Wrap(errorConstants.IncorrectMessage, "") } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + if len(message.ImmutableMetaProperties.GetList()) == 0 { + message.ImmutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.ImmutableProperties.GetList()) == 0 { + message.ImmutableProperties = base.NewPropertyList(nil) + } + if len(message.MutableMetaProperties.GetList()) == 0 { + message.MutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.MutableProperties.GetList()) == 0 { + message.MutableProperties = base.NewPropertyList(nil) + } + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, classificationID types.ID, makerOwnableID types.ID, takerOwnableID types.ID, expiresIn types.Height, makerOwnableSplit sdkTypes.Dec, takerOwnableSplit sdkTypes.Dec, immutableMetaProperties types.MetaProperties, immutableProperties types.Properties, mutableMetaProperties types.MetaProperties, mutableProperties types.Properties) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - ClassificationID: *base.NewID(classificationID.String()), - MakerOwnableID: *base.NewID(makerOwnableID.String()), - TakerOwnableID: *base.NewID(takerOwnableID.String()), - ExpiresIn: *base.NewHeight(expiresIn.Get()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, classificationID ids.ClassificationID, takerID ids.IdentityID, makerOwnableID ids.OwnableID, takerOwnableID ids.OwnableID, expiresIn types.Height, makerOwnableSplit sdkTypes.Dec, takerOwnableSplit sdkTypes.Dec, immutableMetaProperties lists.PropertyList, immutableProperties lists.PropertyList, mutableMetaProperties lists.PropertyList, mutableProperties lists.PropertyList) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + ClassificationID: classificationID, + TakerID: takerID, + MakerOwnableID: makerOwnableID, + TakerOwnableID: takerOwnableID, + ExpiresIn: expiresIn, MakerOwnableSplit: makerOwnableSplit, TakerOwnableSplit: takerOwnableSplit, - ImmutableMetaProperties: *base.NewMetaProperties(immutableMetaProperties.GetList()...), - ImmutableProperties: *base.NewProperties(immutableProperties.GetList()...), - MutableMetaProperties: *base.NewMetaProperties(mutableMetaProperties.GetList()...), - MutableProperties: *base.NewProperties(mutableProperties.GetList()...), + ImmutableMetaProperties: immutableMetaProperties, + ImmutableProperties: immutableProperties, + MutableMetaProperties: mutableMetaProperties, + MutableProperties: mutableProperties, } } diff --git a/modules/orders/internal/transactions/immediate/message.pb.go b/modules/orders/internal/transactions/immediate/message.pb.go deleted file mode 100644 index 581c8922c..000000000 --- a/modules/orders/internal/transactions/immediate/message.pb.go +++ /dev/null @@ -1,1067 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/transactions/immediate/message.proto - -package immediate - -import ( - context "context" - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - ClassificationID base.ID `protobuf:"bytes,3,opt,name=classification_i_d,json=classificationID,proto3" json:"classification_i_d" valid:"required~required field ClassificationID missing"` - MakerOwnableID base.ID `protobuf:"bytes,4,opt,name=maker_ownable_i_d,json=makerOwnableID,proto3" json:"maker_ownable_i_d" valid:"required~required field MakerOwnableID missing"` - TakerOwnableID base.ID `protobuf:"bytes,5,opt,name=taker_ownable_i_d,json=takerOwnableID,proto3" json:"taker_ownable_i_d" valid:"required~required field TakerOwnableID missing"` - ExpiresIn base.Height `protobuf:"bytes,6,opt,name=expires_in,json=expiresIn,proto3" json:"expires_in" valid:"required~required field ExpiresIn missing"` - MakerOwnableSplit github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=maker_ownable_split,json=makerOwnableSplit,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"maker_ownable_split" valid:"required~required field MakerOwnableSplit missing"` - TakerOwnableSplit github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,8,opt,name=taker_ownable_split,json=takerOwnableSplit,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"taker_ownable_split" valid:"required~required field TakerOwnableSplit missing"` - ImmutableMetaProperties base.MetaProperties `protobuf:"bytes,9,opt,name=immutable_meta_properties,json=immutableMetaProperties,proto3" json:"immutable_meta_properties" valid:"required~required field ImmutableMetaProperties missing"` - ImmutableProperties base.Properties `protobuf:"bytes,10,opt,name=immutable_properties,json=immutableProperties,proto3" json:"immutable_properties" valid:"required~required field ImmutableProperties missing"` - MutableMetaProperties base.MetaProperties `protobuf:"bytes,11,opt,name=mutable_meta_properties,json=mutableMetaProperties,proto3" json:"mutable_meta_properties" valid:"required~required field MutableMetaProperties missing"` - MutableProperties base.Properties `protobuf:"bytes,12,opt,name=mutable_properties,json=mutableProperties,proto3" json:"mutable_properties" valid:"required~required field MutableProperties missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_ffb9ecbd187238bb, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_ffb9ecbd187238bb, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.orders.internal.transactions.immediate.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.orders.internal.transactions.immediate.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/orders/internal/transactions/immediate/message.proto", fileDescriptor_ffb9ecbd187238bb) -} - -var fileDescriptor_ffb9ecbd187238bb = []byte{ - // 776 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0xd6, 0x3f, 0x4f, 0x1b, 0x49, - 0x14, 0x00, 0x70, 0xcf, 0xc1, 0x01, 0x1e, 0x4e, 0xe8, 0x58, 0x40, 0xf8, 0x28, 0x6c, 0xcb, 0xd2, - 0x9d, 0xb8, 0xd3, 0xb1, 0x2b, 0x38, 0x09, 0x1d, 0x44, 0x21, 0xc1, 0x98, 0x10, 0x2b, 0xb1, 0x88, - 0x00, 0x29, 0x52, 0x1a, 0x6b, 0xbd, 0xfb, 0x6c, 0x8f, 0xf0, 0xec, 0x2c, 0x33, 0xe3, 0x90, 0x14, - 0x49, 0x93, 0x26, 0x25, 0x29, 0x52, 0xa5, 0x08, 0x4d, 0xaa, 0x34, 0x91, 0x22, 0xe5, 0x33, 0x50, - 0x52, 0x45, 0x51, 0x0a, 0x2b, 0x82, 0x26, 0x35, 0x9f, 0x20, 0xda, 0xf1, 0x3a, 0x5e, 0xff, 0x81, - 0xb5, 0x41, 0x54, 0xbb, 0xde, 0x99, 0x79, 0xef, 0xa7, 0x37, 0x3b, 0xeb, 0x87, 0xef, 0xbb, 0xc0, - 0x05, 0x11, 0x12, 0x1c, 0x0b, 0xf2, 0xc2, 0xde, 0x35, 0x28, 0xb3, 0xab, 0x15, 0x10, 0x06, 0xe3, - 0x36, 0x70, 0x61, 0x10, 0x47, 0x02, 0x77, 0xcc, 0x8a, 0x21, 0xb9, 0xe9, 0x08, 0xd3, 0x92, 0x84, - 0x39, 0xc2, 0x20, 0x94, 0x82, 0x4d, 0x4c, 0x09, 0x06, 0x05, 0x21, 0xcc, 0x12, 0xe8, 0x2e, 0x67, - 0x92, 0x69, 0x2b, 0x6d, 0xd1, 0x74, 0x3f, 0x9a, 0x5e, 0x8f, 0xa6, 0x37, 0xa2, 0xe9, 0xc1, 0x68, - 0xfa, 0xcf, 0x68, 0x33, 0x93, 0x25, 0x56, 0x62, 0x2a, 0x94, 0xe1, 0xdd, 0xd5, 0xa3, 0xce, 0xfc, - 0xd3, 0x6e, 0x14, 0x56, 0x19, 0xa8, 0x69, 0xc8, 0xa7, 0x2e, 0x08, 0xa3, 0x60, 0x0a, 0x30, 0x88, - 0xed, 0xcf, 0xd5, 0xc3, 0xe7, 0x96, 0x81, 0x94, 0xca, 0xd2, 0x9f, 0xbf, 0x10, 0x3e, 0xdf, 0xe5, - 0xcc, 0x05, 0x2e, 0x09, 0x08, 0x7f, 0xcd, 0x62, 0xf8, 0x1a, 0x0a, 0xd2, 0x7c, 0xd0, 0xb6, 0x2e, - 0xf5, 0x79, 0x0c, 0x0f, 0xe7, 0xea, 0xf5, 0xd2, 0x5e, 0x21, 0x3c, 0x58, 0xe4, 0x8c, 0xc6, 0x50, - 0x12, 0xcd, 0x46, 0xd3, 0xcf, 0x8e, 0x6a, 0x89, 0xc8, 0xd7, 0x5a, 0x62, 0xbd, 0x44, 0x64, 0xb9, - 0x5a, 0xd0, 0x2d, 0x46, 0x8d, 0x40, 0x96, 0x4d, 0x07, 0x82, 0x3f, 0xb7, 0x33, 0xf7, 0x3a, 0x73, - 0xea, 0xab, 0x96, 0xb5, 0x6a, 0xdb, 0x1c, 0x84, 0x38, 0xab, 0x25, 0xfe, 0x7d, 0x6c, 0x56, 0x88, - 0xbd, 0x9c, 0xe2, 0xb0, 0x57, 0x25, 0x1c, 0xec, 0xe7, 0x8d, 0x9b, 0x64, 0x91, 0x40, 0xc5, 0x4e, - 0xde, 0xe1, 0x8c, 0x26, 0x29, 0x11, 0x82, 0x38, 0xa5, 0xd4, 0x96, 0xa2, 0x68, 0xfb, 0x78, 0xc4, - 0xbb, 0xe6, 0x49, 0xde, 0x8e, 0xfd, 0x92, 0x44, 0xb3, 0xa3, 0x0b, 0x7f, 0xb6, 0x97, 0x53, 0xaf, - 0xa7, 0xd5, 0x55, 0x5a, 0x5d, 0xa5, 0xcd, 0x66, 0xd2, 0x8b, 0x9e, 0xfe, 0xac, 0x96, 0xd0, 0x7b, - 0x48, 0x9a, 0xcd, 0x34, 0xd3, 0x0e, 0x15, 0xd5, 0x03, 0xed, 0x35, 0xc2, 0x9a, 0x55, 0x31, 0x85, - 0x20, 0x45, 0x62, 0x99, 0xde, 0x4b, 0xa1, 0x0c, 0x03, 0xfd, 0x18, 0x6e, 0xfb, 0x86, 0xff, 0x43, - 0x0c, 0x6b, 0x2d, 0x79, 0x82, 0x9a, 0xdf, 0xad, 0xb6, 0x21, 0xed, 0x00, 0xe1, 0x71, 0x6a, 0xee, - 0x02, 0xcf, 0xb3, 0x7d, 0xc7, 0x2c, 0x54, 0x40, 0xb1, 0x06, 0xfb, 0x61, 0xad, 0xf8, 0xac, 0xc5, - 0x10, 0x56, 0xce, 0x4b, 0xb3, 0x59, 0xcf, 0x12, 0x44, 0x8d, 0xd1, 0x96, 0x01, 0x45, 0x92, 0x1d, - 0xa4, 0x5f, 0xaf, 0x83, 0xb4, 0x73, 0x1e, 0x49, 0xb6, 0x92, 0x5e, 0x20, 0x8c, 0xe1, 0x89, 0x4b, - 0x38, 0x88, 0x3c, 0x71, 0x62, 0x43, 0xca, 0xf2, 0x77, 0x0f, 0x96, 0xbb, 0xea, 0x20, 0xa6, 0x97, - 0x7c, 0xcf, 0x7c, 0x88, 0x67, 0xbd, 0x9e, 0x23, 0xeb, 0x34, 0x29, 0x51, 0x68, 0x3c, 0xd3, 0xde, - 0x20, 0x3c, 0xd1, 0xba, 0x57, 0xc2, 0xad, 0x10, 0x19, 0x1b, 0x56, 0xe7, 0x6b, 0xd7, 0x3f, 0x5f, - 0x7f, 0x05, 0xce, 0x97, 0xc5, 0x04, 0x65, 0xc2, 0xbf, 0xcc, 0x79, 0xe7, 0xb8, 0x6e, 0xcb, 0x80, - 0x75, 0x56, 0x4b, 0x2c, 0xf5, 0xb1, 0x61, 0xdb, 0x5e, 0xa6, 0xa6, 0x6a, 0x9c, 0xb6, 0x8f, 0x29, - 0x9d, 0xec, 0xa2, 0x1b, 0xb9, 0x26, 0xdd, 0xce, 0x05, 0x3a, 0xd9, 0xa1, 0xfb, 0x84, 0xf0, 0x1f, - 0x84, 0xd2, 0xaa, 0x54, 0x32, 0xef, 0xdb, 0x95, 0x6f, 0x7e, 0xf4, 0x62, 0x51, 0xb5, 0xa1, 0xf3, - 0x3d, 0x6c, 0x68, 0xae, 0xe5, 0xab, 0x97, 0xde, 0xf0, 0x37, 0xf6, 0x56, 0x08, 0x36, 0xdb, 0x48, - 0xdd, 0xba, 0xbe, 0x49, 0x9e, 0x26, 0xdd, 0x67, 0x68, 0xef, 0x10, 0x9e, 0x6c, 0xc2, 0x03, 0x66, - 0xac, 0xcc, 0x73, 0x3d, 0x98, 0x03, 0xde, 0x35, 0xdf, 0x7b, 0xa3, 0x57, 0x6f, 0x37, 0xeb, 0x04, - 0xe9, 0x1c, 0xd5, 0x3e, 0x20, 0x3c, 0x7d, 0x5e, 0x79, 0x47, 0x2f, 0x5b, 0xde, 0x75, 0x9f, 0x7b, - 0x33, 0xec, 0x4d, 0xbd, 0xb8, 0xb8, 0x53, 0xdd, 0x4b, 0xfb, 0x16, 0x61, 0xad, 0x4b, 0x61, 0x7f, - 0xbb, 0x4c, 0x61, 0x57, 0x7d, 0xe9, 0x52, 0x6f, 0xd2, 0x6e, 0xca, 0xf1, 0x8e, 0xa2, 0x2e, 0x8f, - 0xbc, 0x3c, 0x4c, 0x44, 0xbe, 0x1f, 0x26, 0x22, 0xa9, 0x29, 0x3c, 0xb1, 0xd3, 0x6c, 0x28, 0xb6, - 0x40, 0xb8, 0xcc, 0x11, 0xb0, 0xf0, 0x11, 0xe1, 0x81, 0x9c, 0x28, 0x69, 0xef, 0x11, 0x8e, 0x66, - 0x1b, 0x3d, 0x86, 0xb6, 0xa1, 0x5f, 0xad, 0x49, 0xd1, 0xfd, 0xbf, 0xf0, 0x99, 0xed, 0xab, 0x06, - 0xea, 0x62, 0x4e, 0x45, 0xd2, 0x7b, 0x47, 0x27, 0x71, 0x74, 0x7c, 0x12, 0x47, 0xdf, 0x4e, 0xe2, - 0xe8, 0xe0, 0x34, 0x1e, 0x39, 0x3e, 0x8d, 0x47, 0xbe, 0x9c, 0xc6, 0x23, 0x8f, 0x1e, 0xf6, 0xdc, - 0x1c, 0xf4, 0xd7, 0xc4, 0x15, 0x86, 0x54, 0x7f, 0xf2, 0xdf, 0x8f, 0x00, 0x00, 0x00, 0xff, 0xff, - 0xb4, 0x6e, 0xbe, 0x14, 0x0d, 0x0a, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Immediate(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Immediate(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.orders.internal.transactions.immediate.Msg/Immediate", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Immediate(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Immediate(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Immediate not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Immediate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Immediate(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.orders.internal.transactions.immediate.Msg/Immediate", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Immediate(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.orders.internal.transactions.immediate.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Immediate", - Handler: _Msg_Immediate_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/orders/internal/transactions/immediate/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x62 - { - size, err := m.MutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x5a - { - size, err := m.ImmutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - { - size, err := m.ImmutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - { - size := m.TakerOwnableSplit.Size() - i -= size - if _, err := m.TakerOwnableSplit.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - { - size := m.MakerOwnableSplit.Size() - i -= size - if _, err := m.MakerOwnableSplit.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size, err := m.ExpiresIn.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.TakerOwnableID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.MakerOwnableID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ClassificationID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ClassificationID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MakerOwnableID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.TakerOwnableID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ExpiresIn.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MakerOwnableSplit.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.TakerOwnableSplit.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MakerOwnableID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MakerOwnableID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TakerOwnableID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TakerOwnableID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExpiresIn", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExpiresIn.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MakerOwnableSplit", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MakerOwnableSplit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TakerOwnableSplit", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TakerOwnableSplit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/orders/internal/transactions/immediate/message_test.go b/modules/orders/internal/transactions/immediate/message_test.go index 5dfa4a823..cd8544bd7 100644 --- a/modules/orders/internal/transactions/immediate/message_test.go +++ b/modules/orders/internal/transactions/immediate/message_test.go @@ -1,57 +1,377 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package immediate import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/codec" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/types" + "github.com/AssetMantle/modules/schema/types/base" + "github.com/AssetMantle/modules/utilities/transaction" +) + +var ( + expiresInHeight = base.NewHeight(60) + testMessage = newMessage(fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties) ) -func Test_Make_Message(t *testing.T) { - - fromID := base.NewID("fromID") - classificationID := base.NewID("classificationID") - makerOwnableID := base.NewID("makerOwnableID") - takerOwnableID := base.NewID("takerOwnableID") - expiresIn := base.NewHeight(12) - makerOwnableSplit := sdkTypes.NewDec(2) - takerOwnableSplit, _ := sdkTypes.NewDecFromStr("2000000000000000000") - zeroTakerOwnableSplit, _ := sdkTypes.NewDecFromStr("0") - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - immutableMetaProperties, Error := base.ReadMetaProperties("defaultImmutableMeta1:S|defaultImmutableMeta1") - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties("defaultImmutable1:S|defaultImmutable1") - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties("defaultMutableMeta1:S|defaultMutableMeta1") - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties("defaultMutable1:S|defaultMutable1") - require.Equal(t, nil, Error) - - testMessage := newMessage(fromAccAddress, fromID, classificationID, makerOwnableID, takerOwnableID, expiresIn, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties) - require.Equal(t, Message{From: fromAccAddress, FromID: fromID, ClassificationID: classificationID, MakerOwnableID: makerOwnableID, TakerOwnableID: takerOwnableID, ExpiresIn: expiresIn, TakerOwnableSplit: takerOwnableSplit, MakerOwnableSplit: makerOwnableSplit, ImmutableMetaProperties: immutableMetaProperties, ImmutableProperties: immutableProperties, MutableMetaProperties: mutableMetaProperties, MutableProperties: mutableProperties}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) - require.Error(t, errors.Wrap(xprtErrors.IncorrectMessage, ""), newMessage(fromAccAddress, fromID, classificationID, makerOwnableID, takerOwnableID, expiresIn, makerOwnableSplit, zeroTakerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties).ValidateBasic()) - require.Error(t, errors.Wrap(xprtErrors.IncorrectMessage, ""), newMessage(fromAccAddress, fromID, classificationID, makerOwnableID, makerOwnableID, expiresIn, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties).ValidateBasic()) +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{testMessage}, message{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + TakerID ids.IdentityID + MakerOwnableID ids.OwnableID + TakerOwnableID ids.OwnableID + ExpiresIn types.Height + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(testMessage))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + TakerID ids.IdentityID + MakerOwnableID ids.OwnableID + TakerOwnableID ids.OwnableID + ExpiresIn types.Height + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + TakerID ids.IdentityID + MakerOwnableID ids.OwnableID + TakerOwnableID ids.OwnableID + ExpiresIn types.Height + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + TakerID ids.IdentityID + MakerOwnableID ids.OwnableID + TakerOwnableID ids.OwnableID + ExpiresIn types.Height + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + TakerID ids.IdentityID + MakerOwnableID ids.OwnableID + TakerOwnableID ids.OwnableID + ExpiresIn types.Height + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + TakerID ids.IdentityID + MakerOwnableID ids.OwnableID + TakerOwnableID ids.OwnableID + ExpiresIn types.Height + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, false}, + {"-ve", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + classificationID ids.ClassificationID + takerID ids.IdentityID + makerOwnableID ids.OwnableID + takerOwnableID ids.OwnableID + expiresIn types.Height + makerOwnableSplit sdkTypes.Dec + takerOwnableSplit sdkTypes.Dec + immutableMetaProperties lists.PropertyList + immutableProperties lists.PropertyList + mutableMetaProperties lists.PropertyList + mutableProperties lists.PropertyList + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, message{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.classificationID, tt.args.takerID, tt.args.makerOwnableID, tt.args.takerOwnableID, tt.args.expiresIn, tt.args.makerOwnableSplit, tt.args.takerOwnableSplit, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/immediate/msg_server.go b/modules/orders/internal/transactions/immediate/msg_server.go deleted file mode 100644 index 7f9591445..000000000 --- a/modules/orders/internal/transactions/immediate/msg_server.go +++ /dev/null @@ -1,180 +0,0 @@ -package immediate - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/conform" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/transfer" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "strconv" -) - -type msgServer struct { - transactionKeeper -} - -func (msgServer msgServer) Immediate(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - if auxiliaryResponse := msgServer.transactionKeeper.transferAuxiliary.GetKeeper().Help(ctx, transfer.NewAuxiliaryRequest(&message.FromID, base.NewID(module.Name), &message.MakerOwnableID, message.MakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - immutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(message.ImmutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - immutableProperties := base.NewProperties(append(immutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...)...) - exchangeRate := message.TakerOwnableSplit.QuoTruncate(sdkTypes.SmallestDec()).QuoTruncate(message.MakerOwnableSplit) - orderID := key.NewOrderID(&message.ClassificationID, &message.MakerOwnableID, &message.TakerOwnableID, base.NewID(exchangeRate.String()), base.NewID(strconv.FormatInt(ctx.BlockHeight(), 10)), &message.FromID, immutableProperties) - orders := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(orderID)) - - if order := orders.Get(key.FromID(orderID)); order != nil { - return nil, errors.EntityAlreadyExists - } - - mutableMetaProperties := message.MutableMetaProperties.Add(base.NewMetaProperty(base.NewID(properties.Expiry), base.NewMetaFact(base.NewHeightData(base.NewHeight(message.ExpiresIn.Get()+ctx.BlockHeight()))))) - mutableMetaProperties = mutableMetaProperties.Add(base.NewMetaProperty(base.NewID(properties.MakerOwnableSplit), base.NewMetaFact(base.NewDecData(message.MakerOwnableSplit)))) - - scrubbedMutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(mutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - mutableProperties := base.NewProperties(append(scrubbedMutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...) - - if auxiliaryResponse := msgServer.transactionKeeper.conformAuxiliary.GetKeeper().Help(ctx, conform.NewAuxiliaryRequest(&message.ClassificationID, immutableProperties, mutableProperties)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - order := mappable.NewOrder(orderID, immutableProperties, mutableProperties) - orders = orders.Add(order) - - // Order execution - orderMutated := false - orderLeftOverMakerOwnableSplit := message.MakerOwnableSplit - - orderExchangeRate, Error := order.GetExchangeRate().GetMetaFact().GetData().AsDec() - if Error != nil { - return nil, Error - } - - accumulator := func(mappableOrder helpers.Mappable) bool { - executableOrder := mappableOrder.(mappables.Order) - - executableOrderExchangeRate, Error := executableOrder.GetExchangeRate().GetMetaFact().GetData().AsDec() - if Error != nil { - panic(Error) - } - - executableOrderMetaProperties, Error := supplement.GetMetaPropertiesFromResponse(msgServer.transactionKeeper.supplementAuxiliary.GetKeeper().Help(ctx, supplement.NewAuxiliaryRequest(executableOrder.GetMakerOwnableSplit(), executableOrder.GetExpiry()))) - if Error != nil { - panic(Error) - } - - var executableOrderMakerOwnableSplit sdkTypes.Dec - - if makerOwnableSplitProperty := executableOrderMetaProperties.Get(base.NewID(properties.MakerOwnableSplit)); makerOwnableSplitProperty != nil { - executableOrderMakerOwnableSplit, Error = makerOwnableSplitProperty.GetMetaFact().GetData().AsDec() - if Error != nil { - panic(Error) - } - } else { - panic(errors.MetaDataError) - } - - executableOrderTakerOwnableSplitDemanded := executableOrderExchangeRate.MulTruncate(executableOrderMakerOwnableSplit).MulTruncate(sdkTypes.SmallestDec()) - - if orderExchangeRate.MulTruncate(executableOrderExchangeRate).MulTruncate(sdkTypes.SmallestDec()).MulTruncate(sdkTypes.SmallestDec()).LTE(sdkTypes.OneDec()) { - switch { - case orderLeftOverMakerOwnableSplit.GT(executableOrderTakerOwnableSplitDemanded): - // sending to buyer - if auxiliaryResponse := msgServer.transactionKeeper.transferAuxiliary.GetKeeper().Help(ctx, transfer.NewAuxiliaryRequest(base.NewID(module.Name), order.GetMakerID(), order.GetTakerOwnableID(), executableOrderMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { - panic(auxiliaryResponse.GetError()) - } - // sending to executableOrder - if auxiliaryResponse := msgServer.transactionKeeper.transferAuxiliary.GetKeeper().Help(ctx, transfer.NewAuxiliaryRequest(base.NewID(module.Name), executableOrder.GetMakerID(), order.GetMakerOwnableID(), executableOrderTakerOwnableSplitDemanded)); !auxiliaryResponse.IsSuccessful() { - panic(auxiliaryResponse.GetError()) - } - - orderLeftOverMakerOwnableSplit = orderLeftOverMakerOwnableSplit.Sub(executableOrderTakerOwnableSplitDemanded) - - orders.Remove(executableOrder) - case orderLeftOverMakerOwnableSplit.LT(executableOrderTakerOwnableSplitDemanded): - // sending to buyer - sendToBuyer := orderLeftOverMakerOwnableSplit.QuoTruncate(sdkTypes.SmallestDec()).QuoTruncate(executableOrderExchangeRate) - if auxiliaryResponse := msgServer.transactionKeeper.transferAuxiliary.GetKeeper().Help(ctx, transfer.NewAuxiliaryRequest(base.NewID(module.Name), order.GetMakerID(), order.GetTakerOwnableID(), sendToBuyer)); !auxiliaryResponse.IsSuccessful() { - panic(auxiliaryResponse.GetError()) - } - // sending to executableOrder - if auxiliaryResponse := msgServer.transactionKeeper.transferAuxiliary.GetKeeper().Help(ctx, transfer.NewAuxiliaryRequest(base.NewID(module.Name), executableOrder.GetMakerID(), order.GetMakerOwnableID(), orderLeftOverMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { - panic(auxiliaryResponse.GetError()) - } - - mutableProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(base.NewMetaProperty(base.NewID(properties.MakerOwnableSplit), base.NewMetaFact(base.NewDecData(executableOrderMakerOwnableSplit.Sub(sendToBuyer))))))) - if Error != nil { - panic(Error) - } - - orders.Mutate(mappable.NewOrder(executableOrder.GetID(), executableOrder.GetImmutableProperties(), executableOrder.GetMutableProperties().Mutate(mutableProperties.GetList()...))) - - orderLeftOverMakerOwnableSplit = sdkTypes.ZeroDec() - default: - // case orderLeftOverMakerOwnableSplit.Equal(executableOrderTakerOwnableSplitDemanded): - // sending to buyer - if auxiliaryResponse := msgServer.transactionKeeper.transferAuxiliary.GetKeeper().Help(ctx, transfer.NewAuxiliaryRequest(base.NewID(module.Name), order.GetMakerID(), order.GetTakerOwnableID(), executableOrderMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { - panic(auxiliaryResponse.GetError()) - } - // sending to seller - if auxiliaryResponse := msgServer.transactionKeeper.transferAuxiliary.GetKeeper().Help(ctx, transfer.NewAuxiliaryRequest(base.NewID(module.Name), executableOrder.GetMakerID(), order.GetMakerOwnableID(), orderLeftOverMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { - panic(auxiliaryResponse.GetError()) - } - - orders.Remove(executableOrder) - - orderLeftOverMakerOwnableSplit = sdkTypes.ZeroDec() - } - - orderMutated = true - } - - if orderLeftOverMakerOwnableSplit.Equal(sdkTypes.ZeroDec()) { - orders.Remove(order) - return true - } - - return false - } - - orders.Iterate(key.FromID(key.NewOrderID(order.GetClassificationID(), order.GetTakerOwnableID(), order.GetMakerOwnableID(), base.NewID(""), base.NewID(""), base.NewID(""), base.NewProperties())), accumulator) - - if !orderLeftOverMakerOwnableSplit.Equal(sdkTypes.ZeroDec()) && orderMutated { - mutableProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(base.NewMetaProperty(base.NewID(properties.MakerOwnableSplit), base.NewMetaFact(base.NewDecData(orderLeftOverMakerOwnableSplit)))))) - if Error != nil { - return nil, Error - } - - orders.Mutate(mappable.NewOrder(orderID, order.GetImmutableProperties(), order.GetMutableProperties().Mutate(mutableProperties.GetList()...))) - } - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} - -var _ MsgServer = msgServer{} diff --git a/modules/orders/internal/transactions/immediate/request.go b/modules/orders/internal/transactions/immediate/request.go index d21b210fa..925b7a24e 100644 --- a/modules/orders/internal/transactions/immediate/request.go +++ b/modules/orders/internal/transactions/immediate/request.go @@ -1,28 +1,30 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package immediate import ( "encoding/json" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + baseTypes "github.com/AssetMantle/modules/schema/types/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { BaseReq rest.BaseReq `json:"baseReq"` FromID string `json:"fromID" valid:"required~required field fromID missing, matches(^[A-Za-z0-9-_=.|]+$)~invalid field fromID"` ClassificationID string `json:"classificationID" valid:"required~required field classificationID missing, matches(^[A-Za-z0-9-_=.]+$)~invalid field classificationID"` + TakerID string `json:"takerID" valid:"required~required field takerID missing, matches(^[A-Za-z0-9-_=.|]+$)~invalid field takerID"` MakerOwnableID string `json:"makerOwnableID" valid:"required~required field makerOwnableID missing, matches(^[A-Za-z0-9-_=.|]+$)~invalid field makerOwnableID"` TakerOwnableID string `json:"takerOwnableID" valid:"required~required field takerOwnableID missing, matches(^[A-Za-z0-9-_=.|]+$)~invalid field takerOwnableID"` ExpiresIn int64 `json:"expiresIn" valid:"required~required field expiresIn missing, matches(^[0-9]+$)~invalid field expiresIn"` @@ -36,39 +38,40 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary immediate order transaction -// @Descrption immediate order transaction +// Validate godoc +// @Summary Immediate order transaction +// @Description Immediate order transaction // @Accept text/plain // @Produce json // @Tags Orders -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body transactionRequest true "Request body for immediate order" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /orders/immediate [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ClassificationID), - cliCommand.ReadString(flags.MakerOwnableID), - cliCommand.ReadString(flags.TakerOwnableID), - cliCommand.ReadInt64(flags.ExpiresIn), - cliCommand.ReadString(flags.MakerOwnableSplit), - cliCommand.ReadString(flags.TakerOwnableSplit), - cliCommand.ReadString(flags.ImmutableMetaProperties), - cliCommand.ReadString(flags.ImmutableProperties), - cliCommand.ReadString(flags.MutableMetaProperties), - cliCommand.ReadString(flags.MutableProperties), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ClassificationID), + cliCommand.ReadString(constants.TakerID), + cliCommand.ReadString(constants.MakerOwnableID), + cliCommand.ReadString(constants.TakerOwnableID), + cliCommand.ReadInt64(constants.ExpiresIn), + cliCommand.ReadString(constants.MakerOwnableSplit), + cliCommand.ReadString(constants.TakerOwnableSplit), + cliCommand.ReadString(constants.ImmutableMetaProperties), + cliCommand.ReadString(constants.ImmutableProperties), + cliCommand.ReadString(constants.MutableMetaProperties), + cliCommand.ReadString(constants.MutableProperties), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -78,48 +81,76 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + classificationID, err := baseIDs.ReadClassificationID(transactionRequest.ClassificationID) + if err != nil { + return nil, err + } + + takerID, err := baseIDs.ReadIdentityID(transactionRequest.TakerID) + if err != nil { + return nil, err + } + + makerOwnableID, err := baseIDs.ReadOwnableID(transactionRequest.MakerOwnableID) + if err != nil { + return nil, err + } + + takerOwnableID, err := baseIDs.ReadOwnableID(transactionRequest.TakerOwnableID) + if err != nil { + return nil, err } - makerOwnableSplit, Error := sdkTypes.NewDecFromStr(transactionRequest.MakerOwnableSplit) - if Error != nil { - return nil, Error + makerOwnableSplit, err := sdkTypes.NewDecFromStr(transactionRequest.MakerOwnableSplit) + if err != nil { + return nil, err } - takerOwnableSplit, Error := sdkTypes.NewDecFromStr(transactionRequest.TakerOwnableSplit) - if Error != nil { - return nil, Error + takerOwnableSplit, err := sdkTypes.NewDecFromStr(transactionRequest.TakerOwnableSplit) + if err != nil { + return nil, err } - immutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.ImmutableMetaProperties) - if Error != nil { - return nil, Error + immutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableMetaProperties) + if err != nil { + return nil, err } - immutableProperties, Error := base.ReadProperties(transactionRequest.ImmutableProperties) - if Error != nil { - return nil, Error + immutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableProperties) + if err != nil { + return nil, err } + immutableProperties = immutableProperties.ScrubData() - mutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.MutableMetaProperties) - if Error != nil { - return nil, Error + mutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableMetaProperties) + if err != nil { + return nil, err } - mutableProperties, Error := base.ReadProperties(transactionRequest.MutableProperties) - if Error != nil { - return nil, Error + mutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableProperties) + if err != nil { + return nil, err } + mutableProperties = mutableProperties.ScrubData() return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.ClassificationID), - base.NewID(transactionRequest.MakerOwnableID), - base.NewID(transactionRequest.TakerOwnableID), - base.NewHeight(transactionRequest.ExpiresIn), + fromID, + classificationID, + takerID, + makerOwnableID, + takerOwnableID, + baseTypes.NewHeight(transactionRequest.ExpiresIn), makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, @@ -128,18 +159,19 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { mutableProperties, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} } -func newTransactionRequest(baseReq rest.BaseReq, fromID string, classificationID string, makerOwnableID string, takerOwnableID string, expiresIn int64, makerOwnableSplit, takerOwnableSplit string, immutableMetaProperties string, immutableProperties string, mutableMetaProperties string, mutableProperties string) helpers.TransactionRequest { +func newTransactionRequest(baseReq rest.BaseReq, fromID string, classificationID string, takerID string, makerOwnableID string, takerOwnableID string, expiresIn int64, makerOwnableSplit, takerOwnableSplit string, immutableMetaProperties string, immutableProperties string, mutableMetaProperties string, mutableProperties string) helpers.TransactionRequest { return transactionRequest{ BaseReq: baseReq, FromID: fromID, ClassificationID: classificationID, + TakerID: takerID, MakerOwnableID: makerOwnableID, TakerOwnableID: takerOwnableID, ExpiresIn: expiresIn, diff --git a/modules/orders/internal/transactions/immediate/request_test.go b/modules/orders/internal/transactions/immediate/request_test.go index b1af1ec1d..ab655f45c 100644 --- a/modules/orders/internal/transactions/immediate/request_test.go +++ b/modules/orders/internal/transactions/immediate/request_test.go @@ -1,110 +1,425 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package immediate import ( "encoding/json" + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/spf13/viper" "github.com/stretchr/testify/require" - "testing" -) - -func Test_Define_Request(t *testing.T) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.ClassificationID, flags.MakerOwnableSplit, flags.MakerOwnableID, flags.TakerOwnableID, flags.ExpiresIn, flags.TakerOwnableSplit, flags.ImmutableMetaProperties, flags.ImmutableProperties, flags.MutableMetaProperties, flags.MutableProperties}) - cliContext := context.NewCLIContext().WithCodec(Codec) - - immutableMetaPropertiesString := "defaultImmutableMeta1:S|defaultImmutableMeta1" - immutablePropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" - mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" - mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - - immutableMetaProperties, Error := base.ReadMetaProperties(immutableMetaPropertiesString) - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties(immutablePropertiesString) - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties(mutableMetaPropertiesString) - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties(mutablePropertiesString) - require.Equal(t, nil, Error) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", sdkTypes.OneDec().String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString) - - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ClassificationID: "classificationID", MakerOwnableID: "makerOwnableID", TakerOwnableID: "takerOwnableID", ExpiresIn: 123, MakerOwnableSplit: "2", TakerOwnableSplit: sdkTypes.OneDec().String(), ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ImmutableMetaProperties: "", ImmutableProperties: "", MutableMetaProperties: "", MutableProperties: ""}, requestFromCLI) - - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, error3 := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, error3) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/schema/types/base" +) - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +var ( + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = types.AccAddressFromBech32(fromAddress) + immutableMetaPropertiesString = "defaultImmutableMeta1:S|defaultImmutableMeta1" + immutablePropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" + mutableMetaPropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" + mutablePropertiesString = "defaultMutable1:S|defaultMutable1" + immutableMetaProperties, _ = utilities.ReadMetaPropertyList(immutableMetaPropertiesString) + immutableProperties, _ = utilities.ReadMetaPropertyList(immutablePropertiesString) + mutableMetaProperties, _ = utilities.ReadMetaPropertyList(mutableMetaPropertiesString) + mutableProperties, _ = utilities.ReadMetaPropertyList(mutablePropertiesString) + immutables = baseQualified.NewImmutables(immutableProperties) + mutables = baseQualified.NewMutables(mutableProperties) + testClassificationID = baseIDs.NewClassificationID(immutables, mutables) + testFromID = baseIDs.NewIdentityID(testClassificationID, immutables) + makerOwnableID = baseIDs.NewOwnableID(baseIDs.NewStringID("makerownableid")) + takerOwnableID = baseIDs.NewOwnableID(baseIDs.NewStringID("takerownableid")) + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + expiresIn = int64(60) + makerOwnableSplit = types.NewDec(60) + takerOwnableSplit = types.NewDec(60) +) - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + classificationID string + takerID string + makerOwnableID string + takerOwnableID string + expiresIn int64 + makerOwnableSplit string + takerOwnableSplit string + immutableMetaProperties string + immutableProperties string + mutableMetaProperties string + mutableProperties string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("classificationID"), base.NewID("makerOwnableID"), base.NewID("takerOwnableID"), base.NewHeight(123), sdkTypes.NewDec(2), sdkTypes.OneDec(), immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties), msg) - require.Nil(t, Error) + {"+ve", args{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, newTransactionRequest(testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.classificationID, tt.args.takerID, tt.args.makerOwnableID, tt.args.takerOwnableID, tt.args.expiresIn, tt.args.makerOwnableSplit, tt.args.takerOwnableSplit, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", sdkTypes.OneDec().String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ - msg, Error = newTransactionRequest(rest.BaseReq{From: fromAddress, ChainID: "test"}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "randomInput", sdkTypes.OneDec().String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", sdkTypes.OneDec().String(), "randomString", immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.ClassificationID, constants.TakerID, constants.MakerOwnableID, constants.TakerOwnableID, constants.ExpiresIn, constants.MakerOwnableSplit, constants.TakerOwnableSplit, constants.ImmutableMetaProperties, constants.ImmutableProperties, constants.MutableMetaProperties, constants.MutableProperties}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.FromID.GetName(), testFromID.String()) + viper.Set(constants.ClassificationID.GetName(), testClassificationID.String()) + viper.Set(constants.TakerID.GetName(), testFromID.String()) + viper.Set(constants.MakerOwnableID.GetName(), makerOwnableID.String()) + viper.Set(constants.TakerOwnableID.GetName(), takerOwnableID.String()) + viper.Set(constants.ExpiresIn.GetName(), expiresIn) + viper.Set(constants.MakerOwnableSplit.GetName(), makerOwnableSplit.String()) + viper.Set(constants.TakerOwnableSplit.GetName(), takerOwnableSplit.String()) + viper.Set(constants.ImmutableMetaProperties.GetName(), immutableMetaPropertiesString) + viper.Set(constants.ImmutableProperties.GetName(), immutablePropertiesString) + viper.Set(constants.MutableMetaProperties.GetName(), mutableMetaPropertiesString) + viper.Set(constants.MutableProperties.GetName(), mutablePropertiesString) + type fields struct { + BaseReq rest.BaseReq + FromID string + ClassificationID string + TakerID string + MakerOwnableID string + TakerOwnableID string + ExpiresIn int64 + MakerOwnableSplit string + TakerOwnableSplit string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, cliContext}, newTransactionRequest(testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", sdkTypes.OneDec().String(), immutableMetaPropertiesString, "randomString", mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_FromJSON(t *testing.T) { + jsonMessage, err := json.Marshal(newTransactionRequest(testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString)) + require.NoError(t, err) + type fields struct { + BaseReq rest.BaseReq + FromID string + ClassificationID string + TakerID string + MakerOwnableID string + TakerOwnableID string + ExpiresIn int64 + MakerOwnableSplit string + TakerOwnableSplit string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{jsonMessage}, newTransactionRequest(testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", sdkTypes.OneDec().String(), immutableMetaPropertiesString, immutablePropertiesString, "randomString", mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ClassificationID string + TakerID string + MakerOwnableID string + TakerOwnableID string + ExpiresIn int64 + MakerOwnableSplit string + TakerOwnableSplit string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", sdkTypes.OneDec().String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, "randomString").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ClassificationID string + TakerID string + MakerOwnableID string + TakerOwnableID string + ExpiresIn int64 + MakerOwnableSplit string + TakerOwnableSplit string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, newMessage(fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, base.NewHeight(60), makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", "test", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, "randomString").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ClassificationID string + TakerID string + MakerOwnableID string + TakerOwnableID string + ExpiresIn int64 + MakerOwnableSplit string + TakerOwnableSplit string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ClassificationID string + TakerID string + MakerOwnableID string + TakerOwnableID string + ExpiresIn int64 + MakerOwnableSplit string + TakerOwnableSplit string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/orders/internal/transactions/immediate/response.go b/modules/orders/internal/transactions/immediate/response.go new file mode 100644 index 000000000..05260bed6 --- /dev/null +++ b/modules/orders/internal/transactions/immediate/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package immediate + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/orders/internal/transactions/immediate/response_test.go b/modules/orders/internal/transactions/immediate/response_test.go index cf5a23b28..2f47f79aa 100644 --- a/modules/orders/internal/transactions/immediate/response_test.go +++ b/modules/orders/internal/transactions/immediate/response_test.go @@ -1,25 +1,84 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package immediate import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/stretchr/testify/require" + "reflect" "testing" -) -func Test_Make_Response(t *testing.T) { + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) - testTransactionResponse := newTransactionResponse(errors.IncorrectFormat) - testTransactionResponse2 := newTransactionResponse(nil) +func Test_newTransactionResponse(t *testing.T) { + type args struct { + error error + } + tests := []struct { + name string + args args + want helpers.TransactionResponse + }{ + {"+ve", args{nil}, transactionResponse{true, nil}}, + {"-ve", args{constants.IncorrectFormat}, transactionResponse{false, constants.IncorrectFormat}}} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionResponse(tt.args.error); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionResponse() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, transactionResponse{Success: false, Error: errors.IncorrectFormat}, testTransactionResponse) - require.Equal(t, false, testTransactionResponse.IsSuccessful()) - require.Equal(t, true, testTransactionResponse2.IsSuccessful()) +func Test_transactionResponse_GetError(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{Success: true, Error: nil}, false}, + {"-ve", fields{Success: false, Error: constants.IncorrectFormat}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if err := transactionResponse.GetError(); (err != nil) != tt.wantErr { + t.Errorf("GetError() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} - require.Equal(t, errors.IncorrectFormat, testTransactionResponse.GetError()) - require.Equal(t, nil, testTransactionResponse2.GetError()) +func Test_transactionResponse_IsSuccessful(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + want bool + }{ + {"+ve", fields{Success: true, Error: nil}, true}, + {"-ve", fields{Success: false, Error: constants.IncorrectFormat}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if got := transactionResponse.IsSuccessful(); got != tt.want { + t.Errorf("IsSuccessful() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/immediate/transaction.go b/modules/orders/internal/transactions/immediate/transaction.go new file mode 100644 index 000000000..d2a94bee7 --- /dev/null +++ b/modules/orders/internal/transactions/immediate/transaction.go @@ -0,0 +1,32 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package immediate + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "immediate", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.ClassificationID, + constants.TakerID, + constants.MakerOwnableID, + constants.TakerOwnableID, + constants.ExpiresIn, + constants.MakerOwnableSplit, + constants.TakerOwnableSplit, + constants.ImmutableMetaProperties, + constants.ImmutableProperties, + constants.MutableMetaProperties, + constants.MutableProperties, +) diff --git a/modules/orders/internal/transactions/make/keeper.go b/modules/orders/internal/transactions/make/keeper.go new file mode 100644 index 000000000..4d469419a --- /dev/null +++ b/modules/orders/internal/transactions/make/keeper.go @@ -0,0 +1,114 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package make + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/verify" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/properties/constants" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + conformAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + maintainersVerifyAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.maintainersVerifyAuxiliary.GetKeeper().Help(context, verify.NewAuxiliaryRequest(message.ClassificationID, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + if auxiliaryResponse := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(message.FromID, module.ModuleIdentityID, message.MakerOwnableID, message.MakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + immutableMetaProperties := message.ImmutableMetaProperties. + Add(baseProperties.NewMetaProperty(constants.ExchangeRateProperty.GetKey(), baseData.NewDecData(message.TakerOwnableSplit.QuoTruncate(sdkTypes.SmallestDec()).QuoTruncate(message.MakerOwnableSplit)))). + Add(baseProperties.NewMetaProperty(constants.CreationHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(context.BlockHeight())))). + Add(baseProperties.NewMetaProperty(constants.MakerOwnableIDProperty.GetKey(), baseData.NewIDData(message.MakerOwnableID))). + Add(baseProperties.NewMetaProperty(constants.TakerOwnableIDProperty.GetKey(), baseData.NewIDData(message.TakerOwnableID))). + Add(baseProperties.NewMetaProperty(constants.MakerIDProperty.GetKey(), baseData.NewIDData(message.FromID))). + Add(baseProperties.NewMetaProperty(constants.TakerIDProperty.GetKey(), baseData.NewIDData(message.TakerID))) + + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(append(immutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...)...)) + + orderID := baseIDs.NewOrderID(message.ClassificationID, immutables) + orders := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(orderID)) + + if orders.Get(key.NewKey(orderID)) != nil { + return newTransactionResponse(errorConstants.EntityAlreadyExists) + } + + mutableMetaProperties := message.MutableMetaProperties. + Add(baseProperties.NewMetaProperty(constants.ExpiryHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(message.ExpiresIn.Get()+context.BlockHeight())))). + Add(baseProperties.NewMetaProperty(constants.MakerOwnableSplitProperty.GetKey(), baseData.NewDecData(message.MakerOwnableSplit))) + + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(append(mutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...)) + + if auxiliaryResponse := transactionKeeper.conformAuxiliary.GetKeeper().Help(context, conform.NewAuxiliaryRequest(message.ClassificationID, immutables, mutables)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + orders.Add(mappable.NewMappable(base.NewOrder(message.ClassificationID, immutables, mutables))) + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, externalKeeper := range auxiliaries { + switch value := externalKeeper.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case conform.Auxiliary.GetName(): + transactionKeeper.conformAuxiliary = value + case supplement.Auxiliary.GetName(): + transactionKeeper.supplementAuxiliary = value + case transfer.Auxiliary.GetName(): + transactionKeeper.transferAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + case verify.Auxiliary.GetName(): + transactionKeeper.maintainersVerifyAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/orders/internal/transactions/make/keeper_test.go b/modules/orders/internal/transactions/make/keeper_test.go index d1aefb258..b6eac110a 100644 --- a/modules/orders/internal/transactions/make/keeper_test.go +++ b/modules/orders/internal/transactions/make/keeper_test.go @@ -1,56 +1,67 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package make import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/test" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/conform" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/mint" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/transfer" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/verify" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +var ( + conformAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + maintainersVerifyAuxiliary helpers.Auxiliary ) type TestKeepers struct { - OrdersKeeper helpers.TransactionKeeper + MakeKeeper helpers.TransactionKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func CreateTestInput(t *testing.T) (types.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + storeKey := types.NewKVStoreKey("test") + paramsStoreKey := types.NewKVStoreKey("testParams") + paramsTransientStoreKeys := types.NewTransientStoreKey("testParamsTransient") Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) paramsKeeper := params.NewKeeper( Codec, @@ -61,128 +72,161 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) - - context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + commitMultiStore.MountStoreWithDB(storeKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, types.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + supplementAuxiliary = supplement.AuxiliaryMock.Initialize(Mapper, Parameters) + transferAuxiliary = transfer.AuxiliaryMock.Initialize(Mapper, Parameters) + conformAuxiliary = conform.AuxiliaryMock.Initialize(Mapper, Parameters) + maintainersVerifyAuxiliary = verify.AuxiliaryMock.Initialize(Mapper, Parameters) + + context := types.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", - }, false, log.NewNopLogger()).WithBlockHeight(100) - - scrubAuxiliary := scrub.AuxiliaryMock.Initialize(Mapper, Parameters) - conformAuxiliary := conform.AuxiliaryMock.Initialize(Mapper, Parameters) - transferAuxiliary := transfer.AuxiliaryMock.Initialize(Mapper, Parameters) - verifyAuxiliary := verify.AuxiliaryMock.Initialize(Mapper, Parameters) - mintAuxiliary := mint.AuxiliaryMock.Initialize(Mapper, Parameters) - supplementAuxiliary := supplement.AuxiliaryMock.Initialize(Mapper, Parameters) + }, false, log.NewNopLogger()) + keepers := TestKeepers{ - OrdersKeeper: keeperPrototype().Initialize(Mapper, Parameters, - []interface{}{scrubAuxiliary, verifyAuxiliary, - conformAuxiliary, transferAuxiliary, mintAuxiliary, supplementAuxiliary}).(helpers.TransactionKeeper), + MakeKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), } - return context, keepers + return context, keepers, Mapper, Parameters } -func Test_transactionKeeper_Transact(t *testing.T) { +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - context, keepers := CreateTestInput(t) - immutableMetaProperties, Error := base.ReadMetaProperties("defaultImmutableMeta1:S|defaultImmutableMeta1") - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties("defaultImmutable1:S|defaultImmutable1") - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties("makerOwnableSplit:D|1") - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties("defaultMutable1:S|defaultMutable1") - require.Equal(t, nil, Error) - conformMockErrorProperties, Error := base.ReadMetaProperties("conformError:S|mockError") - require.Equal(t, nil, Error) - scrubMockErrorProperties, Error := base.ReadMetaProperties("scrubError:S|mockError") - require.Equal(t, nil, Error) - verifyMockErrorAddress := sdkTypes.AccAddress("verifyError") - defaultAddr := sdkTypes.AccAddress("addr") - defaultIdentityID := base.NewID("fromID") - classificationID := base.NewID("classificationID") - makerOwnableID := base.NewID("makerOwnableID") - takerOwnableID := base.NewID("takerOwnableID") - - t.Run("PositiveCase", func(t *testing.T) { - want := newTransactionResponse(nil) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, classificationID, - makerOwnableID, takerOwnableID, base.NewHeight(0), sdkTypes.SmallestDec(), sdkTypes.OneDec(), - immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - Order already exists", func(t *testing.T) { - want := newTransactionResponse(errors.EntityAlreadyExists) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, classificationID, - makerOwnableID, takerOwnableID, base.NewHeight(0), sdkTypes.SmallestDec(), sdkTypes.OneDec(), - immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - Identity mock error", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact( - context, - newMessage( - verifyMockErrorAddress, - defaultIdentityID, - classificationID, - makerOwnableID, - takerOwnableID, - base.NewHeight(0), - sdkTypes.SmallestDec(), - sdkTypes.OneDec(), - immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - conform mock fail", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, classificationID, - makerOwnableID, takerOwnableID, base.NewHeight(0), sdkTypes.OneDec(), sdkTypes.OneDec(), - immutableMetaProperties, immutableProperties, mutableMetaProperties, conformMockErrorProperties.RemoveData())); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - mutables scrub mock fail", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, classificationID, - makerOwnableID, takerOwnableID, base.NewHeight(0), sdkTypes.OneDec(), sdkTypes.OneDec(), - immutableMetaProperties, immutableProperties, scrubMockErrorProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - immutables scrub mock fail", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, classificationID, - makerOwnableID, takerOwnableID, base.NewHeight(0), sdkTypes.SmallestDec(), sdkTypes.OneDec(), - scrubMockErrorProperties, immutableProperties, mutableMetaProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - Transfer mock fail", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, classificationID, - base.NewID("transferError"), takerOwnableID, base.NewHeight(0), sdkTypes.SmallestDec(), sdkTypes.OneDec(), - immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := CreateTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + conformAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + maintainersVerifyAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve with nil", fields{}, args{}, transactionKeeper{}}, + {"+ve", fields{Mapper, Parameters, conformAuxiliary, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary, maintainersVerifyAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, conformAuxiliary, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary, maintainersVerifyAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + conformAuxiliary: tt.fields.conformAuxiliary, + supplementAuxiliary: tt.fields.supplementAuxiliary, + transferAuxiliary: tt.fields.transferAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + maintainersVerifyAuxiliary: tt.fields.maintainersVerifyAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters := CreateTestInput(t) + mutableMetaProperties := baseLists.NewPropertyList( + baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())), + baseProperties.NewMetaProperty(baseIDs.NewStringID("exchangeRate"), baseData.NewDecData(types.NewDec(10))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerOwnableID"), baseData.NewIDData(baseIDs.NewOwnableID(baseIDs.NewStringID("makerID")))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("creationHeight"), baseData.NewHeightData(baseTypes.NewHeight(1))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("takerOwnableID"), baseData.NewIDData(baseIDs.NewOwnableID(baseIDs.NewStringID("takerID")))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(baseIDs.PrototypeIdentityID())), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(baseIDs.PrototypeIdentityID())), + ) + mutableProperties := baseLists.NewPropertyList( + baseProperties.NewMesaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())), + ) + immutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + immutableProperties := baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + immutablesMeta := baseQualified.NewImmutables(immutableMetaProperties) + mutablesMeta := baseQualified.NewMutables(mutableMetaProperties) + testClassificationID := baseIDs.NewClassificationID(immutablesMeta, mutablesMeta) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutablesMeta) + testTakerID := baseIDs.PrototypeIdentityID() + mutableMetaProperties.Mutate( + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(testFromID)), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(testFromID))) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + testIdentity := baseDocuments.NewIdentity(testClassificationID, immutablesMeta, mutablesMeta) + testIdentity.ProvisionAddress([]types.AccAddress{fromAccAddress}...) + testOrder := baseDocuments.NewOrder(testClassificationID, immutablesMeta, mutablesMeta) + // testOrderID := mappable.NewMappable(testOrder).GetKey() + testMakerOwnableID := baseIDs.NewOwnableID(baseIDs.NewStringID("makerID")) + testTakerOwnableID := baseIDs.NewOwnableID(baseIDs.NewStringID("takerID")) + testRate := types.NewDec(10) + testHeight := baseTypes.NewHeight(1) + // testOrderID := baseIDs.NewOrderID(testClassificationID, testMakerOwnableID, testTakerOwnableID, testRate, testHeight, testFromID, immutablesMeta) + // testOrderID2 := baseIDs.NewOrderID(testClassificationID, testTakerOwnableID, testTakerOwnableID, testRate, testHeight, testFromID, immutablesMeta) + keepers.MakeKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testOrder)) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + conformAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + maintainersVerifyAuxiliary helpers.Auxiliary + } + type args struct { + context types.Context + msg types.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, Parameters, conformAuxiliary, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary, maintainersVerifyAuxiliary}, args{context, newMessage(fromAccAddress, testFromID, testClassificationID, testTakerID, testMakerOwnableID, testTakerOwnableID, testHeight, testRate, testRate, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties)}, newTransactionResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + conformAuxiliary: tt.fields.conformAuxiliary, + supplementAuxiliary: tt.fields.supplementAuxiliary, + transferAuxiliary: tt.fields.transferAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + maintainersVerifyAuxiliary: tt.fields.maintainersVerifyAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/make/message.go b/modules/orders/internal/transactions/make/message.go index 32efd25f2..01b8d29b5 100644 --- a/modules/orders/internal/transactions/make/message.go +++ b/modules/orders/internal/transactions/make/message.go @@ -1,86 +1,107 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package make import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/types" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ids.ClassificationID `json:"classificationID" valid:"required~required field classificationID missing"` + TakerID ids.IdentityID `json:"takerID" valid:"required~required field takerID missing"` + MakerOwnableID ids.OwnableID `json:"makerOwnableID" valid:"required~required field makerOwnableID missing"` + TakerOwnableID ids.OwnableID `json:"takerOwnableID" valid:"required~required field takerOwnableID missing"` + ExpiresIn types.Height `json:"expiresIn" valid:"required~required field expiresIn missing"` + MakerOwnableSplit sdkTypes.Dec `json:"makerOwnableSplit" valid:"required~required field makerOwnableSplit missing"` + TakerOwnableSplit sdkTypes.Dec `json:"takerOwnableSplit" valid:"required~required field takerOwnableSplit missing"` + ImmutableMetaProperties lists.PropertyList `json:"immutableMetaProperties" valid:"required~required field immutableMetaProperties missing"` + ImmutableProperties lists.PropertyList `json:"immutableProperties" valid:"required~required field immutableProperties missing"` + MutableMetaProperties lists.PropertyList `json:"mutableMetaProperties" valid:"required~required field mutableMetaProperties missing"` + MutableProperties lists.PropertyList `json:"mutableProperties" valid:"required~required field mutableProperties missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } - if message.MakerOwnableID.Compare(&message.TakerOwnableID) == 0 { - return errors.Wrap(xprtErrors.IncorrectMessage, "") + if message.MakerOwnableID.Compare(message.TakerOwnableID) == 0 { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, "") } if message.TakerOwnableSplit.LTE(sdkTypes.ZeroDec()) || message.MakerOwnableSplit.LTE(sdkTypes.ZeroDec()) { - return errors.Wrap(xprtErrors.IncorrectMessage, "") + return sdkErrors.Wrap(errorConstants.IncorrectMessage, "") } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + if len(message.ImmutableMetaProperties.GetList()) == 0 { + message.ImmutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.ImmutableProperties.GetList()) == 0 { + message.ImmutableProperties = base.NewPropertyList(nil) + } + if len(message.MutableMetaProperties.GetList()) == 0 { + message.MutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.MutableProperties.GetList()) == 0 { + message.MutableProperties = base.NewPropertyList(nil) + } + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, classificationID types.ID, makerOwnableID types.ID, takerOwnableID types.ID, expiresIn types.Height, makerOwnableSplit sdkTypes.Dec, takerOwnableSplit sdkTypes.Dec, immutableMetaProperties types.MetaProperties, immutableProperties types.Properties, mutableMetaProperties types.MetaProperties, mutableProperties types.Properties) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - ClassificationID: *base.NewID(classificationID.String()), - MakerOwnableID: *base.NewID(makerOwnableID.String()), - TakerOwnableID: *base.NewID(takerOwnableID.String()), - ExpiresIn: *base.NewHeight(expiresIn.Get()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, classificationID ids.ClassificationID, takerID ids.IdentityID, makerOwnableID ids.OwnableID, takerOwnableID ids.OwnableID, expiresIn types.Height, makerOwnableSplit sdkTypes.Dec, takerOwnableSplit sdkTypes.Dec, immutableMetaProperties lists.PropertyList, immutableProperties lists.PropertyList, mutableMetaProperties lists.PropertyList, mutableProperties lists.PropertyList) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + ClassificationID: classificationID, + TakerID: takerID, + MakerOwnableID: makerOwnableID, + TakerOwnableID: takerOwnableID, + ExpiresIn: expiresIn, MakerOwnableSplit: makerOwnableSplit, TakerOwnableSplit: takerOwnableSplit, - ImmutableMetaProperties: *base.NewMetaProperties(immutableMetaProperties.GetList()...), - ImmutableProperties: *base.NewProperties(immutableProperties.GetList()...), - MutableMetaProperties: *base.NewMetaProperties(mutableMetaProperties.GetList()...), - MutableProperties: *base.NewProperties(mutableProperties.GetList()...), + ImmutableMetaProperties: immutableMetaProperties, + ImmutableProperties: immutableProperties, + MutableMetaProperties: mutableMetaProperties, + MutableProperties: mutableProperties, } } diff --git a/modules/orders/internal/transactions/make/message.pb.go b/modules/orders/internal/transactions/make/message.pb.go deleted file mode 100644 index 004656d8b..000000000 --- a/modules/orders/internal/transactions/make/message.pb.go +++ /dev/null @@ -1,1066 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/transactions/make/message.proto - -package make - -import ( - context "context" - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - ClassificationID base.ID `protobuf:"bytes,3,opt,name=classification_i_d,json=classificationID,proto3" json:"classification_i_d" valid:"required~required field ClassificationID missing"` - MakerOwnableID base.ID `protobuf:"bytes,4,opt,name=maker_ownable_i_d,json=makerOwnableID,proto3" json:"maker_ownable_i_d" valid:"required~required field MakerOwnableID missing"` - TakerOwnableID base.ID `protobuf:"bytes,5,opt,name=taker_ownable_i_d,json=takerOwnableID,proto3" json:"taker_ownable_i_d" valid:"required~required field TakerOwnableID missing"` - ExpiresIn base.Height `protobuf:"bytes,6,opt,name=expires_in,json=expiresIn,proto3" json:"expires_in" valid:"required~required field ExpiresIn missing"` - MakerOwnableSplit github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,7,opt,name=maker_ownable_split,json=makerOwnableSplit,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"maker_ownable_split" valid:"required~required field MakerOwnableSplit missing"` - TakerOwnableSplit github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,8,opt,name=taker_ownable_split,json=takerOwnableSplit,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"taker_ownable_split" valid:"required~required field TakerOwnableSplit missing"` - ImmutableMetaProperties base.MetaProperties `protobuf:"bytes,9,opt,name=immutable_meta_properties,json=immutableMetaProperties,proto3" json:"immutable_meta_properties" valid:"required~required field ImmutableMetaProperties missing"` - ImmutableProperties base.Properties `protobuf:"bytes,10,opt,name=immutable_properties,json=immutableProperties,proto3" json:"immutable_properties" valid:"required~required field ImmutableProperties missing"` - MutableMetaProperties base.MetaProperties `protobuf:"bytes,11,opt,name=mutable_meta_properties,json=mutableMetaProperties,proto3" json:"mutable_meta_properties" valid:"required~required field MutableMetaProperties missing"` - MutableProperties base.Properties `protobuf:"bytes,12,opt,name=mutable_properties,json=mutableProperties,proto3" json:"mutable_properties" valid:"required~required field MutableProperties missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_b39e195093bc7cab, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_b39e195093bc7cab, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.orders.internal.transactions.make.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.orders.internal.transactions.make.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/orders/internal/transactions/make/message.proto", fileDescriptor_b39e195093bc7cab) -} - -var fileDescriptor_b39e195093bc7cab = []byte{ - // 766 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0xd6, 0xcd, 0x4f, 0x13, 0x4d, - 0x18, 0x00, 0xf0, 0xce, 0x0b, 0x2f, 0x1f, 0xc3, 0x1b, 0xf2, 0xb2, 0x40, 0xe8, 0xcb, 0xa1, 0x6d, - 0x9a, 0xbc, 0x06, 0x8d, 0xcc, 0x06, 0x4c, 0x88, 0xc5, 0xf8, 0x41, 0x29, 0x62, 0x63, 0x2a, 0x06, - 0x38, 0x79, 0x69, 0xb6, 0xbb, 0xd3, 0x76, 0xc2, 0xce, 0xce, 0x3a, 0x33, 0x15, 0x3d, 0xe8, 0xc5, - 0x8b, 0x47, 0x3c, 0x78, 0xd2, 0x44, 0x0e, 0x7a, 0xf7, 0xe4, 0xdf, 0xc0, 0x91, 0x93, 0x31, 0x1e, - 0x1a, 0x03, 0x17, 0xcf, 0xfc, 0x05, 0x66, 0x67, 0xb7, 0xe9, 0xf6, 0x03, 0x76, 0xc1, 0x70, 0xda, - 0x65, 0x67, 0xe6, 0x79, 0x7e, 0x3c, 0xb3, 0xcf, 0x76, 0xe0, 0xba, 0x8b, 0xb9, 0x20, 0x42, 0x62, - 0xc7, 0xc4, 0x65, 0x61, 0xed, 0xe8, 0x94, 0x59, 0x0d, 0x1b, 0x0b, 0x9d, 0x71, 0x0b, 0x73, 0xa1, - 0x13, 0x47, 0x62, 0xee, 0x18, 0xb6, 0x2e, 0xb9, 0xe1, 0x08, 0xc3, 0x94, 0x84, 0x39, 0x42, 0xa7, - 0xc6, 0x0e, 0xd6, 0x29, 0x16, 0xc2, 0xa8, 0x61, 0xe4, 0x72, 0x26, 0x99, 0x96, 0xeb, 0x0a, 0x84, - 0x82, 0x40, 0xc8, 0x0f, 0x84, 0x5a, 0x81, 0x50, 0x38, 0x10, 0xf2, 0x02, 0xcd, 0x4e, 0xd5, 0x58, - 0x8d, 0xa9, 0x28, 0xba, 0x77, 0xe7, 0x07, 0x9c, 0xbd, 0xd6, 0x2d, 0x13, 0x66, 0x1d, 0x53, 0x43, - 0x97, 0x2f, 0x5c, 0x2c, 0xf4, 0x8a, 0x21, 0xb0, 0x4e, 0xac, 0x60, 0xee, 0x62, 0xf4, 0x5c, 0x97, - 0x33, 0x17, 0x73, 0x49, 0xb0, 0x08, 0xd6, 0x2c, 0x45, 0xaf, 0xa1, 0x58, 0x1a, 0x8f, 0xbb, 0xd7, - 0xa1, 0xe8, 0x75, 0x75, 0x4c, 0x6a, 0x75, 0xe9, 0xcf, 0xcf, 0x7e, 0x1b, 0x87, 0xc3, 0x25, 0xbf, - 0x54, 0xda, 0x5b, 0x00, 0x07, 0xab, 0x9c, 0xd1, 0x24, 0xc8, 0x80, 0xb9, 0xd1, 0xfc, 0xcb, 0x83, - 0x66, 0x3a, 0xf1, 0xa3, 0x99, 0x5e, 0xab, 0x11, 0x59, 0x6f, 0x54, 0x90, 0xc9, 0xa8, 0x1e, 0x8a, - 0xbe, 0xe1, 0xe0, 0xf0, 0x9f, 0x5b, 0x85, 0x87, 0xbd, 0xb9, 0xd0, 0x8a, 0x69, 0xae, 0x58, 0x16, - 0xc7, 0x42, 0x9c, 0x34, 0xd3, 0xd7, 0x9f, 0x19, 0x36, 0xb1, 0x96, 0xb3, 0x1c, 0x3f, 0x6d, 0x10, - 0x8e, 0xad, 0x57, 0xad, 0x9b, 0x4c, 0x95, 0x60, 0xdb, 0xca, 0xdc, 0xe7, 0x8c, 0x66, 0x28, 0x11, - 0x82, 0x38, 0xb5, 0xec, 0xa6, 0xa2, 0x68, 0xbb, 0x70, 0xc4, 0xbb, 0x96, 0x49, 0xd9, 0x4a, 0xfe, - 0x95, 0x01, 0x73, 0x63, 0x8b, 0xff, 0x77, 0xff, 0x8b, 0xc8, 0x4f, 0x8b, 0x54, 0x5a, 0xa4, 0xd2, - 0x16, 0x0b, 0xf9, 0x25, 0x4f, 0x7f, 0xd2, 0x4c, 0xa3, 0x18, 0x49, 0x8b, 0x85, 0x76, 0xda, 0xa1, - 0xaa, 0x7a, 0xa0, 0xbd, 0x03, 0x50, 0x33, 0x6d, 0x43, 0x08, 0x52, 0x25, 0xa6, 0xe1, 0xbd, 0x0f, - 0xca, 0x30, 0x70, 0x1e, 0xc3, 0xbd, 0xc0, 0x70, 0x33, 0xc2, 0xb0, 0xda, 0x91, 0x27, 0xac, 0xf9, - 0xd7, 0xec, 0x1a, 0xd2, 0xf6, 0x00, 0x9c, 0xf0, 0xde, 0x4b, 0x5e, 0x66, 0xbb, 0x8e, 0x51, 0xb1, - 0xb1, 0x62, 0x0d, 0x9e, 0x87, 0x75, 0x27, 0x60, 0x2d, 0x45, 0xb0, 0x4a, 0x5e, 0x9a, 0x0d, 0x3f, - 0x4b, 0x18, 0x35, 0x4e, 0x3b, 0x06, 0x14, 0x49, 0xf6, 0x90, 0xfe, 0xbe, 0x0c, 0xd2, 0xf6, 0x69, - 0x24, 0xd9, 0x49, 0x7a, 0x0d, 0x20, 0xc4, 0xcf, 0x5d, 0xc2, 0xb1, 0x28, 0x13, 0x27, 0x39, 0xa4, - 0x2c, 0x57, 0x63, 0x58, 0x1e, 0xa8, 0xe6, 0xc8, 0xe7, 0x02, 0xcf, 0x42, 0x84, 0x67, 0xcd, 0xcf, - 0x51, 0x74, 0xda, 0x94, 0x51, 0xdc, 0x7a, 0xa6, 0xbd, 0x07, 0x70, 0xb2, 0x73, 0xaf, 0x84, 0x6b, - 0x13, 0x99, 0x1c, 0x56, 0xfd, 0xb5, 0x13, 0xf4, 0xd7, 0x95, 0x50, 0x7f, 0x99, 0x4c, 0x50, 0x26, - 0x82, 0xcb, 0xbc, 0xd7, 0xbf, 0xbe, 0xad, 0x80, 0xcd, 0x93, 0x66, 0x3a, 0x77, 0x8e, 0x0d, 0xdb, - 0xf2, 0x32, 0xb5, 0x55, 0x13, 0xb4, 0x7b, 0x4c, 0xe9, 0x64, 0x1f, 0xdd, 0xc8, 0x25, 0xe9, 0xb6, - 0xcf, 0xd0, 0xc9, 0x1e, 0xdd, 0x57, 0x00, 0xff, 0x23, 0x94, 0x36, 0xa4, 0x92, 0x79, 0xdf, 0xba, - 0x72, 0xfb, 0x23, 0x99, 0x1c, 0x55, 0x1b, 0xba, 0x10, 0x63, 0x43, 0x4b, 0x1d, 0x5f, 0xc9, 0xfc, - 0x7a, 0xb0, 0xb1, 0x77, 0x23, 0xb0, 0xc5, 0x56, 0xea, 0xce, 0xf5, 0x6d, 0xf2, 0x0c, 0xe9, 0x3f, - 0x43, 0xfb, 0x0c, 0xe0, 0x54, 0x1b, 0x1e, 0x32, 0x43, 0x65, 0x9e, 0x8f, 0x61, 0x0e, 0x79, 0x57, - 0x03, 0xef, 0xad, 0xb8, 0xde, 0x7e, 0xd6, 0x49, 0xd2, 0x3b, 0xaa, 0x7d, 0x01, 0x70, 0xe6, 0xb4, - 0xf2, 0x8e, 0x5d, 0xb4, 0xbc, 0x6b, 0x01, 0xf7, 0x76, 0xd4, 0x9b, 0x7a, 0x76, 0x71, 0xa7, 0xfb, - 0x97, 0xf6, 0x23, 0x80, 0x5a, 0x9f, 0xc2, 0xfe, 0x73, 0x91, 0xc2, 0xae, 0x04, 0xd2, 0x5c, 0x3c, - 0x69, 0x3f, 0xe5, 0x44, 0x4f, 0x51, 0x97, 0x47, 0xde, 0xec, 0xa7, 0x13, 0xbf, 0xf6, 0xd3, 0x89, - 0xec, 0x34, 0x9c, 0xdc, 0x6e, 0x9f, 0x25, 0x36, 0xb1, 0x70, 0x99, 0x23, 0xf0, 0xe2, 0x27, 0x00, - 0x07, 0x4a, 0xa2, 0xa6, 0x7d, 0x00, 0x70, 0xd0, 0x6b, 0x57, 0x2d, 0x8f, 0x2e, 0x7c, 0x34, 0x41, - 0xc1, 0x0f, 0xf7, 0xec, 0xa3, 0x3f, 0x88, 0xd1, 0x07, 0x99, 0x4d, 0xe4, 0xed, 0x83, 0xa3, 0x14, - 0x38, 0x3c, 0x4a, 0x81, 0x9f, 0x47, 0x29, 0xb0, 0x77, 0x9c, 0x4a, 0x1c, 0x1e, 0xa7, 0x12, 0xdf, - 0x8f, 0x53, 0x89, 0x27, 0x9b, 0xb1, 0x4f, 0x03, 0xb1, 0xcf, 0x6a, 0x95, 0x21, 0x75, 0x16, 0xb9, - 0xf1, 0x3b, 0x00, 0x00, 0xff, 0xff, 0xef, 0xba, 0x80, 0x9b, 0xef, 0x09, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Make(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Make(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.orders.internal.transactions.make.Msg/Make", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Make(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Make(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Make not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Make_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Make(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.orders.internal.transactions.make.Msg/Make", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Make(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.orders.internal.transactions.make.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Make", - Handler: _Msg_Make_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/orders/internal/transactions/make/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x62 - { - size, err := m.MutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x5a - { - size, err := m.ImmutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - { - size, err := m.ImmutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - { - size := m.TakerOwnableSplit.Size() - i -= size - if _, err := m.TakerOwnableSplit.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - { - size := m.MakerOwnableSplit.Size() - i -= size - if _, err := m.MakerOwnableSplit.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size, err := m.ExpiresIn.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size, err := m.TakerOwnableID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.MakerOwnableID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ClassificationID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ClassificationID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MakerOwnableID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.TakerOwnableID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ExpiresIn.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MakerOwnableSplit.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.TakerOwnableSplit.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ImmutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MakerOwnableID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MakerOwnableID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TakerOwnableID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TakerOwnableID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExpiresIn", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExpiresIn.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MakerOwnableSplit", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MakerOwnableSplit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TakerOwnableSplit", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TakerOwnableSplit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ImmutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ImmutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/orders/internal/transactions/make/message_test.go b/modules/orders/internal/transactions/make/message_test.go index 5ba834d86..7b1d76eff 100644 --- a/modules/orders/internal/transactions/make/message_test.go +++ b/modules/orders/internal/transactions/make/message_test.go @@ -1,57 +1,377 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package make import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/codec" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/types" + "github.com/AssetMantle/modules/schema/types/base" + "github.com/AssetMantle/modules/utilities/transaction" +) + +var ( + expiresInHeight = base.NewHeight(60) + testMessage = newMessage(fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties) ) -func Test_Make_Message(t *testing.T) { - - FromID := base.NewID("fromID") - classificationID := base.NewID("classificationID") - makerOwnableID := base.NewID("makerOwnableID") - takerOwnableID := base.NewID("takerOwnableID") - expiresIn := base.NewHeight(12) - makerOwnableSplit := sdkTypes.NewDec(2) - takerOwnableSplit := sdkTypes.NewDec(1) - zeroTakerOwnableSplit := sdkTypes.ZeroDec() - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - immutableMetaProperties, Error := base.ReadMetaProperties("defaultImmutableMeta1:S|defaultImmutableMeta1") - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties("defaultImmutable1:S|defaultImmutable1") - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties("defaultMutableMeta1:S|defaultMutableMeta1") - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties("defaultMutable1:S|defaultMutable1") - require.Equal(t, nil, Error) - - testMessage := newMessage(fromAccAddress, FromID, classificationID, makerOwnableID, takerOwnableID, expiresIn, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties) - require.Equal(t, Message{From: fromAccAddress, FromID: FromID, ClassificationID: classificationID, MakerOwnableID: makerOwnableID, TakerOwnableID: takerOwnableID, ExpiresIn: expiresIn, TakerOwnableSplit: takerOwnableSplit, MakerOwnableSplit: makerOwnableSplit, ImmutableMetaProperties: immutableMetaProperties, ImmutableProperties: immutableProperties, MutableMetaProperties: mutableMetaProperties, MutableProperties: mutableProperties}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) - require.Error(t, errors.Wrap(xprtErrors.IncorrectMessage, ""), newMessage(fromAccAddress, FromID, classificationID, makerOwnableID, takerOwnableID, expiresIn, makerOwnableSplit, zeroTakerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties).ValidateBasic()) - require.Error(t, errors.Wrap(xprtErrors.IncorrectMessage, ""), newMessage(fromAccAddress, FromID, classificationID, makerOwnableID, makerOwnableID, expiresIn, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties).ValidateBasic()) +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{testMessage}, message{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + TakerID ids.IdentityID + MakerOwnableID ids.OwnableID + TakerOwnableID ids.OwnableID + ExpiresIn types.Height + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(testMessage))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + TakerID ids.IdentityID + MakerOwnableID ids.OwnableID + TakerOwnableID ids.OwnableID + ExpiresIn types.Height + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + TakerID ids.IdentityID + MakerOwnableID ids.OwnableID + TakerOwnableID ids.OwnableID + ExpiresIn types.Height + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + TakerID ids.IdentityID + MakerOwnableID ids.OwnableID + TakerOwnableID ids.OwnableID + ExpiresIn types.Height + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + TakerID ids.IdentityID + MakerOwnableID ids.OwnableID + TakerOwnableID ids.OwnableID + ExpiresIn types.Height + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + ClassificationID ids.ClassificationID + TakerID ids.IdentityID + MakerOwnableID ids.OwnableID + TakerOwnableID ids.OwnableID + ExpiresIn types.Height + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ImmutableMetaProperties lists.PropertyList + ImmutableProperties lists.PropertyList + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, false}, + {"-ve for nil", fields{}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + classificationID ids.ClassificationID + takerID ids.IdentityID + makerOwnableID ids.OwnableID + takerOwnableID ids.OwnableID + expiresIn types.Height + makerOwnableSplit sdkTypes.Dec + takerOwnableSplit sdkTypes.Dec + immutableMetaProperties lists.PropertyList + immutableProperties lists.PropertyList + mutableMetaProperties lists.PropertyList + mutableProperties lists.PropertyList + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}, message{fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, expiresInHeight, makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.classificationID, tt.args.takerID, tt.args.makerOwnableID, tt.args.takerOwnableID, tt.args.expiresIn, tt.args.makerOwnableSplit, tt.args.takerOwnableSplit, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/make/msg_server.go b/modules/orders/internal/transactions/make/msg_server.go deleted file mode 100644 index df74f8b9f..000000000 --- a/modules/orders/internal/transactions/make/msg_server.go +++ /dev/null @@ -1,72 +0,0 @@ -package make - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/conform" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/transfer" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "strconv" -) - -type msgServer struct { - transactionKeeper -} - -func (msgServer msgServer) Make(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - if auxiliaryResponse := msgServer.transactionKeeper.transferAuxiliary.GetKeeper().Help(ctx, transfer.NewAuxiliaryRequest(&message.FromID, base.NewID(module.Name), &message.MakerOwnableID, message.MakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - immutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(message.ImmutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - immutableProperties := base.NewProperties(append(immutableMetaProperties.GetList(), message.ImmutableProperties.GetList()...)...) - - exchangeRate := message.TakerOwnableSplit.QuoTruncate(sdkTypes.SmallestDec()).QuoTruncate(message.MakerOwnableSplit) - orderID := key.NewOrderID(&message.ClassificationID, &message.MakerOwnableID, &message.TakerOwnableID, base.NewID(exchangeRate.String()), base.NewID(strconv.FormatInt(ctx.BlockHeight(), 10)), &message.FromID, immutableProperties) - orders := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(orderID)) - makerOwnableSplit := message.MakerOwnableSplit - - order := orders.Get(key.FromID(orderID)) - if order != nil { - return nil, errors.EntityAlreadyExists - } - - mutableMetaProperties := message.MutableMetaProperties.Add(base.NewMetaProperty(base.NewID(properties.Expiry), base.NewMetaFact(base.NewHeightData(base.NewHeight(message.ExpiresIn.Get()+ctx.BlockHeight()))))) - mutableMetaProperties = mutableMetaProperties.Add(base.NewMetaProperty(base.NewID(properties.MakerOwnableSplit), base.NewMetaFact(base.NewDecData(makerOwnableSplit)))) - - scrubbedMutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(mutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - mutableProperties := base.NewProperties(append(scrubbedMutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...) - - if auxiliaryResponse := msgServer.transactionKeeper.conformAuxiliary.GetKeeper().Help(ctx, conform.NewAuxiliaryRequest(&message.ClassificationID, immutableProperties, mutableProperties)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - orders.Add(mappable.NewOrder(orderID, immutableProperties, mutableProperties)) - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} - -var _ MsgServer = msgServer{} diff --git a/modules/orders/internal/transactions/make/request.go b/modules/orders/internal/transactions/make/request.go index 86cee20e0..b4b5d3688 100644 --- a/modules/orders/internal/transactions/make/request.go +++ b/modules/orders/internal/transactions/make/request.go @@ -1,28 +1,30 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package make import ( "encoding/json" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + baseTypes "github.com/AssetMantle/modules/schema/types/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { BaseReq rest.BaseReq `json:"baseReq"` FromID string `json:"fromID" valid:"required~required field fromID missing, matches(^[A-Za-z0-9-_=.|]+$)~invalid field fromID"` ClassificationID string `json:"classificationID" valid:"required~required field classificationID missing, matches(^[A-Za-z0-9-_=.]+$)~invalid field classificationID"` + TakerID string `json:"takerID" valid:"required~required field takerID missing, matches(^[A-Za-z0-9-_=.|]+$)~invalid field takerID"` MakerOwnableID string `json:"makerOwnableID" valid:"required~required field makerOwnableID missing, matches(^[A-Za-z0-9-_=.|]+$)~invalid field makerOwnableID"` TakerOwnableID string `json:"takerOwnableID" valid:"required~required field takerOwnableID missing, matches(^[A-Za-z0-9-_=.|]+$)~invalid field takerOwnableID"` ExpiresIn int64 `json:"expiresIn" valid:"required~required field expiresIn missing, matches(^[0-9]+$)~invalid field expiresIn"` @@ -36,39 +38,40 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary make order transaction -// @Descrption make order transaction +// Validate godoc +// @Summary Make order transaction +// @Description Make order transaction // @Accept text/plain // @Produce json // @Tags Orders -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body transactionRequest true "Request body to make order" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /orders/make [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ClassificationID), - cliCommand.ReadString(flags.MakerOwnableID), - cliCommand.ReadString(flags.TakerOwnableID), - cliCommand.ReadInt64(flags.ExpiresIn), - cliCommand.ReadString(flags.MakerOwnableSplit), - cliCommand.ReadString(flags.TakerOwnableSplit), - cliCommand.ReadString(flags.ImmutableMetaProperties), - cliCommand.ReadString(flags.ImmutableProperties), - cliCommand.ReadString(flags.MutableMetaProperties), - cliCommand.ReadString(flags.MutableProperties), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ClassificationID), + cliCommand.ReadString(constants.TakerID), + cliCommand.ReadString(constants.MakerOwnableID), + cliCommand.ReadString(constants.TakerOwnableID), + cliCommand.ReadInt64(constants.ExpiresIn), + cliCommand.ReadString(constants.MakerOwnableSplit), + cliCommand.ReadString(constants.TakerOwnableSplit), + cliCommand.ReadString(constants.ImmutableMetaProperties), + cliCommand.ReadString(constants.ImmutableProperties), + cliCommand.ReadString(constants.MutableMetaProperties), + cliCommand.ReadString(constants.MutableProperties), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -78,48 +81,76 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + makerOwnableSplit, err := sdkTypes.NewDecFromStr(transactionRequest.MakerOwnableSplit) + if err != nil { + return nil, err + } + + takerOwnableSplit, err := sdkTypes.NewDecFromStr(transactionRequest.TakerOwnableSplit) + if err != nil { + return nil, err + } + + immutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableMetaProperties) + if err != nil { + return nil, err + } + + immutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.ImmutableProperties) + if err != nil { + return nil, err + } + immutableProperties = immutableProperties.ScrubData() + + mutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableMetaProperties) + if err != nil { + return nil, err } - makerOwnableSplit, Error := sdkTypes.NewDecFromStr(transactionRequest.MakerOwnableSplit) - if Error != nil { - return nil, Error + mutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableProperties) + if err != nil { + return nil, err } + mutableProperties = mutableProperties.ScrubData() - takerOwnableSplit, Error := sdkTypes.NewDecFromStr(transactionRequest.TakerOwnableSplit) - if Error != nil { - return nil, Error + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err } - immutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.ImmutableMetaProperties) - if Error != nil { - return nil, Error + classificationID, err := baseIDs.ReadClassificationID(transactionRequest.ClassificationID) + if err != nil { + return nil, err } - immutableProperties, Error := base.ReadProperties(transactionRequest.ImmutableProperties) - if Error != nil { - return nil, Error + takerID, err := baseIDs.ReadIdentityID(transactionRequest.TakerID) + if err != nil { + return nil, err } - mutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.MutableMetaProperties) - if Error != nil { - return nil, Error + makerOwnableID, err := baseIDs.ReadOwnableID(transactionRequest.MakerOwnableID) + if err != nil { + return nil, err } - mutableProperties, Error := base.ReadProperties(transactionRequest.MutableProperties) - if Error != nil { - return nil, Error + takerOwnableID, err := baseIDs.ReadOwnableID(transactionRequest.TakerOwnableID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.ClassificationID), - base.NewID(transactionRequest.MakerOwnableID), - base.NewID(transactionRequest.TakerOwnableID), - base.NewHeight(transactionRequest.ExpiresIn), + fromID, + classificationID, + takerID, + makerOwnableID, + takerOwnableID, + baseTypes.NewHeight(transactionRequest.ExpiresIn), makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, @@ -128,18 +159,19 @@ func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { mutableProperties, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} } -func newTransactionRequest(baseReq rest.BaseReq, fromID string, classificationID string, makerOwnableID string, takerOwnableID string, expiresIn int64, makerOwnableSplit, takerOwnableSplit string, immutableMetaProperties string, immutableProperties string, mutableMetaProperties string, mutableProperties string) helpers.TransactionRequest { +func newTransactionRequest(baseReq rest.BaseReq, fromID string, classificationID string, takerID string, makerOwnableID string, takerOwnableID string, expiresIn int64, makerOwnableSplit, takerOwnableSplit string, immutableMetaProperties string, immutableProperties string, mutableMetaProperties string, mutableProperties string) helpers.TransactionRequest { return transactionRequest{ BaseReq: baseReq, FromID: fromID, ClassificationID: classificationID, + TakerID: takerID, MakerOwnableID: makerOwnableID, TakerOwnableID: takerOwnableID, ExpiresIn: expiresIn, diff --git a/modules/orders/internal/transactions/make/request_test.go b/modules/orders/internal/transactions/make/request_test.go index 7d3024ab1..8464d16ac 100644 --- a/modules/orders/internal/transactions/make/request_test.go +++ b/modules/orders/internal/transactions/make/request_test.go @@ -1,110 +1,423 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package make import ( "encoding/json" + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/spf13/viper" "github.com/stretchr/testify/require" - "testing" -) - -func Test_Define_Request(t *testing.T) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.ClassificationID, flags.MakerOwnableSplit, flags.MakerOwnableID, flags.TakerOwnableID, flags.ExpiresIn, flags.TakerOwnableSplit, flags.ImmutableMetaProperties, flags.ImmutableProperties, flags.MutableMetaProperties, flags.MutableProperties}) - cliContext := context.NewCLIContext().WithCodec(Codec) - - immutableMetaPropertiesString := "defaultImmutableMeta1:S|defaultImmutableMeta1" - immutablePropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" - mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" - mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - - immutableMetaProperties, Error := base.ReadMetaProperties(immutableMetaPropertiesString) - require.Equal(t, nil, Error) - immutableProperties, Error := base.ReadProperties(immutablePropertiesString) - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties(mutableMetaPropertiesString) - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties(mutablePropertiesString) - require.Equal(t, nil, Error) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", sdkTypes.OneDec().String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString) - - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ClassificationID: "classificationID", MakerOwnableID: "makerOwnableID", TakerOwnableID: "takerOwnableID", ExpiresIn: 123, MakerOwnableSplit: "2", TakerOwnableSplit: sdkTypes.OneDec().String(), ImmutableMetaProperties: immutableMetaPropertiesString, ImmutableProperties: immutablePropertiesString, MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) - - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ImmutableMetaProperties: "", ImmutableProperties: "", MutableMetaProperties: "", MutableProperties: ""}, requestFromCLI) - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, error3 := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, error3) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) - - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) - - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/schema/types/base" +) - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("classificationID"), base.NewID("makerOwnableID"), base.NewID("takerOwnableID"), base.NewHeight(123), sdkTypes.NewDec(2), sdkTypes.OneDec(), immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties), msg) - require.Nil(t, Error) +var ( + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = types.AccAddressFromBech32(fromAddress) + immutableMetaPropertiesString = "defaultImmutableMeta1:S|defaultImmutableMeta1" + immutablePropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" + mutableMetaPropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" + mutablePropertiesString = "defaultMutable1:S|defaultMutable1" + immutableMetaProperties, _ = utilities.ReadMetaPropertyList(immutableMetaPropertiesString) + immutableProperties, _ = utilities.ReadMetaPropertyList(immutablePropertiesString) + mutableMetaProperties, _ = utilities.ReadMetaPropertyList(mutableMetaPropertiesString) + mutableProperties, _ = utilities.ReadMetaPropertyList(mutablePropertiesString) + immutables = baseQualified.NewImmutables(immutableProperties) + mutables = baseQualified.NewMutables(mutableProperties) + testClassificationID = baseIDs.NewClassificationID(immutables, mutables) + testFromID = baseIDs.NewIdentityID(testClassificationID, immutables) + makerOwnableID = baseIDs.NewOwnableID(baseIDs.NewStringID("makerownableid")) + takerOwnableID = baseIDs.NewOwnableID(baseIDs.NewStringID("takerownableid")) + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + expiresIn = int64(60) + makerOwnableSplit = types.NewDec(60) + takerOwnableSplit = types.NewDec(60) +) - msg, Error = newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", sdkTypes.OneDec().String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + classificationID string + takerID string + makerOwnableID string + takerOwnableID string + expiresIn int64 + makerOwnableSplit string + takerOwnableSplit string + immutableMetaProperties string + immutableProperties string + mutableMetaProperties string + mutableProperties string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, newTransactionRequest(testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.classificationID, tt.args.takerID, tt.args.makerOwnableID, tt.args.takerOwnableID, tt.args.expiresIn, tt.args.makerOwnableSplit, tt.args.takerOwnableSplit, tt.args.immutableMetaProperties, tt.args.immutableProperties, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: fromAddress, ChainID: "test"}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "randomInput", sdkTypes.OneDec().String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", sdkTypes.OneDec().String(), "randomString", immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.ClassificationID, constants.TakerID, constants.MakerOwnableID, constants.TakerOwnableID, constants.ExpiresIn, constants.MakerOwnableSplit, constants.TakerOwnableSplit, constants.ImmutableMetaProperties, constants.ImmutableProperties, constants.MutableMetaProperties, constants.MutableProperties}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.FromID.GetName(), testFromID.String()) + viper.Set(constants.ClassificationID.GetName(), testClassificationID.String()) + viper.Set(constants.TakerID.GetName(), testFromID.String()) + viper.Set(constants.MakerOwnableID.GetName(), makerOwnableID.String()) + viper.Set(constants.TakerOwnableID.GetName(), takerOwnableID.String()) + viper.Set(constants.ExpiresIn.GetName(), expiresIn) + viper.Set(constants.MakerOwnableSplit.GetName(), makerOwnableSplit.String()) + viper.Set(constants.TakerOwnableSplit.GetName(), takerOwnableSplit.String()) + viper.Set(constants.ImmutableMetaProperties.GetName(), immutableMetaPropertiesString) + viper.Set(constants.ImmutableProperties.GetName(), immutablePropertiesString) + viper.Set(constants.MutableMetaProperties.GetName(), mutableMetaPropertiesString) + viper.Set(constants.MutableProperties.GetName(), mutablePropertiesString) + type fields struct { + BaseReq rest.BaseReq + FromID string + ClassificationID string + TakerID string + MakerOwnableID string + TakerOwnableID string + ExpiresIn int64 + MakerOwnableSplit string + TakerOwnableSplit string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, cliContext}, newTransactionRequest(testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", sdkTypes.OneDec().String(), immutableMetaPropertiesString, "randomString", mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_FromJSON(t *testing.T) { + jsonMessage, err := json.Marshal(newTransactionRequest(testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString)) + require.NoError(t, err) + type fields struct { + BaseReq rest.BaseReq + FromID string + ClassificationID string + TakerID string + MakerOwnableID string + TakerOwnableID string + ExpiresIn int64 + MakerOwnableSplit string + TakerOwnableSplit string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{jsonMessage}, newTransactionRequest(testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", sdkTypes.OneDec().String(), immutableMetaPropertiesString, immutablePropertiesString, "randomString", mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ClassificationID string + TakerID string + MakerOwnableID string + TakerOwnableID string + ExpiresIn int64 + MakerOwnableSplit string + TakerOwnableSplit string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", sdkTypes.OneDec().String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, "randomString").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ClassificationID string + TakerID string + MakerOwnableID string + TakerOwnableID string + ExpiresIn int64 + MakerOwnableSplit string + TakerOwnableSplit string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, newMessage(fromAccAddress, testFromID, testClassificationID, testFromID, makerOwnableID, takerOwnableID, base.NewHeight(60), makerOwnableSplit, takerOwnableSplit, immutableMetaProperties, immutableProperties, mutableMetaProperties, mutableProperties), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "classificationID", "makerOwnableID", "takerOwnableID", 123, "2", "test", immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, "randomString").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ClassificationID string + TakerID string + MakerOwnableID string + TakerOwnableID string + ExpiresIn int64 + MakerOwnableSplit string + TakerOwnableSplit string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ClassificationID string + TakerID string + MakerOwnableID string + TakerOwnableID string + ExpiresIn int64 + MakerOwnableSplit string + TakerOwnableSplit string + ImmutableMetaProperties string + ImmutableProperties string + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testClassificationID.String(), testFromID.String(), makerOwnableID.String(), takerOwnableID.String(), expiresIn, makerOwnableSplit.String(), takerOwnableSplit.String(), immutableMetaPropertiesString, immutablePropertiesString, mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ClassificationID: tt.fields.ClassificationID, + TakerID: tt.fields.TakerID, + MakerOwnableID: tt.fields.MakerOwnableID, + TakerOwnableID: tt.fields.TakerOwnableID, + ExpiresIn: tt.fields.ExpiresIn, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ImmutableMetaProperties: tt.fields.ImmutableMetaProperties, + ImmutableProperties: tt.fields.ImmutableProperties, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/orders/internal/transactions/make/response.go b/modules/orders/internal/transactions/make/response.go new file mode 100644 index 000000000..3fa303925 --- /dev/null +++ b/modules/orders/internal/transactions/make/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package make + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/orders/internal/transactions/make/transaction.go b/modules/orders/internal/transactions/make/transaction.go new file mode 100644 index 000000000..4fd025cd0 --- /dev/null +++ b/modules/orders/internal/transactions/make/transaction.go @@ -0,0 +1,32 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package make + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "make", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.ClassificationID, + constants.ExpiresIn, + constants.FromID, + constants.MakerOwnableID, + constants.MakerOwnableSplit, + constants.MutableMetaProperties, + constants.MutableProperties, + constants.TakerID, + constants.TakerOwnableSplit, + constants.TakerOwnableID, + constants.ImmutableMetaProperties, + constants.ImmutableProperties, +) diff --git a/modules/orders/internal/transactions/modify/keeper.go b/modules/orders/internal/transactions/modify/keeper.go new file mode 100644 index 000000000..c9bb0f29b --- /dev/null +++ b/modules/orders/internal/transactions/modify/keeper.go @@ -0,0 +1,104 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package modify + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/properties/constants" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + conformAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + orders := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.OrderID)) + + Mappable := orders.Get(key.NewKey(message.OrderID)) + if Mappable == nil { + return newTransactionResponse(errorConstants.EntityNotFound) + } + order := Mappable.(documents.Order) + + transferMakerOwnableSplit := message.MakerOwnableSplit.Sub(order.GetMakerOwnableSplit()) + + if transferMakerOwnableSplit.LT(sdkTypes.ZeroDec()) { + if auxiliaryResponse := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, message.FromID, order.GetMakerOwnableID(), transferMakerOwnableSplit.Abs())); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + } else if transferMakerOwnableSplit.GT(sdkTypes.ZeroDec()) { + if auxiliaryResponse := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(message.FromID, module.ModuleIdentityID, order.GetMakerOwnableID(), transferMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + } + + mutableMetaProperties := message.MutableMetaProperties. + Add(baseProperties.NewMetaProperty(constants.MakerOwnableSplitProperty.GetKey(), baseData.NewDecData(message.MakerOwnableSplit))). + Add(baseProperties.NewMetaProperty(constants.ExpiryHeightProperty.GetKey(), baseData.NewHeightData(baseTypes.NewHeight(message.ExpiresIn.Get()+context.BlockHeight())))) + + updatedMutables := order.GetMutables().Mutate(append(mutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...) + + if auxiliaryResponse := transactionKeeper.conformAuxiliary.GetKeeper().Help(context, conform.NewAuxiliaryRequest(order.GetClassificationID(), order.GetImmutables(), updatedMutables)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + orders.Remove(mappable.NewMappable(order)) + orders.Add(mappable.NewMappable(base.NewOrder(order.GetClassificationID(), order.GetImmutables(), updatedMutables))) + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, externalKeeper := range auxiliaries { + switch value := externalKeeper.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case conform.Auxiliary.GetName(): + transactionKeeper.conformAuxiliary = value + case supplement.Auxiliary.GetName(): + transactionKeeper.supplementAuxiliary = value + case transfer.Auxiliary.GetName(): + transactionKeeper.transferAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/orders/internal/transactions/modify/keeper_test.go b/modules/orders/internal/transactions/modify/keeper_test.go index 652e56113..9a2098342 100644 --- a/modules/orders/internal/transactions/modify/keeper_test.go +++ b/modules/orders/internal/transactions/modify/keeper_test.go @@ -1,56 +1,65 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package modify import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/test" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/conform" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/mint" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/transfer" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +var ( + conformAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary ) type TestKeepers struct { - OrdersKeeper helpers.TransactionKeeper + ModifyKeeper helpers.TransactionKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { - +func CreateTestInput(t *testing.T) (types.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { var Codec = codec.New() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + storeKey := types.NewKVStoreKey("test") + paramsStoreKey := types.NewKVStoreKey("testParams") + paramsTransientStoreKeys := types.NewTransientStoreKey("testParamsTransient") Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) paramsKeeper := params.NewKeeper( Codec, @@ -61,110 +70,156 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) - - context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + commitMultiStore.MountStoreWithDB(storeKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, types.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + supplementAuxiliary = supplement.AuxiliaryMock.Initialize(Mapper, Parameters) + transferAuxiliary = transfer.AuxiliaryMock.Initialize(Mapper, Parameters) + conformAuxiliary = conform.AuxiliaryMock.Initialize(Mapper, Parameters) + + context := types.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) - scrubAuxiliary := scrub.AuxiliaryMock.Initialize(Mapper, Parameters) - conformAuxiliary := conform.AuxiliaryMock.Initialize(Mapper, Parameters) - transferAuxiliary := transfer.AuxiliaryMock.Initialize(Mapper, Parameters) - verifyAuxiliary := verify.AuxiliaryMock.Initialize(Mapper, Parameters) - mintAuxiliary := mint.AuxiliaryMock.Initialize(Mapper, Parameters) - supplementAuxiliary := supplement.AuxiliaryMock.Initialize(Mapper, Parameters) keepers := TestKeepers{ - OrdersKeeper: keeperPrototype().Initialize(Mapper, Parameters, - []interface{}{scrubAuxiliary, verifyAuxiliary, - conformAuxiliary, transferAuxiliary, mintAuxiliary, supplementAuxiliary}).(helpers.TransactionKeeper), + ModifyKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), } - return context, keepers + return context, keepers, Mapper, Parameters } -func Test_transactionKeeper_Transact(t *testing.T) { +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - context, keepers := CreateTestInput(t) - immutableProperties, Error := base.ReadProperties("defaultImmutable1:S|defaultImmutable1") - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties("defaultMutable1:S|defaultMutable1") - require.Equal(t, nil, Error) - mutablePropertiesUpdated, Error := base.ReadMetaProperties("defaultMutable1:S|defaultMutable2") - require.Equal(t, nil, Error) - verifyMockErrorAddress := sdkTypes.AccAddress("verifyError") - defaultAddr := sdkTypes.AccAddress("addr") - defaultIdentityID := base.NewID("fromID") - classificationID := base.NewID("classificationID") - makerOwnableID := base.NewID("makerOwnableID") - rateID := base.NewID(sdkTypes.OneDec().String()) - updatedRate := sdkTypes.MustNewDecFromStr("0.002") - creationID := base.NewID("100") - //makerID := base.NewID("makerID") - takerOwnableID := base.NewID("takerOwnableID") - makerOwnableSplit := sdkTypes.SmallestDec().MulInt64(2) - orderID := key.NewOrderID(classificationID, makerOwnableID, takerOwnableID, rateID, creationID, defaultIdentityID, immutableProperties) - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(orderID, immutableProperties, mutableProperties)) - - t.Run("PositiveCase Modifying Order - Changing TakerOwnableSplit, mutableProperty and subtracting makerOwnableSplit", func(t *testing.T) { - want := newTransactionResponse(nil) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, orderID, - updatedRate, makerOwnableSplit.Sub(sdkTypes.SmallestDec()), base.NewHeight(100), - base.NewMetaProperties(), mutablePropertiesUpdated.RemoveData())); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(orderID, immutableProperties, mutableProperties)) - t.Run("PositiveCase Modifying Order - Changing TakerOwnableSplit, mutableProperty and adding makerOwnableSplit", func(t *testing.T) { - want := newTransactionResponse(nil) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, orderID, - updatedRate, makerOwnableSplit.Add(sdkTypes.SmallestDec()), base.NewHeight(100), - base.NewMetaProperties(), mutablePropertiesUpdated.RemoveData())); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase Modifying Order - Order not found", func(t *testing.T) { - want := newTransactionResponse(errors.EntityNotFound) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, base.NewID("orderID"), - updatedRate, makerOwnableSplit, base.NewHeight(100), - base.NewMetaProperties(), mutablePropertiesUpdated.RemoveData())); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - Identity mock error", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(verifyMockErrorAddress, defaultIdentityID, orderID, - updatedRate, makerOwnableSplit, base.NewHeight(100), base.NewMetaProperties(), - mutablePropertiesUpdated.RemoveData())); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - orderID = key.NewOrderID(classificationID, base.NewID("transferError"), takerOwnableID, rateID, creationID, defaultIdentityID, immutableProperties) - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(orderID, immutableProperties, mutableProperties)) - t.Run("NegativeCase Modifying Order - transferError", func(t *testing.T) { - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, orderID, - updatedRate, makerOwnableSplit.Sub(sdkTypes.SmallestDec()), base.NewHeight(100), - base.NewMetaProperties(), mutablePropertiesUpdated.RemoveData())); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase Modifying Order - Changing TakerOwnableSplit, mutableProperty and adding makerOwnableSplit", func(t *testing.T) { - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, orderID, - updatedRate, makerOwnableSplit.Add(sdkTypes.SmallestDec()), base.NewHeight(100), - base.NewMetaProperties(), mutablePropertiesUpdated.RemoveData())); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := CreateTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + conformAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve with nil", fields{}, args{}, transactionKeeper{}}, + {"+ve", fields{Mapper, Parameters, conformAuxiliary, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, conformAuxiliary, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + conformAuxiliary: tt.fields.conformAuxiliary, + supplementAuxiliary: tt.fields.supplementAuxiliary, + transferAuxiliary: tt.fields.transferAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters := CreateTestInput(t) + mutableMetaProperties := baseLists.NewPropertyList( + baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())), + baseProperties.NewMetaProperty(baseIDs.NewStringID("exchangeRate"), baseData.NewDecData(types.NewDec(10))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerOwnableID"), baseData.NewIDData(baseIDs.NewOwnableID(baseIDs.NewStringID("makerID")))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("creationHeight"), baseData.NewHeightData(baseTypes.NewHeight(1))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("takerOwnableID"), baseData.NewIDData(baseIDs.NewOwnableID(baseIDs.NewStringID("takerID")))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(baseIDs.PrototypeIdentityID())), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(baseIDs.PrototypeIdentityID())), + ) + mutableProperties := baseLists.NewPropertyList( + baseProperties.NewMesaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())), + ) + immutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + // immutableProperties := baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + immutablesMeta := baseQualified.NewImmutables(immutableMetaProperties) + mutablesMeta := baseQualified.NewMutables(mutableMetaProperties) + testClassificationID := baseIDs.NewClassificationID(immutablesMeta, mutablesMeta) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutablesMeta) + // testFromID2 := baseIDs.PrototypeIdentityID() + mutableMetaProperties.Mutate( + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(testFromID)), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(testFromID))) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + testIdentity := baseDocuments.NewIdentity(testClassificationID, immutablesMeta, mutablesMeta) + testIdentity.ProvisionAddress([]types.AccAddress{fromAccAddress}...) + testOrder := baseDocuments.NewOrder(testClassificationID, immutablesMeta, mutablesMeta) + // testOrderID := mappable.NewMappable(testOrder).GetKey() + // testMakerOwnableID := baseIDs.NewOwnableID(baseIDs.NewStringID("makerID")) + // testTakerOwnableID := baseIDs.NewOwnableID(baseIDs.NewStringID("takerID")) + testRate := types.NewDec(10) + testHeight := baseTypes.NewHeight(1) + testOrderID := baseIDs.NewOrderID(testClassificationID, immutablesMeta) + // testOrderID2 := baseIDs.NewOrderID(testClassificationID, testTakerOwnableID, testTakerOwnableID, testRate, testHeight, testFromID, immutablesMeta) + keepers.ModifyKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testOrder)) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + conformAuxiliary helpers.Auxiliary + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + context types.Context + msg types.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, Parameters, conformAuxiliary, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}, args{context, newMessage(fromAccAddress, testFromID, testOrderID, testRate, testRate, testHeight, mutableMetaProperties, mutableProperties)}, newTransactionResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + conformAuxiliary: tt.fields.conformAuxiliary, + supplementAuxiliary: tt.fields.supplementAuxiliary, + transferAuxiliary: tt.fields.transferAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/modify/message.go b/modules/orders/internal/transactions/modify/message.go index fe9be4d30..d10f427a3 100644 --- a/modules/orders/internal/transactions/modify/message.go +++ b/modules/orders/internal/transactions/modify/message.go @@ -1,82 +1,92 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package modify import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/types" + baseTypes "github.com/AssetMantle/modules/schema/types/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ids.OrderID `json:"orderID" valid:"required~required field orderID missing"` + MakerOwnableSplit sdkTypes.Dec `json:"makerOwnableSplit" valid:"required~required field makerOwnableSplit missing"` + TakerOwnableSplit sdkTypes.Dec `json:"takerOwnableSplit" valid:"required~required field takerOwnableSplit missing"` + ExpiresIn types.Height `json:"expiresIn" valid:"required~required field expiresIn missing"` + MutableMetaProperties lists.PropertyList `json:"mutableMetaProperties" valid:"required~required field mutableMetaProperties missing"` + MutableProperties lists.PropertyList `json:"mutableProperties" valid:"required~required field mutableProperties missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } if message.TakerOwnableSplit.LTE(sdkTypes.ZeroDec()) || message.MakerOwnableSplit.LTE(sdkTypes.ZeroDec()) { - return errors.Wrap(xprtErrors.IncorrectMessage, "") + return sdkErrors.Wrap(errorConstants.IncorrectMessage, "") } - if message.ExpiresIn.Compare(base.NewHeight(0)) <= 0 { - return errors.Wrap(xprtErrors.IncorrectMessage, "") + if message.ExpiresIn.Compare(baseTypes.NewHeight(0)) <= 0 { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, "") } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + if len(message.MutableMetaProperties.GetList()) == 0 { + message.MutableMetaProperties = base.NewPropertyList(nil) + } + if len(message.MutableProperties.GetList()) == 0 { + message.MutableProperties = base.NewPropertyList(nil) + } + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, orderID types.ID, takerOwnableSplit sdkTypes.Dec, makerOwnableSplit sdkTypes.Dec, expiresIn types.Height, mutableMetaProperties types.MetaProperties, mutableProperties types.Properties) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - OrderID: *base.NewID(orderID.String()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, orderID ids.OrderID, takerOwnableSplit sdkTypes.Dec, makerOwnableSplit sdkTypes.Dec, expiresIn types.Height, mutableMetaProperties lists.PropertyList, mutableProperties lists.PropertyList) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + OrderID: orderID, TakerOwnableSplit: takerOwnableSplit, MakerOwnableSplit: makerOwnableSplit, - ExpiresIn: *base.NewHeight(expiresIn.Get()), - MutableMetaProperties: *base.NewMetaProperties(mutableMetaProperties.GetList()...), - MutableProperties: *base.NewProperties(mutableProperties.GetList()...), + ExpiresIn: expiresIn, + MutableMetaProperties: mutableMetaProperties, + MutableProperties: mutableProperties, } } diff --git a/modules/orders/internal/transactions/modify/message.pb.go b/modules/orders/internal/transactions/modify/message.pb.go deleted file mode 100644 index 1eb0fcad5..000000000 --- a/modules/orders/internal/transactions/modify/message.pb.go +++ /dev/null @@ -1,876 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/transactions/modify/message.proto - -package modify - -import ( - context "context" - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - OrderID base.ID `protobuf:"bytes,3,opt,name=order_i_d,json=orderID,proto3" json:"order_i_d" valid:"required~required field OrderID missing"` - MakerOwnableSplit github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,4,opt,name=maker_ownable_split,json=makerOwnableSplit,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"maker_ownable_split" valid:"required~required field MakerOwnableSplit missing"` - TakerOwnableSplit github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=taker_ownable_split,json=takerOwnableSplit,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"taker_ownable_split" valid:"required~required field TakerOwnableSplit missing"` - ExpiresIn base.Height `protobuf:"bytes,6,opt,name=expires_in,json=expiresIn,proto3" json:"expires_in" valid:"required~required field ExpiresIn missing"` - MutableMetaProperties base.MetaProperties `protobuf:"bytes,7,opt,name=mutable_meta_properties,json=mutableMetaProperties,proto3" json:"mutable_meta_properties" valid:"required~required field MutableMetaProperties missing"` - MutableProperties base.Properties `protobuf:"bytes,8,opt,name=mutable_properties,json=mutableProperties,proto3" json:"mutable_properties" valid:"required~required field MutableProperties missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_81cb781fe82216d8, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_81cb781fe82216d8, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.orders.internal.transactions.modify.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.orders.internal.transactions.modify.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/orders/internal/transactions/modify/message.proto", fileDescriptor_81cb781fe82216d8) -} - -var fileDescriptor_81cb781fe82216d8 = []byte{ - // 669 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x95, 0xb1, 0x6f, 0xd3, 0x4c, - 0x18, 0xc6, 0x7d, 0x5f, 0xfb, 0xa5, 0xcd, 0x7d, 0x53, 0xdd, 0xaf, 0xfa, 0xa2, 0x0e, 0x71, 0x14, - 0xe9, 0x43, 0x05, 0xd1, 0xb3, 0x5a, 0xa4, 0xa2, 0x16, 0x31, 0x34, 0x4a, 0x11, 0x11, 0x8a, 0x5a, - 0xb5, 0x9d, 0x58, 0x2c, 0xc7, 0x7e, 0xe3, 0x9c, 0x9a, 0xf3, 0x99, 0xbb, 0x0b, 0xa5, 0x48, 0xb0, - 0xb0, 0x30, 0xc2, 0xcc, 0x40, 0xc5, 0xc8, 0x84, 0xc4, 0x3f, 0xd1, 0xb1, 0x23, 0x62, 0x88, 0x50, - 0xbb, 0x30, 0xf7, 0x2f, 0x40, 0x3e, 0x3b, 0x8a, 0x9b, 0x46, 0x38, 0x55, 0xc5, 0x64, 0xe7, 0xee, - 0xde, 0xe7, 0xf9, 0xe5, 0x9e, 0xbc, 0x6f, 0x70, 0x23, 0x02, 0x21, 0xa9, 0x54, 0x10, 0x7a, 0xe0, - 0x48, 0xff, 0xc0, 0x66, 0xdc, 0xef, 0x75, 0x41, 0xda, 0x5c, 0xf8, 0x20, 0xa4, 0x4d, 0x43, 0x05, - 0x22, 0x74, 0xbb, 0xb6, 0x12, 0x6e, 0x28, 0x5d, 0x4f, 0x51, 0x1e, 0xca, 0xf8, 0x10, 0x6d, 0x1f, - 0xd9, 0x0c, 0xa4, 0x74, 0x03, 0x20, 0x91, 0xe0, 0x8a, 0x9b, 0x0f, 0x46, 0xa4, 0x48, 0x2a, 0x45, - 0x12, 0x29, 0x32, 0x90, 0x22, 0x59, 0x29, 0x92, 0x48, 0x2d, 0xfe, 0x1b, 0xf0, 0x80, 0x6b, 0x1d, - 0x3b, 0x7e, 0x4b, 0x24, 0x17, 0xef, 0x8c, 0xd2, 0x49, 0xaf, 0x03, 0xcc, 0xb5, 0xd5, 0x51, 0x04, - 0xd2, 0x6e, 0xb9, 0x12, 0x6c, 0xea, 0xa7, 0x67, 0x57, 0xf3, 0xcf, 0x46, 0x82, 0x47, 0x20, 0x14, - 0x05, 0x99, 0xd6, 0xac, 0xe5, 0xd7, 0x30, 0x50, 0xee, 0xce, 0x68, 0x1d, 0xc9, 0xaf, 0xeb, 0x00, - 0x0d, 0x3a, 0x2a, 0x39, 0x5f, 0xfd, 0x5a, 0xc4, 0x33, 0xcd, 0xe4, 0xb2, 0xcc, 0xf7, 0x08, 0x4f, - 0xb7, 0x05, 0x67, 0x25, 0x54, 0x41, 0x4b, 0xc5, 0xda, 0xab, 0x93, 0xbe, 0x65, 0x7c, 0xef, 0x5b, - 0x5b, 0x01, 0x55, 0x9d, 0x5e, 0x8b, 0x78, 0x9c, 0xd9, 0x19, 0xf5, 0xed, 0x10, 0xb2, 0x1f, 0xf7, - 0xea, 0x4f, 0xae, 0x7a, 0x91, 0x4d, 0xcf, 0xdb, 0xf4, 0x7d, 0x01, 0x52, 0x5e, 0xf4, 0xad, 0xbb, - 0xcf, 0xdd, 0x2e, 0xf5, 0x37, 0xaa, 0x02, 0x9e, 0xf5, 0xa8, 0x00, 0xff, 0xf5, 0xe0, 0xa5, 0xd2, - 0xa6, 0xd0, 0xf5, 0x2b, 0x8f, 0x04, 0x67, 0x15, 0x46, 0xa5, 0xa4, 0x61, 0x50, 0xdd, 0xd5, 0x28, - 0xe6, 0x21, 0x9e, 0x8d, 0x9f, 0x0e, 0x75, 0xfc, 0xd2, 0x5f, 0x15, 0xb4, 0xf4, 0xcf, 0xea, 0xff, - 0xa3, 0x5f, 0x91, 0x24, 0xb6, 0x44, 0xdb, 0x12, 0x6d, 0xdb, 0xa8, 0xd7, 0xd6, 0x62, 0xfa, 0x8b, - 0xbe, 0x45, 0x26, 0x30, 0x6d, 0xd4, 0x87, 0xb6, 0x85, 0xb6, 0x5e, 0x30, 0x5f, 0xe2, 0xa2, 0xfe, - 0x75, 0x68, 0xe7, 0xa9, 0xeb, 0x38, 0xdf, 0x4f, 0x9d, 0xed, 0x1c, 0xe7, 0xed, 0x58, 0x3e, 0x6b, - 0x3d, 0xc3, 0x93, 0x15, 0xf3, 0x03, 0xc2, 0xf3, 0xcc, 0x3d, 0x00, 0xe1, 0xf0, 0xc3, 0xd0, 0x6d, - 0x75, 0xc1, 0x91, 0x51, 0x97, 0xaa, 0xd2, 0xb4, 0xce, 0xe5, 0x20, 0xcd, 0xe5, 0x56, 0x26, 0x17, - 0x8f, 0x4b, 0xc6, 0x65, 0xfa, 0x58, 0x8e, 0x73, 0x4f, 0x98, 0xea, 0xe0, 0x5d, 0xf4, 0xad, 0xf5, - 0x1c, 0x92, 0x66, 0xec, 0xb5, 0x9d, 0x58, 0xed, 0xc5, 0x4e, 0x43, 0xa6, 0x39, 0x36, 0xba, 0xa7, - 0xe9, 0xd4, 0x18, 0xba, 0xbf, 0xff, 0x10, 0xdd, 0xfe, 0x6f, 0xe8, 0xd4, 0x15, 0xba, 0x37, 0x08, - 0x63, 0x78, 0x11, 0x51, 0x01, 0xd2, 0xa1, 0x61, 0xa9, 0xa0, 0x93, 0xbb, 0x3d, 0x41, 0x72, 0x8f, - 0x75, 0x5b, 0xd4, 0xd6, 0xd3, 0xf4, 0x56, 0x72, 0xa8, 0xb6, 0x12, 0x8f, 0x46, 0x38, 0xa4, 0x29, - 0xc2, 0x60, 0xcd, 0xfc, 0x82, 0xf0, 0x7f, 0xac, 0xa7, 0xf4, 0xed, 0xc4, 0x7d, 0xea, 0x0c, 0x1b, - 0xbc, 0x34, 0xa3, 0x91, 0x56, 0x26, 0x40, 0x6a, 0x5e, 0xea, 0xf0, 0xda, 0x56, 0x8a, 0xf6, 0x30, - 0x2f, 0xce, 0xc4, 0xf8, 0x72, 0xf5, 0x10, 0x73, 0x81, 0x8d, 0xdb, 0x37, 0x3f, 0x22, 0x6c, 0x0e, - 0x90, 0x33, 0xb4, 0xb3, 0x9a, 0x76, 0x79, 0x02, 0xda, 0x0c, 0xe9, 0x66, 0x4a, 0xba, 0x3e, 0x19, - 0xe9, 0x38, 0xca, 0x39, 0x36, 0xba, 0xb7, 0x31, 0xfb, 0xf6, 0xd8, 0x32, 0x7e, 0x1e, 0x5b, 0x46, - 0x75, 0x01, 0xcf, 0xef, 0x0f, 0x47, 0xf5, 0x2e, 0xc8, 0x88, 0x87, 0x12, 0x56, 0x3f, 0x23, 0x3c, - 0xd5, 0x94, 0x81, 0xf9, 0x09, 0xe1, 0x42, 0x53, 0x4f, 0x6f, 0xb3, 0x4e, 0x6e, 0x30, 0xfb, 0x49, - 0x3a, 0x19, 0x17, 0x77, 0x6e, 0xa4, 0x32, 0x06, 0xb5, 0x6a, 0xd4, 0xc2, 0x93, 0xb3, 0x32, 0x3a, - 0x3d, 0x2b, 0xa3, 0x1f, 0x67, 0x65, 0xf4, 0xee, 0xbc, 0x6c, 0x9c, 0x9e, 0x97, 0x8d, 0x6f, 0xe7, - 0x65, 0xe3, 0xe9, 0xfe, 0xc4, 0x03, 0xf7, 0x1a, 0x7f, 0x89, 0xad, 0x82, 0x1e, 0xf8, 0xf7, 0x7e, - 0x05, 0x00, 0x00, 0xff, 0xff, 0xf0, 0xa7, 0x5d, 0x81, 0x58, 0x07, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Modify(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Modify(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.orders.internal.transactions.modify.Msg/Modify", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Modify(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Modify(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Modify not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Modify_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Modify(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.orders.internal.transactions.modify.Msg/Modify", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Modify(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.orders.internal.transactions.modify.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Modify", - Handler: _Msg_Modify_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/orders/internal/transactions/modify/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MutableProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - { - size, err := m.MutableMetaProperties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - { - size, err := m.ExpiresIn.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - { - size := m.TakerOwnableSplit.Size() - i -= size - if _, err := m.TakerOwnableSplit.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size := m.MakerOwnableSplit.Size() - i -= size - if _, err := m.MakerOwnableSplit.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.OrderID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.OrderID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MakerOwnableSplit.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.TakerOwnableSplit.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ExpiresIn.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableMetaProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.MutableProperties.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OrderID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OrderID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MakerOwnableSplit", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MakerOwnableSplit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TakerOwnableSplit", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TakerOwnableSplit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ExpiresIn", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ExpiresIn.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableMetaProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableMetaProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MutableProperties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MutableProperties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/orders/internal/transactions/modify/message_test.go b/modules/orders/internal/transactions/modify/message_test.go index d82343544..42787a50a 100644 --- a/modules/orders/internal/transactions/modify/message_test.go +++ b/modules/orders/internal/transactions/modify/message_test.go @@ -1,57 +1,312 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package modify import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/codec" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/types" + "github.com/AssetMantle/modules/schema/types/base" + "github.com/AssetMantle/modules/utilities/transaction" +) + +var ( + expiresInHeight = base.NewHeight(60) + testMessage = newMessage(fromAccAddress, testFromID, testOrderID, takerOwnableSplit, makerOwnableSplit, expiresInHeight, mutableMetaProperties, mutableProperties) ) -func Test_Make_Message(t *testing.T) { - - fromID := base.NewID("fromID") - classificationID := base.NewID("classificationID") - makerOwnableID := base.NewID("makerOwnableID") - takerOwnableID := base.NewID("takerOwnableID") - expiresIn := base.NewHeight(12) - makerOwnableSplit := sdkTypes.NewDec(2) - makerID := base.NewID("makerID") - rateID := base.NewID("0.11") - creationId := base.NewID("100") - immutableProperties, Error := base.ReadProperties("defaultImmutable1:S|defaultImmutable1") - require.Equal(t, nil, Error) - mutableMetaProperties, Error := base.ReadMetaProperties("defaultMutableMeta1:S|defaultMutableMeta1") - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties("defaultMutable1:S|defaultMutable1") - require.Equal(t, nil, Error) - orderID := base.NewID(key.NewOrderID(classificationID, makerOwnableID, takerOwnableID, rateID, creationId, makerID, immutableProperties).String()) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - testMessage := newMessage(fromAccAddress, fromID, orderID, sdkTypes.OneDec(), makerOwnableSplit, expiresIn, mutableMetaProperties, mutableProperties) - require.Equal(t, Message{From: fromAccAddress, FromID: fromID, OrderID: orderID, TakerOwnableSplit: sdkTypes.OneDec(), MakerOwnableSplit: makerOwnableSplit, ExpiresIn: expiresIn, MutableMetaProperties: mutableMetaProperties, MutableProperties: mutableProperties}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) - require.Error(t, errors.Wrap(xprtErrors.IncorrectMessage, ""), newMessage(fromAccAddress, fromID, orderID, sdkTypes.OneDec().Neg(), makerOwnableSplit, expiresIn, mutableMetaProperties, mutableProperties).ValidateBasic()) - require.Error(t, errors.Wrap(xprtErrors.IncorrectMessage, ""), newMessage(fromAccAddress, fromID, orderID, sdkTypes.OneDec(), makerOwnableSplit, base.NewHeight(-12), mutableMetaProperties, mutableProperties).ValidateBasic()) +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg sdkTypes.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{testMessage}, message{fromAccAddress, testFromID, testOrderID, takerOwnableSplit, makerOwnableSplit, expiresInHeight, mutableMetaProperties, mutableProperties}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + OrderID ids.OrderID + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ExpiresIn types.Height + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, testFromID, testOrderID, takerOwnableSplit, makerOwnableSplit, expiresInHeight, mutableMetaProperties, mutableProperties}, sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(testMessage))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ExpiresIn: tt.fields.ExpiresIn, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + OrderID ids.OrderID + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ExpiresIn types.Height + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want []sdkTypes.AccAddress + }{ + {"+ve", fields{fromAccAddress, testFromID, testOrderID, takerOwnableSplit, makerOwnableSplit, expiresInHeight, mutableMetaProperties, mutableProperties}, []sdkTypes.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ExpiresIn: tt.fields.ExpiresIn, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + OrderID ids.OrderID + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ExpiresIn types.Height + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, testFromID, testOrderID, takerOwnableSplit, makerOwnableSplit, expiresInHeight, mutableMetaProperties, mutableProperties}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ExpiresIn: tt.fields.ExpiresIn, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + OrderID ids.OrderID + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ExpiresIn types.Height + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testOrderID, takerOwnableSplit, makerOwnableSplit, expiresInHeight, mutableMetaProperties, mutableProperties}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ExpiresIn: tt.fields.ExpiresIn, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + OrderID ids.OrderID + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ExpiresIn types.Height + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testOrderID, takerOwnableSplit, makerOwnableSplit, expiresInHeight, mutableMetaProperties, mutableProperties}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ExpiresIn: tt.fields.ExpiresIn, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From sdkTypes.AccAddress + FromID ids.IdentityID + OrderID ids.OrderID + MakerOwnableSplit sdkTypes.Dec + TakerOwnableSplit sdkTypes.Dec + ExpiresIn types.Height + MutableMetaProperties lists.PropertyList + MutableProperties lists.PropertyList + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"-ve for nil", fields{}, true}, + {"+ve", fields{fromAccAddress, testFromID, testOrderID, takerOwnableSplit, makerOwnableSplit, expiresInHeight, mutableMetaProperties, mutableProperties}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + ExpiresIn: tt.fields.ExpiresIn, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from sdkTypes.AccAddress + fromID ids.IdentityID + orderID ids.OrderID + takerOwnableSplit sdkTypes.Dec + makerOwnableSplit sdkTypes.Dec + expiresIn types.Height + mutableMetaProperties lists.PropertyList + mutableProperties lists.PropertyList + } + tests := []struct { + name string + args args + want sdkTypes.Msg + }{ + {"+ve", args{fromAccAddress, testFromID, testOrderID, takerOwnableSplit, makerOwnableSplit, expiresInHeight, mutableMetaProperties, mutableProperties}, message{fromAccAddress, testFromID, testOrderID, takerOwnableSplit, makerOwnableSplit, expiresInHeight, mutableMetaProperties, mutableProperties}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.orderID, tt.args.takerOwnableSplit, tt.args.makerOwnableSplit, tt.args.expiresIn, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/modify/msg_server.go b/modules/orders/internal/transactions/modify/msg_server.go deleted file mode 100644 index a8c6bf90a..000000000 --- a/modules/orders/internal/transactions/modify/msg_server.go +++ /dev/null @@ -1,99 +0,0 @@ -package modify - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/classifications/auxiliaries/conform" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/transfer" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -func (msgServer msgServer) Modify(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - orders := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(&message.OrderID)) - - order := orders.Get(key.FromID(&message.OrderID)) - if order == nil { - return nil, errors.EntityNotFound - } - - metaProperties, Error := supplement.GetMetaPropertiesFromResponse(msgServer.transactionKeeper.supplementAuxiliary.GetKeeper().Help(ctx, supplement.NewAuxiliaryRequest(order.(mappables.Order).GetMakerOwnableSplit()))) - if Error != nil { - return nil, Error - } - - transferMakerOwnableSplit := sdkTypes.ZeroDec() - - if makerOwnableSplitProperty := metaProperties.Get(base.NewID(properties.MakerOwnableSplit)); makerOwnableSplitProperty != nil { - oldMakerOwnableSplit, Error := makerOwnableSplitProperty.GetMetaFact().GetData().AsDec() - if Error != nil { - return nil, Error - } - - transferMakerOwnableSplit = message.MakerOwnableSplit.Sub(oldMakerOwnableSplit) - } else { - return nil, errors.MetaDataError - } - - if transferMakerOwnableSplit.LT(sdkTypes.ZeroDec()) { - if auxiliaryResponse := msgServer.transactionKeeper.transferAuxiliary.GetKeeper().Help(ctx, transfer.NewAuxiliaryRequest(base.NewID(module.Name), &message.FromID, order.(mappables.Order).GetMakerOwnableID(), transferMakerOwnableSplit.Abs())); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - } else if transferMakerOwnableSplit.GT(sdkTypes.ZeroDec()) { - if auxiliaryResponse := msgServer.transactionKeeper.transferAuxiliary.GetKeeper().Help(ctx, transfer.NewAuxiliaryRequest(&message.FromID, base.NewID(module.Name), order.(mappables.Order).GetMakerOwnableID(), transferMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - } - - mutableMetaProperties := message.MutableMetaProperties.Add(base.NewMetaProperty(base.NewID(properties.MakerOwnableSplit), base.NewMetaFact(base.NewDecData(message.MakerOwnableSplit)))) - mutableMetaProperties = mutableMetaProperties.Add(base.NewMetaProperty(base.NewID(properties.Expiry), base.NewMetaFact(base.NewHeightData(base.NewHeight(message.ExpiresIn.Get()+ctx.BlockHeight()))))) - - scrubbedMutableMetaProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(mutableMetaProperties.GetList()...))) - if Error != nil { - return nil, Error - } - - updatedMutables := order.(mappables.Order).GetMutableProperties().Mutate(append(scrubbedMutableMetaProperties.GetList(), message.MutableProperties.GetList()...)...) - - if auxiliaryResponse := msgServer.transactionKeeper.conformAuxiliary.GetKeeper().Help(ctx, conform.NewAuxiliaryRequest(order.(mappables.Order).GetClassificationID(), order.(mappables.Order).GetImmutableProperties(), updatedMutables)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - orders.Remove(order) - orders.Add(mappable.NewOrder( - key.NewOrderID( - order.(mappables.Order).GetClassificationID(), - order.(mappables.Order).GetMakerOwnableID(), - order.(mappables.Order).GetTakerOwnableID(), - base.NewID(message.TakerOwnableSplit.QuoTruncate(sdkTypes.SmallestDec()).QuoTruncate(message.MakerOwnableSplit).String()), - base.NewID(order.(mappables.Order).GetCreation().GetMetaFact().GetData().String()), - order.(mappables.Order).GetMakerID(), order.(mappables.Order).GetImmutableProperties(), - ), - order.(mappables.Order).GetImmutableProperties(), - updatedMutables), - ) - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} - -var _ MsgServer = msgServer{} diff --git a/modules/orders/internal/transactions/modify/request.go b/modules/orders/internal/transactions/modify/request.go index 06cd7f16b..9f47d3d87 100644 --- a/modules/orders/internal/transactions/modify/request.go +++ b/modules/orders/internal/transactions/modify/request.go @@ -1,22 +1,23 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package modify import ( "encoding/json" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + baseTypes "github.com/AssetMantle/modules/schema/types/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -32,35 +33,35 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary modify order transaction -// @Descrption modify order transaction +// Validate godoc +// @Summary Modify order transaction +// @Description Modify order transaction // @Accept text/plain // @Produce json // @Tags Orders -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body transactionRequest true "Request body to modify order transaction" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /orders/modify [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.OrderID), - cliCommand.ReadString(flags.TakerOwnableSplit), - cliCommand.ReadString(flags.MakerOwnableSplit), - cliCommand.ReadInt64(flags.ExpiresIn), - cliCommand.ReadString(flags.MutableMetaProperties), - cliCommand.ReadString(flags.MutableProperties), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.OrderID), + cliCommand.ReadString(constants.TakerOwnableSplit), + cliCommand.ReadString(constants.MakerOwnableSplit), + cliCommand.ReadInt64(constants.ExpiresIn), + cliCommand.ReadString(constants.MutableMetaProperties), + cliCommand.ReadString(constants.MutableProperties), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -70,44 +71,55 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + makerOwnableSplit, err := sdkTypes.NewDecFromStr(transactionRequest.MakerOwnableSplit) + if err != nil { + return nil, err + } + + takerOwnableSplit, err := sdkTypes.NewDecFromStr(transactionRequest.TakerOwnableSplit) + if err != nil { + return nil, err } - makerOwnableSplit, Error := sdkTypes.NewDecFromStr(transactionRequest.MakerOwnableSplit) - if Error != nil { - return nil, Error + mutableMetaProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableMetaProperties) + if err != nil { + return nil, err } - takerOwnableSplit, Error := sdkTypes.NewDecFromStr(transactionRequest.TakerOwnableSplit) - if Error != nil { - return nil, Error + mutableProperties, err := utilities.ReadMetaPropertyList(transactionRequest.MutableProperties) + if err != nil { + return nil, err } + mutableProperties = mutableProperties.ScrubData() - mutableMetaProperties, Error := base.ReadMetaProperties(transactionRequest.MutableMetaProperties) - if Error != nil { - return nil, Error + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err } - mutableProperties, Error := base.ReadProperties(transactionRequest.MutableProperties) - if Error != nil { - return nil, Error + orderID, err := baseIDs.ReadOrderID(transactionRequest.OrderID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.OrderID), + fromID, + orderID, takerOwnableSplit, makerOwnableSplit, - base.NewHeight(transactionRequest.ExpiresIn), + baseTypes.NewHeight(transactionRequest.ExpiresIn), mutableMetaProperties, mutableProperties, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/orders/internal/transactions/modify/request_test.go b/modules/orders/internal/transactions/modify/request_test.go index b3b451fdf..c70e07c4d 100644 --- a/modules/orders/internal/transactions/modify/request_test.go +++ b/modules/orders/internal/transactions/modify/request_test.go @@ -1,96 +1,353 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package modify import ( "encoding/json" + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/spf13/viper" "github.com/stretchr/testify/require" - "testing" -) - -func Test_Define_Request(t *testing.T) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.OrderID, flags.MakerOwnableSplit, flags.ExpiresIn, flags.TakerOwnableSplit, flags.MutableMetaProperties, flags.MutableProperties}) - cliContext := context.NewCLIContext().WithCodec(Codec) - - mutableMetaPropertiesString := "defaultMutableMeta1:S|defaultMutableMeta1" - mutablePropertiesString := "defaultMutable1:S|defaultMutable1" - - mutableMetaProperties, Error := base.ReadMetaProperties(mutableMetaPropertiesString) - require.Equal(t, nil, Error) - mutableProperties, Error := base.ReadProperties(mutablePropertiesString) - require.Equal(t, nil, Error) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "orderID", sdkTypes.OneDec().String(), "1.0", 123, mutableMetaPropertiesString, mutablePropertiesString) - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", OrderID: "orderID", ExpiresIn: 123, MakerOwnableSplit: "1.0", TakerOwnableSplit: sdkTypes.OneDec().String(), MutableMetaProperties: mutableMetaPropertiesString, MutableProperties: mutablePropertiesString}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) - - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", MutableMetaProperties: "", MutableProperties: ""}, requestFromCLI) + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/utilities" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/schema/types/base" +) - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, error3 := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, error3) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +var ( + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = types.AccAddressFromBech32(fromAddress) + immutableMetaPropertiesString = "defaultImmutableMeta1:S|defaultImmutableMeta1" + immutablePropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" + mutableMetaPropertiesString = "defaultMutableMeta1:S|defaultMutableMeta1" + mutablePropertiesString = "defaultMutable1:S|defaultMutable1" + immutableMetaProperties, _ = utilities.ReadMetaPropertyList(immutableMetaPropertiesString) + immutableProperties, _ = utilities.ReadMetaPropertyList(immutablePropertiesString) + mutableMetaProperties, _ = utilities.ReadMetaPropertyList(mutableMetaPropertiesString) + mutableProperties, _ = utilities.ReadMetaPropertyList(mutablePropertiesString) + immutables = baseQualified.NewImmutables(immutableProperties) + mutables = baseQualified.NewMutables(mutableProperties) - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) + testClassificationID = baseIDs.NewClassificationID(immutables, mutables) + testFromID = baseIDs.NewIdentityID(testClassificationID, immutables) + testOrderID = baseIDs.NewOrderID(testClassificationID, immutables) + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + expiresIn = int64(60) + makerOwnableSplit = types.NewDec(60) + takerOwnableSplit = types.NewDec(60) +) - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + orderID string + takerOwnableSplit string + makerOwnableSplit string + expiresIn int64 + mutableMetaProperties string + mutableProperties string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, testFromID.String(), testOrderID.String(), takerOwnableSplit.String(), makerOwnableSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString}, transactionRequest{testBaseRequest, testFromID.String(), testOrderID.String(), takerOwnableSplit.String(), makerOwnableSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.orderID, tt.args.takerOwnableSplit, tt.args.makerOwnableSplit, tt.args.expiresIn, tt.args.mutableMetaProperties, tt.args.mutableProperties); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("orderID"), sdkTypes.OneDec(), sdkTypes.NewDec(1), base.NewHeight(123), mutableMetaProperties, mutableProperties), msg) - require.Nil(t, Error) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "fromAddress", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "orderID", sdkTypes.OneDec().String(), "aa", 123, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.OrderID, constants.TakerOwnableSplit, constants.MakerOwnableSplit, constants.ExpiresIn, constants.MutableMetaProperties, constants.MutableProperties}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.FromID.GetName(), testFromID.String()) + viper.Set(constants.OrderID.GetName(), testOrderID.String()) + viper.Set(constants.TakerOwnableSplit.GetName(), takerOwnableSplit.String()) + viper.Set(constants.MakerOwnableSplit.GetName(), makerOwnableSplit.String()) + viper.Set(constants.ExpiresIn.GetName(), expiresIn) + viper.Set(constants.MutableMetaProperties.GetName(), mutableMetaPropertiesString) + viper.Set(constants.MutableProperties.GetName(), mutablePropertiesString) + type fields struct { + BaseReq rest.BaseReq + FromID string + OrderID string + TakerOwnableSplit string + MakerOwnableSplit string + ExpiresIn int64 + MutableMetaProperties string + MutableProperties string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testOrderID.String(), takerOwnableSplit.String(), makerOwnableSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString}, args{cliCommand, cliContext}, transactionRequest{testBaseRequest, testFromID.String(), testOrderID.String(), takerOwnableSplit.String(), makerOwnableSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + ExpiresIn: tt.fields.ExpiresIn, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, "fromID", "orderID", sdkTypes.OneDec().String(), "aa", 123, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_FromJSON(t *testing.T) { + jsonMessage, err := json.Marshal(newTransactionRequest(testBaseRequest, testFromID.String(), testOrderID.String(), takerOwnableSplit.String(), makerOwnableSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString)) + require.NoError(t, err) + type fields struct { + BaseReq rest.BaseReq + FromID string + OrderID string + TakerOwnableSplit string + MakerOwnableSplit string + ExpiresIn int64 + MutableMetaProperties string + MutableProperties string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testOrderID.String(), takerOwnableSplit.String(), makerOwnableSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString}, args{jsonMessage}, newTransactionRequest(testBaseRequest, testFromID.String(), testOrderID.String(), takerOwnableSplit.String(), makerOwnableSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + ExpiresIn: tt.fields.ExpiresIn, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(testBaseReq, "fromID", "orderID", "aa", "2.0", 123, mutableMetaPropertiesString, mutablePropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + OrderID string + TakerOwnableSplit string + MakerOwnableSplit string + ExpiresIn int64 + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testOrderID.String(), takerOwnableSplit.String(), makerOwnableSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + ExpiresIn: tt.fields.ExpiresIn, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "orderID", sdkTypes.OneDec().String(), sdkTypes.OneDec().String(), 123, "randomString", mutableMetaPropertiesString).MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + OrderID string + TakerOwnableSplit string + MakerOwnableSplit string + ExpiresIn int64 + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testOrderID.String(), takerOwnableSplit.String(), makerOwnableSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString}, newMessage(fromAccAddress, testFromID, testOrderID, takerOwnableSplit, makerOwnableSplit, base.NewHeight(60), mutableMetaProperties, mutableProperties), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + ExpiresIn: tt.fields.ExpiresIn, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error = newTransactionRequest(rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "orderID", sdkTypes.OneDec().String(), sdkTypes.OneDec().String(), 123, mutablePropertiesString, "randomString").MakeMsg() - require.Equal(t, nil, msg) - require.NotNil(t, Error) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + OrderID string + TakerOwnableSplit string + MakerOwnableSplit string + ExpiresIn int64 + MutableMetaProperties string + MutableProperties string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testOrderID.String(), takerOwnableSplit.String(), makerOwnableSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + ExpiresIn: tt.fields.ExpiresIn, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + OrderID string + TakerOwnableSplit string + MakerOwnableSplit string + ExpiresIn int64 + MutableMetaProperties string + MutableProperties string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testOrderID.String(), takerOwnableSplit.String(), makerOwnableSplit.String(), expiresIn, mutableMetaPropertiesString, mutablePropertiesString}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OrderID: tt.fields.OrderID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + MakerOwnableSplit: tt.fields.MakerOwnableSplit, + ExpiresIn: tt.fields.ExpiresIn, + MutableMetaProperties: tt.fields.MutableMetaProperties, + MutableProperties: tt.fields.MutableProperties, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/orders/internal/transactions/modify/response.go b/modules/orders/internal/transactions/modify/response.go new file mode 100644 index 000000000..c45d31c42 --- /dev/null +++ b/modules/orders/internal/transactions/modify/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package modify + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/orders/internal/transactions/modify/response_test.go b/modules/orders/internal/transactions/modify/response_test.go index 63b9a5912..dc9ee387c 100644 --- a/modules/orders/internal/transactions/modify/response_test.go +++ b/modules/orders/internal/transactions/modify/response_test.go @@ -1,25 +1,84 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package modify import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/stretchr/testify/require" + "reflect" "testing" -) -func Test_Make_Response(t *testing.T) { + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) - testTransactionResponse := newTransactionResponse(errors.IncorrectFormat) - testTransactionResponse2 := newTransactionResponse(nil) +func Test_newTransactionResponse(t *testing.T) { + type args struct { + error error + } + tests := []struct { + name string + args args + want helpers.TransactionResponse + }{ + {"+ve", args{nil}, transactionResponse{true, nil}}, + {"-ve", args{constants.IncorrectFormat}, transactionResponse{false, constants.IncorrectFormat}}} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionResponse(tt.args.error); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionResponse() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, transactionResponse{Success: false, Error: errors.IncorrectFormat}, testTransactionResponse) - require.Equal(t, false, testTransactionResponse.IsSuccessful()) - require.Equal(t, true, testTransactionResponse2.IsSuccessful()) +func Test_transactionResponse_GetError(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{Success: true, Error: nil}, false}, + {"-ve", fields{Success: false, Error: constants.IncorrectFormat}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if err := transactionResponse.GetError(); (err != nil) != tt.wantErr { + t.Errorf("GetError() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} - require.Equal(t, errors.IncorrectFormat, testTransactionResponse.GetError()) - require.Equal(t, nil, testTransactionResponse2.GetError()) +func Test_transactionResponse_IsSuccessful(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + want bool + }{ + {"+ve", fields{Success: true, Error: nil}, true}, + {"-ve", fields{Success: false, Error: constants.IncorrectFormat}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if got := transactionResponse.IsSuccessful(); got != tt.want { + t.Errorf("IsSuccessful() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/modify/transaction.go b/modules/orders/internal/transactions/modify/transaction.go new file mode 100644 index 000000000..f3347b80c --- /dev/null +++ b/modules/orders/internal/transactions/modify/transaction.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package modify + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "modify", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + constants.FromID, + constants.OrderID, + constants.MakerOwnableSplit, + constants.TakerOwnableSplit, + constants.ExpiresIn, + constants.ImmutableMetaProperties, + constants.ImmutableProperties, + constants.MutableMetaProperties, + constants.MutableProperties, +) diff --git a/modules/orders/internal/transactions/prototype.go b/modules/orders/internal/transactions/prototype.go new file mode 100644 index 000000000..285bef048 --- /dev/null +++ b/modules/orders/internal/transactions/prototype.go @@ -0,0 +1,27 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transactions + +import ( + "github.com/AssetMantle/modules/modules/orders/internal/transactions/cancel" + "github.com/AssetMantle/modules/modules/orders/internal/transactions/define" + "github.com/AssetMantle/modules/modules/orders/internal/transactions/make" + "github.com/AssetMantle/modules/modules/orders/internal/transactions/take" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Transactions { + return baseHelpers.NewTransactions( + // TODO ***** revisit business logic + // deputize.Transaction, + // immediate.Transaction, + // modify.Transaction, + // revoke.Transaction, + take.Transaction, + cancel.Transaction, + define.Transaction, + make.Transaction, + ) +} diff --git a/modules/orders/internal/transactions/revoke/keeper.go b/modules/orders/internal/transactions/revoke/keeper.go new file mode 100644 index 000000000..534b5fe1b --- /dev/null +++ b/modules/orders/internal/transactions/revoke/keeper.go @@ -0,0 +1,57 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/revoke" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + revokeAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + if auxiliaryResponse := transactionKeeper.revokeAuxiliary.GetKeeper().Help(context, revoke.NewAuxiliaryRequest(message.FromID, message.ToID, message.ClassificationID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + return newTransactionResponse(nil) +} +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case revoke.Auxiliary.GetName(): + transactionKeeper.revokeAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(constants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/orders/internal/transactions/revoke/keeper_test.go b/modules/orders/internal/transactions/revoke/keeper_test.go index 3172fb226..4026ef51f 100644 --- a/modules/orders/internal/transactions/revoke/keeper_test.go +++ b/modules/orders/internal/transactions/revoke/keeper_test.go @@ -1,51 +1,62 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" - sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/test" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/revoke" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/revoke" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + + "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/helpers" +) + +var ( + authenticateAuxiliary helpers.Auxiliary + revokeAuxiliary helpers.Auxiliary ) type TestKeepers struct { - OrdersKeeper helpers.TransactionKeeper + RevokeKeeper helpers.TransactionKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { - - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func CreateTestInput(t *testing.T) (types.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + storeKey := types.NewKVStoreKey("test") + paramsStoreKey := types.NewKVStoreKey("testParams") + paramsTransientStoreKeys := types.NewTransientStoreKey("testParamsTransient") Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) paramsKeeper := params.NewKeeper( Codec, @@ -56,60 +67,117 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + commitMultiStore.MountStoreWithDB(storeKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, types.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + revokeAuxiliary = revoke.AuxiliaryMock.Initialize(Mapper, Parameters) - context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + context := types.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) - revokeAuxiliary := revoke.AuxiliaryMock.Initialize(Mapper, Parameters) - verifyAuxiliary := verify.AuxiliaryMock.Initialize(Mapper, Parameters) keepers := TestKeepers{ - OrdersKeeper: keeperPrototype().Initialize(Mapper, Parameters, - []interface{}{verifyAuxiliary, revokeAuxiliary}).(helpers.TransactionKeeper), + RevokeKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), } - return context, keepers + return context, keepers, Mapper, Parameters } -func Test_transactionKeeper_Transact(t *testing.T) { +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := CreateTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + revokeAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper, Parameters, authenticateAuxiliary, revokeAuxiliary}, args{Mapper, Parameters, []interface{}{authenticateAuxiliary, revokeAuxiliary}}, transactionKeeper{Mapper, Parameters, authenticateAuxiliary, revokeAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + revokeAuxiliary: tt.fields.revokeAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} - context, keepers := CreateTestInput(t) - - _, Error := base.ReadProperties("maintainedProperties:S|maintainedProperties") - require.Equal(t, nil, Error) - _, Error = base.ReadProperties("conformError:S|mockError") - require.Equal(t, nil, Error) - defaultAddr := sdkTypes.AccAddress("addr") - verifyMockErrorAddress := sdkTypes.AccAddress("verifyError") - defaultIdentityID := base.NewID("fromIdentityID") - toID := base.NewID("toID") - toID2 := base.NewID("toID2") - classificationID := base.NewID("ClassificationID") - mockErrorClassification := base.NewID("revokeError") - - t.Run("PositiveCase", func(t *testing.T) { - want := newTransactionResponse(nil) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, toID, classificationID)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - verify identity fail", func(t *testing.T) { - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(verifyMockErrorAddress, defaultIdentityID, toID, classificationID)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - conform mock error", func(t *testing.T) { - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, toID2, mockErrorClassification)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters := CreateTestInput(t) + mutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList()))) + immutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + immutablesMeta := baseQualified.NewImmutables(immutableMetaProperties) + mutablesMeta := baseQualified.NewMutables(mutableMetaProperties) + testIdentity := baseDocuments.NewIdentity(testClassificationID, immutablesMeta, mutablesMeta) + testIdentity.ProvisionAddress([]types.AccAddress{fromAccAddress}...) + testOrder := baseDocuments.NewOrder(testClassificationID, immutablesMeta, mutablesMeta) + keepers.RevokeKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testOrder)) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + revokeAuxiliary helpers.Auxiliary + } + type args struct { + context types.Context + msg types.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, Parameters, authenticateAuxiliary, revokeAuxiliary}, args{context, newMessage(fromAccAddress, testFromID, testFromID, testClassificationID)}, newTransactionResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + revokeAuxiliary: tt.fields.revokeAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/revoke/message.go b/modules/orders/internal/transactions/revoke/message.go index f575c0d61..4242cdfd9 100644 --- a/modules/orders/internal/transactions/revoke/message.go +++ b/modules/orders/internal/transactions/revoke/message.go @@ -1,70 +1,66 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ToID ids.IdentityID `json:"toID" valid:"required~required field toID missing"` + ids.ClassificationID `json:"classificationID" valid:"required~required field classificationID missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, toID types.ID, classificationID types.ID) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - ToID: *base.NewID(toID.String()), - ClassificationID: *base.NewID(classificationID.String()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, toID ids.IdentityID, classificationID ids.ClassificationID) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + ToID: toID, + ClassificationID: classificationID, } } diff --git a/modules/orders/internal/transactions/revoke/message.pb.go b/modules/orders/internal/transactions/revoke/message.pb.go deleted file mode 100644 index 78279fdb5..000000000 --- a/modules/orders/internal/transactions/revoke/message.pb.go +++ /dev/null @@ -1,677 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/transactions/revoke/message.proto - -package revoke - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - ToID base.ID `protobuf:"bytes,3,opt,name=to_i_d,json=toID,proto3" json:"to_i_d" valid:"required~required field ToID missing"` - ClassificationID base.ID `protobuf:"bytes,4,opt,name=classification_i_d,json=classificationID,proto3" json:"classification_i_d" valid:"required~required field ClassificationID missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_7069e63d31f993b9, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_7069e63d31f993b9, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.orders.internal.transactions.revoke.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.orders.internal.transactions.revoke.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/orders/internal/transactions/revoke/message.proto", fileDescriptor_7069e63d31f993b9) -} - -var fileDescriptor_7069e63d31f993b9 = []byte{ - // 474 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0xcf, 0x6b, 0xd4, 0x40, - 0x14, 0xc7, 0x33, 0x76, 0x59, 0x6b, 0xbc, 0x48, 0x54, 0x28, 0x3d, 0x24, 0x21, 0x20, 0x14, 0x91, - 0x19, 0xa8, 0x22, 0x52, 0x2f, 0x76, 0x8d, 0xc2, 0x22, 0x45, 0x59, 0xf7, 0xe4, 0x65, 0xc9, 0xce, - 0xbc, 0x4d, 0x87, 0x26, 0x33, 0xdb, 0x79, 0xb3, 0x15, 0x0f, 0x7a, 0xf6, 0xa8, 0x07, 0xef, 0xc5, - 0xa3, 0xfe, 0x23, 0x3d, 0xf6, 0x28, 0x1e, 0x16, 0xd9, 0xbd, 0x78, 0xee, 0x5f, 0x20, 0x3b, 0xd9, - 0xd2, 0xb8, 0x0a, 0xed, 0xd2, 0x53, 0x5e, 0x7e, 0xf0, 0xf9, 0x7c, 0x93, 0x7c, 0x9f, 0xdf, 0x1e, - 0x82, 0x41, 0x89, 0x16, 0x14, 0x87, 0x1e, 0x8a, 0x3d, 0x56, 0x6a, 0x31, 0x2a, 0x00, 0x99, 0x36, - 0x02, 0x0c, 0x32, 0xa9, 0x2c, 0x18, 0x95, 0x15, 0xcc, 0x9a, 0x4c, 0x61, 0xc6, 0xad, 0xd4, 0x0a, - 0x99, 0x81, 0x03, 0xbd, 0x07, 0xac, 0x04, 0xc4, 0x2c, 0x07, 0x3a, 0x34, 0xda, 0xea, 0xe0, 0xf1, - 0x02, 0x8a, 0xce, 0x51, 0xb4, 0x42, 0xd1, 0x53, 0x14, 0xad, 0xa3, 0x68, 0x85, 0x5a, 0xbf, 0x95, - 0xeb, 0x5c, 0x3b, 0x0e, 0x9b, 0x4d, 0x15, 0x72, 0xfd, 0xee, 0x62, 0x3a, 0xe4, 0xbb, 0x50, 0x66, - 0xcc, 0xbe, 0x1b, 0x02, 0xb2, 0x7e, 0x86, 0xc0, 0xa4, 0xa8, 0x9e, 0x4d, 0xbe, 0x37, 0xfc, 0xab, - 0x3b, 0x55, 0xa0, 0xe0, 0x33, 0xf1, 0x1b, 0x03, 0xa3, 0xcb, 0x35, 0x12, 0x93, 0x8d, 0x6b, 0xad, - 0xf7, 0x47, 0xe3, 0xc8, 0xfb, 0x39, 0x8e, 0x9e, 0xe5, 0xd2, 0xee, 0x8e, 0xfa, 0x94, 0xeb, 0x92, - 0xd5, 0xc8, 0x2f, 0x15, 0xd4, 0x4f, 0x5f, 0xa7, 0x2f, 0xfe, 0xf5, 0xd0, 0x6d, 0xce, 0xb7, 0x85, - 0x30, 0x80, 0x78, 0x32, 0x8e, 0xee, 0x1d, 0x64, 0x85, 0x14, 0x5b, 0x89, 0x81, 0xfd, 0x91, 0x34, - 0x20, 0x3e, 0x9c, 0x0e, 0xf1, 0x40, 0x42, 0x21, 0xe2, 0xe7, 0x46, 0x97, 0x71, 0x29, 0x11, 0xa5, - 0xca, 0x93, 0x8e, 0x8b, 0x12, 0xbc, 0xf5, 0x57, 0x67, 0xc7, 0x9e, 0xec, 0x89, 0xb5, 0x2b, 0x31, - 0xd9, 0xb8, 0xbe, 0x79, 0x87, 0x2e, 0x7e, 0xb1, 0x4a, 0x4b, 0x9d, 0x96, 0x3a, 0x6d, 0x3b, 0x6d, - 0x3d, 0x9c, 0xa5, 0x3f, 0x19, 0x47, 0xf4, 0x02, 0xd2, 0x76, 0x7a, 0xa6, 0x6d, 0x0e, 0xdc, 0x85, - 0x60, 0xdf, 0x6f, 0x5a, 0xed, 0xb4, 0x2b, 0xcb, 0x68, 0x1f, 0xcc, 0xb5, 0xe7, 0xbd, 0x6b, 0x57, - 0xd7, 0xa5, 0x0d, 0xab, 0xdb, 0x69, 0xf0, 0x85, 0xf8, 0x01, 0x2f, 0x32, 0x44, 0x39, 0x90, 0x3c, - 0x9b, 0xfd, 0x68, 0xe7, 0x6f, 0x2c, 0xe3, 0x7f, 0x32, 0xf7, 0x3f, 0x3a, 0xc7, 0xff, 0xf4, 0x2f, - 0x4f, 0x3d, 0xcb, 0x0d, 0xbe, 0x70, 0x6b, 0x6b, 0xf5, 0xe3, 0x61, 0xe4, 0xfd, 0x3e, 0x8c, 0xbc, - 0xe4, 0xb6, 0x7f, 0xb3, 0x7b, 0x56, 0xc3, 0x0e, 0xe0, 0x50, 0x2b, 0x84, 0xcd, 0x6f, 0xc4, 0x5f, - 0xd9, 0xc1, 0x3c, 0xf8, 0x4a, 0xfc, 0x66, 0xc7, 0x35, 0x33, 0x48, 0xe9, 0x25, 0x7a, 0x4d, 0xe7, - 0x8d, 0x5c, 0x7f, 0x75, 0x29, 0xca, 0x7f, 0xa2, 0x26, 0x5e, 0x4b, 0x1d, 0x4d, 0x42, 0x72, 0x3c, - 0x09, 0xc9, 0xaf, 0x49, 0x48, 0x3e, 0x4d, 0x43, 0xef, 0x78, 0x1a, 0x7a, 0x3f, 0xa6, 0xa1, 0xf7, - 0xa6, 0x7b, 0xe1, 0xa2, 0x2f, 0xb1, 0xee, 0xfd, 0xa6, 0x5b, 0xb4, 0xfb, 0x7f, 0x02, 0x00, 0x00, - 0xff, 0xff, 0xa5, 0xb6, 0x54, 0x53, 0x34, 0x04, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Revoke(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Revoke(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.orders.internal.transactions.revoke.Msg/Revoke", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Revoke(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Revoke(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Revoke not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Revoke_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Revoke(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.orders.internal.transactions.revoke.Msg/Revoke", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Revoke(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.orders.internal.transactions.revoke.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Revoke", - Handler: _Msg_Revoke_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/orders/internal/transactions/revoke/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.ClassificationID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ToID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ToID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ClassificationID.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ToID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ToID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ClassificationID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/orders/internal/transactions/revoke/message_test.go b/modules/orders/internal/transactions/revoke/message_test.go index 589980896..8bcd0e74a 100644 --- a/modules/orders/internal/transactions/revoke/message_test.go +++ b/modules/orders/internal/transactions/revoke/message_test.go @@ -1,40 +1,256 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Revoke_Message(t *testing.T) { - - testFromID := base.NewID("fromID") - testToID := base.NewID("toID") - testClassificationID := base.NewID("classificationID") - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - require.Equal(t, nil, Error) - - testMessage := newMessage(fromAccAddress, testFromID, testToID, testClassificationID) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, ToID: testToID, ClassificationID: testClassificationID}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +var ( + testMessage = newMessage(fromAccAddress, testFromID, testFromID, testClassificationID) +) + +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg types.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{testMessage}, message{fromAccAddress, testFromID, testFromID, testClassificationID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, testFromID, testFromID, testClassificationID}, types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(testMessage))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want []types.AccAddress + }{ + {"+ve", fields{fromAccAddress, testFromID, testFromID, testClassificationID}, []types.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, testFromID, testFromID, testClassificationID}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testFromID, testClassificationID}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, testFromID, testClassificationID}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + ClassificationID ids.ClassificationID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve with nil", fields{}, true}, + {"+ve", fields{fromAccAddress, testFromID, testFromID, testClassificationID}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_newMessage(t *testing.T) { + type args struct { + from types.AccAddress + fromID ids.IdentityID + toID ids.IdentityID + classificationID ids.ClassificationID + } + tests := []struct { + name string + args args + want types.Msg + }{ + {"+ve", args{fromAccAddress, testFromID, testFromID, testClassificationID}, message{fromAccAddress, testFromID, testFromID, testClassificationID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.toID, tt.args.classificationID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/revoke/msg_server.go b/modules/orders/internal/transactions/revoke/msg_server.go deleted file mode 100644 index 90b15d9b8..000000000 --- a/modules/orders/internal/transactions/revoke/msg_server.go +++ /dev/null @@ -1,30 +0,0 @@ -package revoke - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/maintainers/auxiliaries/revoke" -) - -type msgServer struct { - transactionKeeper -} - -func (msgServer msgServer) Revoke(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - if auxiliaryResponse := msgServer.transactionKeeper.revokeAuxiliary.GetKeeper().Help(ctx, revoke.NewAuxiliaryRequest(&message.FromID, &message.ToID, &message.ClassificationID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} - -var _ MsgServer = msgServer{} diff --git a/modules/orders/internal/transactions/revoke/request.go b/modules/orders/internal/transactions/revoke/request.go index 3c69e6e2e..b61808bcc 100644 --- a/modules/orders/internal/transactions/revoke/request.go +++ b/modules/orders/internal/transactions/revoke/request.go @@ -1,22 +1,21 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke import ( "encoding/json" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -28,31 +27,31 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary revoke order transaction -// @Descrption revoke order transaction +// Validate godoc +// @Summary Revoke order transaction +// @Description Revoke order transaction // @Accept text/plain // @Produce json // @Tags Orders -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "error" +// @Param body transactionRequest true "Request body to revoke order" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /orders/revoke [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ToID), - cliCommand.ReadString(flags.ClassificationID), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ToID), + cliCommand.ReadString(constants.ClassificationID), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -61,20 +60,35 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + toID, err := baseIDs.ReadIdentityID(transactionRequest.ToID) + if err != nil { + return nil, err + } + + classificationID, err := baseIDs.ReadClassificationID(transactionRequest.ClassificationID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.ToID), - base.NewID(transactionRequest.ClassificationID), + fromID, + toID, + classificationID, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/orders/internal/transactions/revoke/request_test.go b/modules/orders/internal/transactions/revoke/request_test.go index 5aac79628..04a669617 100644 --- a/modules/orders/internal/transactions/revoke/request_test.go +++ b/modules/orders/internal/transactions/revoke/request_test.go @@ -1,71 +1,286 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke import ( "encoding/json" + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/spf13/viper" "github.com/stretchr/testify/require" - "testing" -) -func Test_Revoke_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.ToID, flags.ClassificationID}) - cliContext := context.NewCLIContext().WithCodec(Codec) + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) +var ( + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = types.AccAddressFromBech32(fromAddress) + immutables = baseQualified.NewImmutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables = baseQualified.NewMutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "toID", "classificationID") + testClassificationID = baseIDs.NewClassificationID(immutables, mutables) + testFromID = baseIDs.NewIdentityID(testClassificationID, immutables) + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} +) - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ToID: "toID", ClassificationID: "classificationID"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + toID string + classificationID string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String()}, transactionRequest{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.toID, tt.args.classificationID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ToID: "", ClassificationID: ""}, requestFromCLI) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.ToID, constants.ClassificationID}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.FromID.GetName(), testFromID.String()) + viper.Set(constants.ToID.GetName(), testFromID.String()) + viper.Set(constants.ClassificationID.GetName(), testClassificationID.String()) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String()}, args{cliCommand, cliContext}, transactionRequest{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +func Test_transactionRequest_FromJSON(t *testing.T) { + jsonMessage, err := json.Marshal(newTransactionRequest(testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String())) + require.NoError(t, err) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String()}, args{jsonMessage}, newTransactionRequest(testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String()}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("toID"), base.NewID("classificationID")), msg) - require.Nil(t, Error) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String()}, newMessage(fromAccAddress, testFromID, testFromID, testClassificationID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error := newTransactionRequest(rest.BaseReq{From: "randomString", ChainID: "test", Fees: sdkTypes.NewCoins()}, "fromID", "toID", "classificationID").MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + ClassificationID string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), testFromID.String(), testClassificationID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + ClassificationID: tt.fields.ClassificationID, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/orders/internal/transactions/revoke/response.go b/modules/orders/internal/transactions/revoke/response.go new file mode 100644 index 000000000..f4e2a16c2 --- /dev/null +++ b/modules/orders/internal/transactions/revoke/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/orders/internal/transactions/revoke/response_test.go b/modules/orders/internal/transactions/revoke/response_test.go index b386df6a6..87e8625d7 100644 --- a/modules/orders/internal/transactions/revoke/response_test.go +++ b/modules/orders/internal/transactions/revoke/response_test.go @@ -1,25 +1,84 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package revoke import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/stretchr/testify/require" + "reflect" "testing" -) -func Test_Revoke_Response(t *testing.T) { + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) - testTransactionResponse := newTransactionResponse(errors.IncorrectFormat) - testTransactionResponse2 := newTransactionResponse(nil) +func Test_newTransactionResponse(t *testing.T) { + type args struct { + error error + } + tests := []struct { + name string + args args + want helpers.TransactionResponse + }{ + {"+ve", args{nil}, transactionResponse{true, nil}}, + {"-ve", args{constants.IncorrectFormat}, transactionResponse{false, constants.IncorrectFormat}}} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionResponse(tt.args.error); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionResponse() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, transactionResponse{Success: false, Error: errors.IncorrectFormat}, testTransactionResponse) - require.Equal(t, false, testTransactionResponse.IsSuccessful()) - require.Equal(t, true, testTransactionResponse2.IsSuccessful()) +func Test_transactionResponse_GetError(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{Success: true, Error: nil}, false}, + {"-ve", fields{Success: false, Error: constants.IncorrectFormat}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if err := transactionResponse.GetError(); (err != nil) != tt.wantErr { + t.Errorf("GetError() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} - require.Equal(t, errors.IncorrectFormat, testTransactionResponse.GetError()) - require.Equal(t, nil, testTransactionResponse2.GetError()) +func Test_transactionResponse_IsSuccessful(t *testing.T) { + type fields struct { + Success bool + Error error + } + tests := []struct { + name string + fields fields + want bool + }{ + {"+ve", fields{Success: true, Error: nil}, true}, + {"-ve", fields{Success: false, Error: constants.IncorrectFormat}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionResponse := transactionResponse{ + Success: tt.fields.Success, + Error: tt.fields.Error, + } + if got := transactionResponse.IsSuccessful(); got != tt.want { + t.Errorf("IsSuccessful() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/revoke/transaction.go b/modules/orders/internal/transactions/revoke/transaction.go new file mode 100644 index 000000000..94603fa7c --- /dev/null +++ b/modules/orders/internal/transactions/revoke/transaction.go @@ -0,0 +1,23 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package revoke + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "revoke", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.ToID, + constants.ClassificationID, +) diff --git a/modules/orders/internal/transactions/take/keeper.go b/modules/orders/internal/transactions/take/keeper.go new file mode 100644 index 000000000..565599aef --- /dev/null +++ b/modules/orders/internal/transactions/take/keeper.go @@ -0,0 +1,113 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package take + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/properties/constants" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(errorConstants.EntityNotFound) + } + + orders := transactionKeeper.mapper.NewCollection(context).Fetch(key.NewKey(message.OrderID)) + + Mutable := orders.Get(key.NewKey(message.OrderID)) + if Mutable == nil { + return newTransactionResponse(errorConstants.EntityNotFound) + } + order := Mutable.(documents.Order) + + if order.GetTakerID().Compare(baseIDs.PrototypeIdentityID()) != 0 && order.GetTakerID().Compare(message.FromID) != 0 { + return newTransactionResponse(errorConstants.NotAuthorized) + } + + makerReceiveTakerOwnableSplit := order.GetMakerOwnableSplit().MulTruncate(order.GetExchangeRate()).MulTruncate(sdkTypes.SmallestDec()) + takerReceiveMakerOwnableSplit := message.TakerOwnableSplit.QuoTruncate(sdkTypes.SmallestDec()).QuoTruncate(order.GetExchangeRate()) + + switch updatedMakerOwnableSplit := order.GetMakerOwnableSplit().Sub(takerReceiveMakerOwnableSplit); { + case updatedMakerOwnableSplit.Equal(sdkTypes.ZeroDec()): + if message.TakerOwnableSplit.LT(makerReceiveTakerOwnableSplit) { + return newTransactionResponse(errorConstants.InsufficientBalance) + } + + orders.Remove(mappable.NewMappable(order)) + case updatedMakerOwnableSplit.LT(sdkTypes.ZeroDec()): + if message.TakerOwnableSplit.LT(makerReceiveTakerOwnableSplit) { + return newTransactionResponse(errorConstants.InsufficientBalance) + } + + takerReceiveMakerOwnableSplit = order.GetMakerOwnableSplit() + + orders.Remove(mappable.NewMappable(order)) + default: + makerReceiveTakerOwnableSplit = message.TakerOwnableSplit + mutableProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(constants.MakerOwnableSplitProperty.GetKey(), baseData.NewDecData(updatedMakerOwnableSplit))) + + orders.Mutate(mappable.NewMappable(base.NewOrder(order.GetClassificationID(), order.GetImmutables(), order.GetMutables().Mutate(mutableProperties.GetList()...)))) + } + + if auxiliaryResponse := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(message.FromID, order.GetMakerID(), order.GetTakerOwnableID(), makerReceiveTakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + if auxiliaryResponse := transactionKeeper.transferAuxiliary.GetKeeper().Help(context, transfer.NewAuxiliaryRequest(module.ModuleIdentityID, message.FromID, order.GetMakerOwnableID(), takerReceiveMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case helpers.Auxiliary: + switch value.GetName() { + case supplement.Auxiliary.GetName(): + transactionKeeper.supplementAuxiliary = value + case transfer.Auxiliary.GetName(): + transactionKeeper.transferAuxiliary = value + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + } + default: + panic(errorConstants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/orders/internal/transactions/take/keeper_test.go b/modules/orders/internal/transactions/take/keeper_test.go index 81e2b5052..e74db48af 100644 --- a/modules/orders/internal/transactions/take/keeper_test.go +++ b/modules/orders/internal/transactions/take/keeper_test.go @@ -1,56 +1,64 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package take import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" - cryptoCodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/store" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/constants/test" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/transfer" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/orders/internal/key" + "github.com/AssetMantle/modules/modules/orders/internal/mappable" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +var ( + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary ) type TestKeepers struct { - OrdersKeeper helpers.TransactionKeeper + TakeKeeper helpers.TransactionKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { - +func CreateTestInput(t *testing.T) (types.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { var Codec = codec.New() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + schema.RegisterCodec(Codec) + types.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + storeKey := types.NewKVStoreKey("test") + paramsStoreKey := types.NewKVStoreKey("testParams") + paramsTransientStoreKeys := types.NewTransientStoreKey("testParamsTransient") Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) paramsKeeper := params.NewKeeper( Codec, @@ -61,145 +69,148 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + commitMultiStore.MountStoreWithDB(storeKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, types.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, types.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) + supplementAuxiliary = supplement.AuxiliaryMock.Initialize(Mapper, Parameters) + transferAuxiliary = transfer.AuxiliaryMock.Initialize(Mapper, Parameters) - context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + context := types.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", - Height: 100, }, false, log.NewNopLogger()) - scrubAuxiliary := scrub.AuxiliaryMock.Initialize(Mapper, Parameters) - transferAuxiliary := transfer.AuxiliaryMock.Initialize(Mapper, Parameters) - verifyAuxiliary := verify.AuxiliaryMock.Initialize(Mapper, Parameters) - supplementAuxiliary := supplement.AuxiliaryMock.Initialize(Mapper, Parameters) keepers := TestKeepers{ - OrdersKeeper: keeperPrototype().Initialize(Mapper, Parameters, - []interface{}{scrubAuxiliary, verifyAuxiliary, - transferAuxiliary, supplementAuxiliary}).(helpers.TransactionKeeper), + TakeKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), } - return context, keepers + return context, keepers, Mapper, Parameters } -func Test_transactionKeeper_Transact(t *testing.T) { +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - context, keepers := CreateTestInput(t) - verifyMockErrorAddress := sdkTypes.AccAddress("verifyError") - defaultAddr := sdkTypes.AccAddress("addr") - defaultIdentityID := base.NewID("fromID") - classificationID := base.NewID("classificationID") - makerOwnableID := base.NewID("makerOwnableID") - takerOwnableID := base.NewID("takerOwnableID") - rateID := base.NewID(sdkTypes.OneDec().MulInt64(2).Quo(sdkTypes.SmallestDec()).Quo(sdkTypes.SmallestDec()).String()) - creationID := base.NewID("100") - orderID := key.NewOrderID(classificationID, makerOwnableID, - takerOwnableID, rateID, creationID, defaultIdentityID, base.NewProperties()) - metaProperties, Error := base.ReadMetaProperties(properties.MakerOwnableSplit + ":D|0.000000000000000001" + - "," + properties.TakerID + ":I|fromID") - require.Equal(t, nil, Error) - - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(orderID, base.NewProperties(), metaProperties.RemoveData())) - - t.Run("PositiveCase", func(t *testing.T) { - metaProperties, Error := base.ReadMetaProperties(properties.MakerOwnableSplit + ":D|0.000000000000000001" + - "," + properties.TakerID + ":I|fromID") - require.Equal(t, nil, Error) - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(orderID, base.NewProperties(), metaProperties.RemoveData())) - - want := newTransactionResponse(nil) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, sdkTypes.OneDec().MulInt64(2), - orderID)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - Identity mock error", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(errors.EntityNotFound) - if got := keepers.OrdersKeeper.Transact(context, newMessage(verifyMockErrorAddress, defaultIdentityID, sdkTypes.SmallestDec(), orderID)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - No order", func(t *testing.T) { - t.Parallel() - - want := newTransactionResponse(errors.EntityNotFound) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, sdkTypes.SmallestDec(), - base.NewID("orderID"))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - transfer mock fail", func(t *testing.T) { - t.Parallel() - transferErrorID := key.NewOrderID(classificationID, makerOwnableID, - base.NewID("transferError"), rateID, creationID, defaultIdentityID, base.NewProperties()) - metaProperties, Error := base.ReadMetaProperties(properties.MakerOwnableSplit + ":D|0.000000000000000001" + - "," + properties.TakerID + ":I|fromID") - require.Equal(t, nil, Error) - - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(transferErrorID, base.NewProperties(), metaProperties.RemoveData())) - - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, sdkTypes.SmallestDec(), - transferErrorID)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - transfer mock fail", func(t *testing.T) { - t.Parallel() - transferErrorID := key.NewOrderID(classificationID, base.NewID("transferError"), - takerOwnableID, rateID, creationID, defaultIdentityID, base.NewProperties()) - metaProperties, Error := base.ReadMetaProperties(properties.MakerOwnableSplit + ":D|0.000000000000000001" + - "," + properties.TakerID + ":I|fromID" + "," + - properties.ExchangeRate + ":D|1") - require.Equal(t, nil, Error) - - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(transferErrorID, base.NewProperties(), metaProperties.RemoveData())) - - want := newTransactionResponse(test.MockError) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, sdkTypes.SmallestDec(), - transferErrorID)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase - transfer mock fail", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(errors.NotAuthorized) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, base.NewID("id"), sdkTypes.SmallestDec(), orderID)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("Positive Case - take more than make order", func(t *testing.T) { - t.Parallel() - orderID := key.NewOrderID(classificationID, makerOwnableID, - takerOwnableID, rateID, creationID, defaultIdentityID, base.NewProperties()) - metaProperties, Error := base.ReadMetaProperties(properties.MakerOwnableSplit + ":D|0.000000000000000001" + - "," + properties.TakerID + ":I|fromID" + "," + - properties.ExchangeRate + ":D|1") - require.Equal(t, nil, Error) - - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(orderID, base.NewProperties(), metaProperties.RemoveData())) - - want := newTransactionResponse(nil) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, sdkTypes.SmallestDec().MulInt64(1), - orderID)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - keepers.OrdersKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewOrder(orderID, base.NewProperties(), metaProperties.RemoveData())) - want = newTransactionResponse(nil) - if got := keepers.OrdersKeeper.Transact(context, newMessage(defaultAddr, defaultIdentityID, sdkTypes.SmallestDec().MulInt64(10), - orderID)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := CreateTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve with nil", fields{}, args{}, transactionKeeper{}}, + {"+ve", fields{Mapper, Parameters, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + supplementAuxiliary: tt.fields.supplementAuxiliary, + transferAuxiliary: tt.fields.transferAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters := CreateTestInput(t) + mutableMetaProperties := baseLists.NewPropertyList( + baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())), + baseProperties.NewMetaProperty(baseIDs.NewStringID("exchangeRate"), baseData.NewDecData(types.NewDec(10))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerOwnableID"), baseData.NewIDData(baseIDs.NewOwnableID(baseIDs.NewStringID("makerID")))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("creationHeight"), baseData.NewHeightData(baseTypes.NewHeight(1))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("takerOwnableID"), baseData.NewIDData(baseIDs.NewOwnableID(baseIDs.NewStringID("takerID")))), + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(baseIDs.PrototypeIdentityID())), + baseProperties.NewMetaProperty(baseIDs.NewStringID("takerID"), baseData.NewIDData(baseIDs.PrototypeIdentityID())), + ) + immutableMetaProperties := baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewListData(baseLists.NewDataList()))) + immutablesMeta := baseQualified.NewImmutables(immutableMetaProperties) + mutablesMeta := baseQualified.NewMutables(mutableMetaProperties) + testClassificationID := baseIDs.NewClassificationID(immutablesMeta, mutablesMeta) + testFromID := baseIDs.NewIdentityID(testClassificationID, immutablesMeta) + testFromID2 := baseIDs.PrototypeIdentityID() + mutableMetaProperties.Mutate( + baseProperties.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(testFromID)), + baseProperties.NewMetaProperty(baseIDs.NewStringID("takerID"), baseData.NewIDData(testFromID))) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := types.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + testIdentity := baseDocuments.NewIdentity(testClassificationID, immutablesMeta, mutablesMeta) + testIdentity.ProvisionAddress([]types.AccAddress{fromAccAddress}...) + testOrder := baseDocuments.NewOrder(testClassificationID, immutablesMeta, mutablesMeta) + // testMakerOwnableID := baseIDs.NewOwnableID(baseIDs.NewStringID("makerID")) + // testTakerOwnableID := baseIDs.NewOwnableID(baseIDs.NewStringID("takerID")) + testRate := types.NewDec(10) + // testHeight := baseTypes.NewHeight(1) + testOrderID := baseIDs.NewOrderID(testClassificationID, immutablesMeta) + testOrderID2 := baseIDs.NewOrderID(testClassificationID, immutablesMeta) + keepers.TakeKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(testOrder)) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplementAuxiliary helpers.Auxiliary + transferAuxiliary helpers.Auxiliary + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + context types.Context + msg types.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve Not Authorized", fields{Mapper, Parameters, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}, args{context, newMessage(fromAccAddress, testFromID2, testRate, testOrderID)}, newTransactionResponse(errorConstants.NotAuthorized)}, + {"+ve", fields{Mapper, Parameters, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}, args{context, newMessage(fromAccAddress, testFromID, testRate, testOrderID)}, newTransactionResponse(nil)}, + {"+ve Entity Not Found", fields{Mapper, Parameters, supplementAuxiliary, transferAuxiliary, authenticateAuxiliary}, args{context, newMessage(fromAccAddress, testFromID, testRate, testOrderID2)}, newTransactionResponse(errorConstants.EntityNotFound)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + supplementAuxiliary: tt.fields.supplementAuxiliary, + transferAuxiliary: tt.fields.transferAuxiliary, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/take/message.go b/modules/orders/internal/transactions/take/message.go index d9bc55191..b1b7320eb 100644 --- a/modules/orders/internal/transactions/take/message.go +++ b/modules/orders/internal/transactions/take/message.go @@ -1,70 +1,66 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package take import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/orders/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ sdkTypes.Msg = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + TakerOwnableSplit sdkTypes.Dec `json:"takerOwnableSplit" valid:"required~required field takerOwnableSplit missing"` + ids.OrderID `json:"orderID" valid:"required~required field orderID missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, takerOwnableSplit sdkTypes.Dec, orderID types.ID) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, takerOwnableSplit sdkTypes.Dec, orderID ids.OrderID) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, TakerOwnableSplit: takerOwnableSplit, - OrderID: *base.NewID(orderID.String()), + OrderID: orderID, } } diff --git a/modules/orders/internal/transactions/take/message.pb.go b/modules/orders/internal/transactions/take/message.pb.go deleted file mode 100644 index ce1596cfc..000000000 --- a/modules/orders/internal/transactions/take/message.pb.go +++ /dev/null @@ -1,681 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/orders/internal/transactions/take/message.proto - -package take - -import ( - context "context" - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - TakerOwnableSplit github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=taker_ownable_split,json=takerOwnableSplit,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"taker_ownable_split" valid:"required~required field TakerOwnableSplit missing"` - OrderID base.ID `protobuf:"bytes,4,opt,name=order_i_d,json=orderID,proto3" json:"order_i_d" valid:"required~required field OrderID missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_4e4f159f493b6506, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4e4f159f493b6506, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.orders.internal.transactions.take.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.orders.internal.transactions.take.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/orders/internal/transactions/take/message.proto", fileDescriptor_4e4f159f493b6506) -} - -var fileDescriptor_4e4f159f493b6506 = []byte{ - // 503 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0x4f, 0x6b, 0xd4, 0x40, - 0x18, 0xc6, 0x33, 0x76, 0xe9, 0x9f, 0x78, 0x32, 0x55, 0x28, 0x7b, 0x48, 0x96, 0x05, 0xa5, 0x88, - 0xce, 0x40, 0x05, 0xa5, 0xbd, 0x75, 0x59, 0x95, 0x22, 0x75, 0x61, 0xdb, 0x93, 0x97, 0x90, 0xcd, - 0xbc, 0x9b, 0x0e, 0x9b, 0x64, 0xe2, 0xbc, 0xb3, 0x16, 0x05, 0x3d, 0x7b, 0xd4, 0xb3, 0x1e, 0x7a, - 0xf0, 0x53, 0xf8, 0x09, 0x7a, 0xec, 0x51, 0x3c, 0x04, 0xd9, 0xbd, 0x78, 0xde, 0x4f, 0x20, 0x93, - 0xa4, 0x6c, 0x58, 0x85, 0xae, 0x7a, 0x9a, 0xc9, 0x24, 0xfc, 0x9e, 0x27, 0x3f, 0xde, 0xb1, 0x9f, - 0x66, 0xa0, 0x50, 0xa0, 0x86, 0x34, 0x04, 0x1f, 0xf9, 0x88, 0x25, 0x92, 0x8f, 0x63, 0x40, 0x26, - 0x15, 0x07, 0x85, 0x4c, 0xa4, 0x1a, 0x54, 0x1a, 0xc4, 0x4c, 0xab, 0x20, 0xc5, 0x20, 0xd4, 0x42, - 0xa6, 0xc8, 0x74, 0x30, 0x02, 0x96, 0x00, 0x62, 0x10, 0x01, 0xcd, 0x94, 0xd4, 0xd2, 0xd9, 0x5d, - 0x00, 0xd1, 0x0a, 0x44, 0x4b, 0x10, 0xbd, 0x04, 0xd1, 0x3a, 0x88, 0x1a, 0x50, 0xf3, 0x66, 0x24, - 0x23, 0x59, 0x50, 0x98, 0xd9, 0x95, 0xc0, 0xe6, 0xdd, 0xc5, 0x66, 0x18, 0x9e, 0x40, 0x12, 0x30, - 0xfd, 0x3a, 0x03, 0x64, 0x83, 0x00, 0x81, 0x09, 0x5e, 0x7e, 0xdb, 0xfe, 0xda, 0xb0, 0xd7, 0x0e, - 0xcb, 0x3a, 0xce, 0x47, 0x62, 0x37, 0x86, 0x4a, 0x26, 0x5b, 0xa4, 0x45, 0xb6, 0x37, 0x3a, 0x6f, - 0xcf, 0x73, 0xcf, 0xfa, 0x9e, 0x7b, 0x8f, 0x23, 0xa1, 0x4f, 0xc6, 0x03, 0x1a, 0xca, 0x84, 0xd5, - 0xc8, 0xbd, 0x14, 0xea, 0x8f, 0x47, 0xdd, 0x67, 0xbf, 0xe7, 0xd0, 0xfd, 0x30, 0xdc, 0xe7, 0x5c, - 0x01, 0xe2, 0x2c, 0xf7, 0xee, 0xbd, 0x0a, 0x62, 0xc1, 0xf7, 0xda, 0x0a, 0x5e, 0x8e, 0x85, 0x02, - 0xfe, 0xee, 0x72, 0xd3, 0x1a, 0x0a, 0x88, 0x79, 0xeb, 0x89, 0x92, 0x49, 0x2b, 0x11, 0x88, 0x22, - 0x8d, 0xda, 0xfd, 0xa2, 0x8a, 0x73, 0x6a, 0xaf, 0x9b, 0xd5, 0x17, 0x3e, 0xdf, 0xba, 0xd6, 0x22, - 0xdb, 0xd7, 0x77, 0x6e, 0xd3, 0x45, 0x5f, 0x65, 0x2c, 0x2d, 0x62, 0x69, 0x11, 0x7b, 0xd0, 0xed, - 0x3c, 0x34, 0xed, 0x67, 0xb9, 0x47, 0x97, 0x08, 0x3d, 0xe8, 0xce, 0x63, 0x57, 0x87, 0xc5, 0x81, - 0xf3, 0x89, 0xd8, 0x9b, 0xc6, 0xb1, 0xf2, 0xe5, 0x69, 0x1a, 0x0c, 0x62, 0xf0, 0x31, 0x8b, 0x85, - 0xde, 0x5a, 0x29, 0xdc, 0x8c, 0x2a, 0x37, 0x77, 0x6a, 0x6e, 0x42, 0x89, 0x89, 0xc4, 0x6a, 0xb9, - 0x6f, 0xbc, 0x97, 0x8d, 0xba, 0x10, 0xce, 0x72, 0x6f, 0xf7, 0x8a, 0x1e, 0xc7, 0x26, 0xab, 0x57, - 0x46, 0x1d, 0x99, 0xa4, 0x79, 0xa5, 0x1b, 0x7a, 0xf1, 0x9d, 0xf3, 0xc6, 0xde, 0x28, 0xa6, 0xa3, - 0xf0, 0xd2, 0xf8, 0x1b, 0x2f, 0x8f, 0x2a, 0x2f, 0xec, 0x8a, 0x3e, 0x3d, 0x83, 0xaf, 0x8b, 0x59, - 0x93, 0xe5, 0xc9, 0xde, 0xfa, 0xfb, 0x33, 0xcf, 0xfa, 0x79, 0xe6, 0x59, 0xed, 0x5b, 0xf6, 0xe6, - 0xf1, 0x7c, 0x26, 0xfb, 0x80, 0x99, 0x4c, 0x11, 0x76, 0xbe, 0x10, 0x7b, 0xe5, 0x10, 0x23, 0xe7, - 0x33, 0xb1, 0x1b, 0xe6, 0xb7, 0x9c, 0x0e, 0xfd, 0xe7, 0x11, 0xa7, 0xd5, 0x70, 0x36, 0x9f, 0xff, - 0x07, 0xe3, 0x0f, 0x25, 0xdb, 0x56, 0x27, 0x3e, 0x9f, 0xb8, 0xe4, 0x62, 0xe2, 0x92, 0x1f, 0x13, - 0x97, 0x7c, 0x98, 0xba, 0xd6, 0xc5, 0xd4, 0xb5, 0xbe, 0x4d, 0x5d, 0xeb, 0x45, 0x7f, 0xe9, 0x89, - 0x5f, 0xfa, 0xce, 0x0f, 0x56, 0x8b, 0xfb, 0xf6, 0xe0, 0x57, 0x00, 0x00, 0x00, 0xff, 0xff, 0x6a, - 0xc2, 0xdf, 0x4a, 0x37, 0x04, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Take(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Take(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.orders.internal.transactions.take.Msg/Take", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Take(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Take(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Take not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Take_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Take(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.orders.internal.transactions.take.Msg/Take", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Take(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.orders.internal.transactions.take.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Take", - Handler: _Msg_Take_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/orders/internal/transactions/take/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.OrderID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size := m.TakerOwnableSplit.Size() - i -= size - if _, err := m.TakerOwnableSplit.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.TakerOwnableSplit.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.OrderID.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TakerOwnableSplit", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TakerOwnableSplit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OrderID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OrderID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/orders/internal/transactions/take/message_test.go b/modules/orders/internal/transactions/take/message_test.go index 3f18b9171..d92c8b9bd 100644 --- a/modules/orders/internal/transactions/take/message_test.go +++ b/modules/orders/internal/transactions/take/message_test.go @@ -1,41 +1,256 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package take import ( + "reflect" "testing" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Take_Message(t *testing.T) { +var ( + testMessage = newMessage(fromAccAddress, testFromID, takerOwnableSplit, testOrderID) +) + +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg types.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{testMessage}, message{fromAccAddress, testFromID, takerOwnableSplit, testOrderID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + TakerOwnableSplit types.Dec + OrderID ids.OrderID + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, testFromID, takerOwnableSplit, testOrderID}, types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(testMessage))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + OrderID: tt.fields.OrderID, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} - testFromID := base.NewID("fromID") - testOrderID := base.NewID("orderID") - testTakerOwnableSplit := sdkTypes.NewDec(2) +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + TakerOwnableSplit types.Dec + OrderID ids.OrderID + } + tests := []struct { + name string + fields fields + want []types.AccAddress + }{ + {"+ve", fields{fromAccAddress, testFromID, takerOwnableSplit, testOrderID}, []types.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + OrderID: tt.fields.OrderID, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + TakerOwnableSplit types.Dec + OrderID ids.OrderID + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, testFromID, takerOwnableSplit, testOrderID}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + OrderID: tt.fields.OrderID, + } + me.RegisterCodec(tt.args.codec) + }) + } +} - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, err) +func Test_message_Route(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + TakerOwnableSplit types.Dec + OrderID ids.OrderID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, takerOwnableSplit, testOrderID}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + OrderID: tt.fields.OrderID, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} - testMessage := newMessage(fromAccAddress, testFromID, testTakerOwnableSplit, testOrderID) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, TakerOwnableSplit: testTakerOwnableSplit, OrderID: testOrderID}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +func Test_message_Type(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + TakerOwnableSplit types.Dec + OrderID ids.OrderID + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, testFromID, takerOwnableSplit, testOrderID}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + OrderID: tt.fields.OrderID, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + TakerOwnableSplit types.Dec + OrderID ids.OrderID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"-ve with nil", fields{}, true}, + {"+ve", fields{fromAccAddress, testFromID, takerOwnableSplit, testOrderID}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + OrderID: tt.fields.OrderID, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from types.AccAddress + fromID ids.IdentityID + takerOwnableSplit types.Dec + orderID ids.OrderID + } + tests := []struct { + name string + args args + want types.Msg + }{ + {"+ve", args{fromAccAddress, testFromID, takerOwnableSplit, testOrderID}, message{fromAccAddress, testFromID, takerOwnableSplit, testOrderID}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.takerOwnableSplit, tt.args.orderID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/orders/internal/transactions/take/msg_server.go b/modules/orders/internal/transactions/take/msg_server.go deleted file mode 100644 index 8d93b4edc..000000000 --- a/modules/orders/internal/transactions/take/msg_server.go +++ /dev/null @@ -1,110 +0,0 @@ -package take - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/properties" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/scrub" - "github.com/persistenceOne/persistenceSDK/modules/metas/auxiliaries/supplement" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/splits/auxiliaries/transfer" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -func (msgServer msgServer) Take(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, errors.EntityNotFound - } - - orderID := message.OrderID - orders := msgServer.transactionKeeper.mapper.NewCollection(ctx).Fetch(key.FromID(&orderID)) - order := orders.Get(key.FromID(&orderID)) - - if order == nil { - return nil, errors.EntityNotFound - } - - metaProperties, Error := supplement.GetMetaPropertiesFromResponse(msgServer.transactionKeeper.supplementAuxiliary.GetKeeper().Help(ctx, supplement.NewAuxiliaryRequest(order.(mappables.Order).GetTakerID(), order.(mappables.Order).GetMakerOwnableSplit()))) - if Error != nil { - return nil, Error - } - - if takerIDProperty := metaProperties.Get(base.NewID(properties.TakerID)); takerIDProperty != nil { - takerID, Error := takerIDProperty.GetMetaFact().GetData().AsID() - if Error != nil { - return nil, errors.MetaDataError - } else if takerID.Compare(base.NewID("")) != 0 && takerID.Compare(&message.FromID) != 0 { - return nil, errors.NotAuthorized - } - } - - exchangeRate, Error := order.(mappables.Order).GetExchangeRate().GetMetaFact().GetData().AsDec() - if Error != nil { - return nil, Error - } - - makerOwnableSplitProperty := metaProperties.Get(base.NewID(properties.MakerOwnableSplit)) - if makerOwnableSplitProperty == nil { - return nil, errors.MetaDataError - } - - makerOwnableSplit, Error := makerOwnableSplitProperty.GetMetaFact().GetData().AsDec() - if Error != nil { - return nil, errors.MetaDataError - } - - makerReceiveTakerOwnableSplit := makerOwnableSplit.MulTruncate(exchangeRate).MulTruncate(sdkTypes.SmallestDec()) - takerReceiveMakerOwnableSplit := message.TakerOwnableSplit.QuoTruncate(sdkTypes.SmallestDec()).QuoTruncate(exchangeRate) - - switch updatedMakerOwnableSplit := makerOwnableSplit.Sub(takerReceiveMakerOwnableSplit); { - case updatedMakerOwnableSplit.Equal(sdkTypes.ZeroDec()): - if message.TakerOwnableSplit.LT(makerReceiveTakerOwnableSplit) { - return nil, errors.InsufficientBalance - } - - orders.Remove(order) - case updatedMakerOwnableSplit.LT(sdkTypes.ZeroDec()): - if message.TakerOwnableSplit.LT(makerReceiveTakerOwnableSplit) { - return nil, errors.InsufficientBalance - } - - takerReceiveMakerOwnableSplit = makerOwnableSplit - - orders.Remove(order) - default: - makerReceiveTakerOwnableSplit = message.TakerOwnableSplit - mutableProperties, Error := scrub.GetPropertiesFromResponse(msgServer.transactionKeeper.scrubAuxiliary.GetKeeper().Help(ctx, scrub.NewAuxiliaryRequest(base.NewMetaProperty(base.NewID(properties.MakerOwnableSplit), base.NewMetaFact(base.NewDecData(updatedMakerOwnableSplit)))))) - - if Error != nil { - return nil, Error - } - - order = mappable.NewOrder(&orderID, order.(mappables.Order).GetImmutableProperties(), order.(mappables.Order).GetImmutableProperties().Mutate(mutableProperties.GetList()...)) - orders.Mutate(order) - } - - if auxiliaryResponse := msgServer.transactionKeeper.transferAuxiliary.GetKeeper().Help(ctx, transfer.NewAuxiliaryRequest(&message.FromID, order.(mappables.Order).GetMakerID(), order.(mappables.Order).GetTakerOwnableID(), makerReceiveTakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - if auxiliaryResponse := msgServer.transactionKeeper.transferAuxiliary.GetKeeper().Help(ctx, transfer.NewAuxiliaryRequest(base.NewID(module.Name), &message.FromID, order.(mappables.Order).GetMakerOwnableID(), takerReceiveMakerOwnableSplit)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} - -var _ MsgServer = msgServer{} diff --git a/modules/orders/internal/transactions/take/request.go b/modules/orders/internal/transactions/take/request.go index ad2f8b6a6..25700197a 100644 --- a/modules/orders/internal/transactions/take/request.go +++ b/modules/orders/internal/transactions/take/request.go @@ -1,22 +1,21 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package take import ( "encoding/json" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/orders/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -28,31 +27,31 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary take order transaction -// @Descrption take order transaction +// Validate godoc +// @Summary Take order transaction +// @Description Take order transaction // @Accept text/plain // @Produce json // @Tags Orders -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body transactionRequest true "Request body to take order" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /orders/take [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.TakerOwnableSplit), - cliCommand.ReadString(flags.OrderID), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.TakerOwnableSplit), + cliCommand.ReadString(constants.OrderID), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -61,25 +60,35 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + takerOwnableSplit, err := sdkTypes.NewDecFromStr(transactionRequest.TakerOwnableSplit) + if err != nil { + return nil, err + } + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err } - takerOwnableSplit, Error := sdkTypes.NewDecFromStr(transactionRequest.TakerOwnableSplit) - if Error != nil { - return nil, Error + orderID, err := baseIDs.ReadOrderID(transactionRequest.OrderID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), + fromID, takerOwnableSplit, - base.NewID(transactionRequest.OrderID), + orderID, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/orders/internal/transactions/take/request_test.go b/modules/orders/internal/transactions/take/request_test.go index 61dcf23e2..44b7d8ea2 100644 --- a/modules/orders/internal/transactions/take/request_test.go +++ b/modules/orders/internal/transactions/take/request_test.go @@ -1,75 +1,288 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package take import ( "encoding/json" + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/spf13/viper" "github.com/stretchr/testify/require" - "testing" -) -func Test_Take_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.TakerOwnableSplit, flags.OrderID}) - cliContext := context.NewCLIContext().WithCodec(Codec) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "3", "orderID") +var ( + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = types.AccAddressFromBech32(fromAddress) + immutables = baseQualified.NewImmutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("Data2")))) + mutables = baseQualified.NewMutables(base.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("Data1")))) - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", TakerOwnableSplit: "3", OrderID: "orderID"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) + testClassificationID = baseIDs.NewClassificationID(immutables, mutables) + testFromID = baseIDs.NewIdentityID(testClassificationID, immutables) + testOrderID = baseIDs.NewOrderID(testClassificationID, immutables) + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + takerOwnableSplit = types.NewDec(60) +) - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", TakerOwnableSplit: "", OrderID: ""}, requestFromCLI) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + takerOwnableSplit string + orderID string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, testFromID.String(), takerOwnableSplit.String(), testOrderID.String()}, transactionRequest{testBaseRequest, testFromID.String(), takerOwnableSplit.String(), testOrderID.String()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.takerOwnableSplit, tt.args.orderID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{constants.FromID, constants.TakerOwnableSplit, constants.OrderID}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.FromID.GetName(), testFromID.String()) + viper.Set(constants.TakerOwnableSplit.GetName(), takerOwnableSplit.String()) + viper.Set(constants.OrderID.GetName(), testOrderID.String()) + type fields struct { + BaseReq rest.BaseReq + FromID string + TakerOwnableSplit string + OrderID string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), takerOwnableSplit.String(), testOrderID.String()}, args{cliCommand, cliContext}, transactionRequest{testBaseRequest, testFromID.String(), takerOwnableSplit.String(), testOrderID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + OrderID: tt.fields.OrderID, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromJSON(t *testing.T) { + jsonMessage, err := json.Marshal(newTransactionRequest(testBaseRequest, testFromID.String(), takerOwnableSplit.String(), testOrderID.String())) + require.NoError(t, err) + type fields struct { + BaseReq rest.BaseReq + FromID string + TakerOwnableSplit string + OrderID string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), takerOwnableSplit.String(), testOrderID.String()}, args{jsonMessage}, newTransactionRequest(testBaseRequest, testFromID.String(), takerOwnableSplit.String(), testOrderID.String()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + OrderID: tt.fields.OrderID, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), sdkTypes.NewDec(3), base.NewID("orderID")), msg) - require.Nil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + TakerOwnableSplit string + OrderID string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), takerOwnableSplit.String(), testOrderID.String()}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + OrderID: tt.fields.OrderID, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error := newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", "3", "orderID").MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + TakerOwnableSplit string + OrderID string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), takerOwnableSplit.String(), testOrderID.String()}, newMessage(fromAccAddress, testFromID, takerOwnableSplit, testOrderID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + OrderID: tt.fields.OrderID, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error = newTransactionRequest(testBaseReq, "fromID", "randomString", "orderID").MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + TakerOwnableSplit string + OrderID string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), takerOwnableSplit.String(), testOrderID.String()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + OrderID: tt.fields.OrderID, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + TakerOwnableSplit string + OrderID string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, testFromID.String(), takerOwnableSplit.String(), testOrderID.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + TakerOwnableSplit: tt.fields.TakerOwnableSplit, + OrderID: tt.fields.OrderID, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/orders/internal/transactions/take/response.go b/modules/orders/internal/transactions/take/response.go new file mode 100644 index 000000000..3a7b20779 --- /dev/null +++ b/modules/orders/internal/transactions/take/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package take + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/orders/internal/transactions/take/transaction.go b/modules/orders/internal/transactions/take/transaction.go new file mode 100644 index 000000000..23357860d --- /dev/null +++ b/modules/orders/internal/transactions/take/transaction.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package take + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "take", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + constants.FromID, + constants.TakerOwnableSplit, + constants.OrderID, +) diff --git a/modules/orders/prototype.go b/modules/orders/prototype.go new file mode 100644 index 000000000..9638c4d8a --- /dev/null +++ b/modules/orders/prototype.go @@ -0,0 +1,32 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package orders + +import ( + "github.com/AssetMantle/modules/modules/orders/auxiliaries" + "github.com/AssetMantle/modules/modules/orders/internal/block" + "github.com/AssetMantle/modules/modules/orders/internal/genesis" + "github.com/AssetMantle/modules/modules/orders/internal/mapper" + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/modules/orders/internal/queries" + "github.com/AssetMantle/modules/modules/orders/internal/simulator" + "github.com/AssetMantle/modules/modules/orders/internal/transactions" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Module { + return baseHelpers.NewModule( + module.Name, + auxiliaries.Prototype, + genesis.Prototype, + mapper.Prototype, + parameters.Prototype, + queries.Prototype, + simulator.Prototype, + transactions.Prototype, + block.Prototype, + ) +} diff --git a/modules/orders/prototype_test.go b/modules/orders/prototype_test.go new file mode 100644 index 000000000..d52a94b23 --- /dev/null +++ b/modules/orders/prototype_test.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package orders + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries" + "github.com/AssetMantle/modules/modules/orders/internal/block" + "github.com/AssetMantle/modules/modules/orders/internal/genesis" + "github.com/AssetMantle/modules/modules/orders/internal/mapper" + "github.com/AssetMantle/modules/modules/orders/internal/module" + "github.com/AssetMantle/modules/modules/orders/internal/parameters" + "github.com/AssetMantle/modules/modules/orders/internal/queries" + "github.com/AssetMantle/modules/modules/orders/internal/simulator" + "github.com/AssetMantle/modules/modules/orders/internal/transactions" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Name(), baseHelpers.NewModule( + module.Name, + auxiliaries.Prototype, + genesis.Prototype, + mapper.Prototype, + parameters.Prototype, + queries.Prototype, + simulator.Prototype, + transactions.Prototype, + block.Prototype, + ).Name()) +} diff --git a/modules/splits/auxiliaries/burn/auxiliary.go b/modules/splits/auxiliaries/burn/auxiliary.go new file mode 100644 index 000000000..f5774e197 --- /dev/null +++ b/modules/splits/auxiliaries/burn/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package burn + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "burn", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "burn", + keeperPrototypeMock, +) diff --git a/modules/splits/auxiliaries/burn/keeper.go b/modules/splits/auxiliaries/burn/keeper.go new file mode 100644 index 000000000..69151bd44 --- /dev/null +++ b/modules/splits/auxiliaries/burn/keeper.go @@ -0,0 +1,52 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package burn + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/types" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + splitID := baseIDs.NewSplitID(auxiliaryRequest.OwnerID, auxiliaryRequest.OwnableID) + splits := auxiliaryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(splitID)) + + Mappable := splits.Get(key.NewKey(splitID)) + if Mappable == nil { + return newAuxiliaryResponse(constants.EntityNotFound) + } + split := Mappable.(types.Split) + + switch split = split.Send(auxiliaryRequest.Value); { + case split.GetValue().LT(sdkTypes.ZeroDec()): + return newAuxiliaryResponse(constants.InsufficientBalance) + case split.GetValue().Equal(sdkTypes.ZeroDec()): + splits.Remove(mappable.NewMappable(split)) + default: + splits.Mutate(mappable.NewMappable(split)) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeper{mapper: mapper} +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/splits/auxiliaries/burn/keeper_mock.go b/modules/splits/auxiliaries/burn/keeper_mock.go new file mode 100644 index 000000000..a2c8b1d93 --- /dev/null +++ b/modules/splits/auxiliaries/burn/keeper_mock.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package burn + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(_ sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + if auxiliaryRequest.OwnerID.String() == "burnError" { + return newAuxiliaryResponse(constants.MockError) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/splits/auxiliaries/burn/keeper_test.go b/modules/splits/auxiliaries/burn/keeper_test.go index e5b4ea24a..07224709f 100644 --- a/modules/splits/auxiliaries/burn/keeper_test.go +++ b/modules/splits/auxiliaries/burn/keeper_test.go @@ -1,41 +1,47 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package burn import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" ) type TestKeepers struct { - SplitsKeeper helpers.AuxiliaryKeeper + BurnKeeper helpers.AuxiliaryKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() @@ -56,65 +62,100 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) keepers := TestKeepers{ - SplitsKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.AuxiliaryKeeper), + BurnKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.AuxiliaryKeeper), } - return context, keepers - + return context, keepers, Mapper, Parameters } -func Test_Burn_Aux_Keeper_Help(t *testing.T) { - - context, keepers := CreateTestInput(t) - - ownerID := base.NewID("ownerID") - ownableID := base.NewID("ownableID") - - ownerID2 := base.NewID("ownerID2") - ownableID2 := base.NewID("ownableID2") - - splitID := key.NewSplitID(ownerID, ownableID) - splitID2 := key.NewSplitID(ownerID2, ownableID2) - splits := sdkTypes.NewDec(10) - - keepers.SplitsKeeper.(auxiliaryKeeper).mapper.NewCollection(context).Add(mappable.NewSplit(splitID, splits)).Add(mappable.NewSplit(splitID2, splits)) - - t.Run("PositiveCase- mutate split", func(t *testing.T) { - want := newAuxiliaryResponse(nil) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(ownerID, ownableID, sdkTypes.NewDec(1))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("PositiveCase- remove split", func(t *testing.T) { - want := newAuxiliaryResponse(nil) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(ownerID2, ownableID2, sdkTypes.NewDec(10))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase-Nil Value", func(t *testing.T) { - t.Parallel() - want := newAuxiliaryResponse(errors.EntityNotFound) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(base.NewID("negativeTestOwner"), base.NewID("negativeTestOwnable"), sdkTypes.NewDec(1))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_auxiliaryKeeper_Help(t *testing.T) { + context, keepers, Mapper, _ := createTestInput(t) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testOwnerIdentityID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + testRate := sdkTypes.NewDec(1) + split := baseTypes.NewSplit(testOwnerIdentityID, testOwnableID, testRate) + keepers.BurnKeeper.(auxiliaryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(split)) + type fields struct { + mapper helpers.Mapper + } + type args struct { + context sdkTypes.Context + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + fields fields + args args + want helpers.AuxiliaryResponse + }{ + {"+ve", fields{Mapper}, args{context, NewAuxiliaryRequest(testOwnerIdentityID, testOwnableID, testRate)}, newAuxiliaryResponse(nil)}, + {"+ve Entity Not Found", fields{Mapper}, args{context, NewAuxiliaryRequest(baseIds.PrototypeIdentityID(), testOwnableID, testRate)}, newAuxiliaryResponse(errorConstants.EntityNotFound)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryKeeper := auxiliaryKeeper{ + mapper: tt.fields.mapper, + } + if got := auxiliaryKeeper.Help(tt.args.context, tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Help() = %v, want %v", got, tt.want) + } + }) + } +} - t.Run("NegativeCase-Insufficient Balance", func(t *testing.T) { - t.Parallel() - want := newAuxiliaryResponse(errors.InsufficientBalance) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(ownerID, ownableID, sdkTypes.NewDec(1234))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_auxiliaryKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + in2 []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper}, args{Mapper, Parameters, []interface{}{}}, auxiliaryKeeper{Mapper}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + au := auxiliaryKeeper{ + mapper: tt.fields.mapper, + } + if got := au.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.AuxiliaryKeeper + }{ + {"+ve", auxiliaryKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/auxiliaries/burn/request.go b/modules/splits/auxiliaries/burn/request.go index 931b747c9..0f3e4c23b 100644 --- a/modules/splits/auxiliaries/burn/request.go +++ b/modules/splits/auxiliaries/burn/request.go @@ -1,24 +1,20 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package burn import ( - "fmt" "github.com/asaskevich/govalidator" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" ) type auxiliaryRequest struct { - OwnerID types.ID `json:"ownerID" valid:"required~required field ownerID missing"` - OwnableID types.ID `json:"ownableID" valid:"required~required field ownableID missing"` - Value sdkTypes.Dec `json:"value" valid:"required~required field value missing"` + OwnerID ids.IdentityID `json:"ownerID" valid:"required~required field ownerID missing"` + OwnableID ids.OwnableID `json:"ownableID" valid:"required~required field ownableID missing"` + Value sdkTypes.Dec `json:"value" valid:"required~required field value missing"` } var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) @@ -37,10 +33,10 @@ func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRe } } -func NewAuxiliaryRequest(ownerID fmt.Stringer, ownableID fmt.Stringer, value sdkTypes.Dec) helpers.AuxiliaryRequest { +func NewAuxiliaryRequest(ownerID ids.IdentityID, ownableID ids.OwnableID, value sdkTypes.Dec) helpers.AuxiliaryRequest { return auxiliaryRequest{ - OwnerID: base.NewID(ownerID.String()), - OwnableID: base.NewID(ownableID.String()), + OwnerID: ownerID, + OwnableID: ownableID, Value: value, } } diff --git a/modules/splits/auxiliaries/burn/request_test.go b/modules/splits/auxiliaries/burn/request_test.go index 126515736..dad7c1a47 100644 --- a/modules/splits/auxiliaries/burn/request_test.go +++ b/modules/splits/auxiliaries/burn/request_test.go @@ -1,27 +1,102 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package burn import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" ) -func Test_Burn_Request(t *testing.T) { +func createTestInput1() (ids.IdentityID, ids.OwnableID, types.Dec) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testOwnerID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + testValue := types.NewDec(1) + return testOwnerID, testOwnableID, testValue +} - ownerID := base.NewID("ownerID") - ownableID := base.NewID("ownableID") - splits := sdkTypes.NewDec(10) - testAuxiliaryRequest := NewAuxiliaryRequest(ownerID, ownableID, splits) +func TestNewAuxiliaryRequest(t *testing.T) { + testOwnerID, testOwnableID, testValue := createTestInput1() + type args struct { + ownerID ids.IdentityID + ownableID ids.OwnableID + value types.Dec + } + tests := []struct { + name string + args args + want helpers.AuxiliaryRequest + }{ + {"+ve", args{testOwnerID, testOwnableID, testValue}, NewAuxiliaryRequest(testOwnerID, testOwnableID, testValue)}, + {"+ve with nil", args{baseIds.PrototypeIdentityID(), baseIds.PrototypeOwnableID(), testValue}, NewAuxiliaryRequest(baseIds.PrototypeIdentityID(), baseIds.PrototypeOwnableID(), testValue)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewAuxiliaryRequest(tt.args.ownerID, tt.args.ownableID, tt.args.value); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewAuxiliaryRequest() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, auxiliaryRequest{OwnerID: ownerID, OwnableID: ownableID, Value: splits}, testAuxiliaryRequest) - require.Equal(t, nil, testAuxiliaryRequest.Validate()) - require.Equal(t, testAuxiliaryRequest, auxiliaryRequestFromInterface(testAuxiliaryRequest)) - require.Equal(t, auxiliaryRequest{}, auxiliaryRequestFromInterface(nil)) +func Test_auxiliaryRequestFromInterface(t *testing.T) { + testOwnerID, testOwnableID, testValue := createTestInput1() + type args struct { + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + args args + want auxiliaryRequest + }{ + {"+ve", args{NewAuxiliaryRequest(testOwnerID, testOwnableID, testValue)}, auxiliaryRequest{testOwnerID, testOwnableID, testValue}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := auxiliaryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("auxiliaryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_auxiliaryRequest_Validate(t *testing.T) { + testOwnerID, testOwnableID, testValue := createTestInput1() + type fields struct { + OwnerID ids.IdentityID + OwnableID ids.OwnableID + Value types.Dec + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testOwnerID, testOwnableID, testValue}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryRequest := auxiliaryRequest{ + OwnerID: tt.fields.OwnerID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if err := auxiliaryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/splits/auxiliaries/burn/response.go b/modules/splits/auxiliaries/burn/response.go new file mode 100644 index 000000000..c7f70acb2 --- /dev/null +++ b/modules/splits/auxiliaries/burn/response.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package burn + +import "github.com/AssetMantle/modules/schema/helpers" + +type auxiliaryResponse struct { + Success bool `json:"success"` + Error error `json:"error"` +} + +var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) + +func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { + return auxiliaryResponse.Success +} +func (auxiliaryResponse auxiliaryResponse) GetError() error { + return auxiliaryResponse.Error +} +func newAuxiliaryResponse(error error) helpers.AuxiliaryResponse { + success := true + if error != nil { + success = false + } + + return auxiliaryResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/splits/auxiliaries/burn/response_test.go b/modules/splits/auxiliaries/burn/response_test.go index 52cd0d47b..69702e36c 100644 --- a/modules/splits/auxiliaries/burn/response_test.go +++ b/modules/splits/auxiliaries/burn/response_test.go @@ -4,10 +4,11 @@ package burn import ( - errorConstants "github.com/AssetMantle/modules/schema/errors/constants" - "github.com/AssetMantle/modules/schema/helpers" "reflect" "testing" + + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" ) func Test_auxiliaryResponse_GetError(t *testing.T) { diff --git a/modules/splits/auxiliaries/mint/auxiliary.go b/modules/splits/auxiliaries/mint/auxiliary.go new file mode 100644 index 000000000..a91da9445 --- /dev/null +++ b/modules/splits/auxiliaries/mint/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mint + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "mint", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "mint", + keeperPrototypeMock, +) diff --git a/modules/splits/auxiliaries/mint/keeper.go b/modules/splits/auxiliaries/mint/keeper.go new file mode 100644 index 000000000..11a34ebf3 --- /dev/null +++ b/modules/splits/auxiliaries/mint/keeper.go @@ -0,0 +1,44 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mint + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/types" + "github.com/AssetMantle/modules/schema/types/base" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + splitID := baseIDs.NewSplitID(auxiliaryRequest.OwnerID, auxiliaryRequest.OwnableID) + splits := auxiliaryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(splitID)) + + split := splits.Get(key.NewKey(splitID)) + if split == nil { + splits.Add(mappable.NewMappable(base.NewSplit(auxiliaryRequest.OwnerID, auxiliaryRequest.OwnableID, auxiliaryRequest.Value))) + } else { + splits.Mutate(mappable.NewMappable(split.(types.Split).Receive(auxiliaryRequest.Value))) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeper{mapper: mapper} +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/splits/auxiliaries/mint/keeper_mock.go b/modules/splits/auxiliaries/mint/keeper_mock.go new file mode 100644 index 000000000..a60eb843b --- /dev/null +++ b/modules/splits/auxiliaries/mint/keeper_mock.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mint + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeperMock)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(_ sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + if auxiliaryRequest.OwnerID.String() == "mintError" { + return newAuxiliaryResponse(constants.MockError) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/splits/auxiliaries/mint/keeper_test.go b/modules/splits/auxiliaries/mint/keeper_test.go index 69ef0333f..a0f95f6ac 100644 --- a/modules/splits/auxiliaries/mint/keeper_test.go +++ b/modules/splits/auxiliaries/mint/keeper_test.go @@ -1,11 +1,10 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mint import ( + "fmt" "reflect" "testing" @@ -19,24 +18,29 @@ import ( "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" ) type TestKeepers struct { - SplitsKeeper helpers.AuxiliaryKeeper + MintKeeper helpers.AuxiliaryKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) sdkTypes.RegisterCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() @@ -65,36 +69,91 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { }, false, log.NewNopLogger()) keepers := TestKeepers{ - SplitsKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.AuxiliaryKeeper), + MintKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.AuxiliaryKeeper), } - return context, keepers - + return context, keepers, Mapper, Parameters } -func Test_Burn_Aux_Keeper_Help(t *testing.T) { - context, keepers := CreateTestInput(t) - - ownerID := base.NewID("ownerID") - ownableID := base.NewID("ownableID") - - defaultSplitID := key.NewSplitID(ownerID, ownableID) - splits := sdkTypes.NewDec(123) - - keepers.SplitsKeeper.(auxiliaryKeeper).mapper.NewCollection(context).Add(mappable.NewSplit(defaultSplitID, splits)) - - t.Run("PositiveCase - Mint First Time", func(t *testing.T) { - want := newAuxiliaryResponse(nil) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(ownerID, ownableID, splits)); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_auxiliaryKeeper_Help(t *testing.T) { + context, keepers, Mapper, _ := createTestInput(t) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testOwnerIdentityID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + testRate := sdkTypes.NewDec(1) + split := baseTypes.NewSplit(testOwnerIdentityID, testOwnableID, testRate) + keepers.MintKeeper.(auxiliaryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(split)) + type fields struct { + mapper helpers.Mapper + } + type args struct { + context sdkTypes.Context + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + fields fields + args args + want helpers.AuxiliaryResponse + }{ + {"+ve", fields{Mapper}, args{context, NewAuxiliaryRequest(testOwnerIdentityID, testOwnableID, testRate)}, newAuxiliaryResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryKeeper := auxiliaryKeeper{ + mapper: tt.fields.mapper, + } + if got := auxiliaryKeeper.Help(tt.args.context, tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Help() = %v, want %v", got, tt.want) + } + }) + } +} - t.Run("PositiveCase - Mint 2nd Time", func(t *testing.T) { - want := newAuxiliaryResponse(nil) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(base.NewID("ownerID1"), base.NewID("ownableID1"), sdkTypes.NewDec(12))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_auxiliaryKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + in2 []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper}, args{Mapper, Parameters, []interface{}{}}, auxiliaryKeeper{Mapper}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + au := auxiliaryKeeper{ + mapper: tt.fields.mapper, + } + if got := au.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.AuxiliaryKeeper + }{ + // TODO: Add test cases. + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/auxiliaries/mint/request.go b/modules/splits/auxiliaries/mint/request.go index 9499327c4..3e2530234 100644 --- a/modules/splits/auxiliaries/mint/request.go +++ b/modules/splits/auxiliaries/mint/request.go @@ -1,24 +1,20 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mint import ( - "fmt" "github.com/asaskevich/govalidator" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" ) type auxiliaryRequest struct { - OwnerID types.ID `json:"ownerID" valid:"required~required field ownerID missing"` - OwnableID types.ID `json:"ownableID" valid:"required~required field ownableID missing"` - Value sdkTypes.Dec `json:"value" valid:"required~required field value missing"` + OwnerID ids.IdentityID `json:"ownerID" valid:"required~required field ownerID missing"` + ids.OwnableID `json:"ownableID" valid:"required~required field ownableID missing"` + Value sdkTypes.Dec `json:"value" valid:"required~required field value missing"` } var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) @@ -37,10 +33,10 @@ func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRe } } -func NewAuxiliaryRequest(ownerID fmt.Stringer, ownableID fmt.Stringer, value sdkTypes.Dec) helpers.AuxiliaryRequest { +func NewAuxiliaryRequest(ownerID ids.IdentityID, ownableID ids.OwnableID, value sdkTypes.Dec) helpers.AuxiliaryRequest { return auxiliaryRequest{ - OwnerID: base.NewID(ownerID.String()), - OwnableID: base.NewID(ownableID.String()), + OwnerID: ownerID, + OwnableID: ownableID, Value: value, } } diff --git a/modules/splits/auxiliaries/mint/request_test.go b/modules/splits/auxiliaries/mint/request_test.go index 2f68fdf0c..0bc8a930a 100644 --- a/modules/splits/auxiliaries/mint/request_test.go +++ b/modules/splits/auxiliaries/mint/request_test.go @@ -1,27 +1,102 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package mint import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" ) -func Test_Mint_Request(t *testing.T) { +func createTestInput1() (ids.IdentityID, ids.OwnableID, types.Dec) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testOwnerID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + testValue := types.NewDec(1) + return testOwnerID, testOwnableID, testValue +} - ownerID := base.NewID("ownerID") - ownableID := base.NewID("ownableID") - splits := sdkTypes.NewDec(10) - testAuxiliaryRequest := NewAuxiliaryRequest(ownerID, ownableID, splits) +func TestNewAuxiliaryRequest(t *testing.T) { + testOwnerID, testOwnableID, testValue := createTestInput1() + type args struct { + ownerID ids.IdentityID + ownableID ids.OwnableID + value types.Dec + } + tests := []struct { + name string + args args + want helpers.AuxiliaryRequest + }{ + {"+ve", args{testOwnerID, testOwnableID, testValue}, NewAuxiliaryRequest(testOwnerID, testOwnableID, testValue)}, + {"+ve with nil", args{baseIds.PrototypeIdentityID(), baseIds.PrototypeOwnableID(), testValue}, NewAuxiliaryRequest(baseIds.PrototypeIdentityID(), baseIds.PrototypeOwnableID(), testValue)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewAuxiliaryRequest(tt.args.ownerID, tt.args.ownableID, tt.args.value); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewAuxiliaryRequest() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, auxiliaryRequest{OwnerID: ownerID, OwnableID: ownableID, Value: splits}, testAuxiliaryRequest) - require.Equal(t, nil, testAuxiliaryRequest.Validate()) - require.Equal(t, testAuxiliaryRequest, auxiliaryRequestFromInterface(testAuxiliaryRequest)) - require.Equal(t, auxiliaryRequest{}, auxiliaryRequestFromInterface(nil)) +func Test_auxiliaryRequestFromInterface(t *testing.T) { + testOwnerID, testOwnableID, testValue := createTestInput1() + type args struct { + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + args args + want auxiliaryRequest + }{ + {"+ve", args{NewAuxiliaryRequest(testOwnerID, testOwnableID, testValue)}, auxiliaryRequest{testOwnerID, testOwnableID, testValue}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := auxiliaryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("auxiliaryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_auxiliaryRequest_Validate(t *testing.T) { + testOwnerID, testOwnableID, testValue := createTestInput1() + type fields struct { + OwnerID ids.IdentityID + OwnableID ids.OwnableID + Value types.Dec + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testOwnerID, testOwnableID, testValue}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryRequest := auxiliaryRequest{ + OwnerID: tt.fields.OwnerID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if err := auxiliaryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/splits/auxiliaries/mint/response.go b/modules/splits/auxiliaries/mint/response.go new file mode 100644 index 000000000..2c1f33b8e --- /dev/null +++ b/modules/splits/auxiliaries/mint/response.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mint + +import "github.com/AssetMantle/modules/schema/helpers" + +type auxiliaryResponse struct { + Success bool `json:"success"` + Error error `json:"error"` +} + +var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) + +func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { + return auxiliaryResponse.Success +} +func (auxiliaryResponse auxiliaryResponse) GetError() error { + return auxiliaryResponse.Error +} +func newAuxiliaryResponse(error error) helpers.AuxiliaryResponse { + success := true + if error != nil { + success = false + } + + return auxiliaryResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/splits/auxiliaries/mint/response_test.go b/modules/splits/auxiliaries/mint/response_test.go new file mode 100644 index 000000000..ccd268d0f --- /dev/null +++ b/modules/splits/auxiliaries/mint/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mint + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Mint_Response(t *testing.T) { + testAuxiliaryResponse := newAuxiliaryResponse(nil) + require.Equal(t, auxiliaryResponse{Success: true, Error: nil}, testAuxiliaryResponse) + require.Equal(t, true, testAuxiliaryResponse.IsSuccessful()) + require.Equal(t, nil, testAuxiliaryResponse.GetError()) + + testAuxiliaryResponse2 := newAuxiliaryResponse(constants.IncorrectFormat) + require.Equal(t, auxiliaryResponse{Success: false, Error: constants.IncorrectFormat}, testAuxiliaryResponse2) + require.Equal(t, false, testAuxiliaryResponse2.IsSuccessful()) + require.Equal(t, constants.IncorrectFormat, testAuxiliaryResponse2.GetError()) +} diff --git a/modules/splits/auxiliaries/prototype.go b/modules/splits/auxiliaries/prototype.go new file mode 100644 index 000000000..5bee895e8 --- /dev/null +++ b/modules/splits/auxiliaries/prototype.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "github.com/AssetMantle/modules/modules/splits/auxiliaries/burn" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/mint" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/renumerate" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Auxiliaries { + return baseHelpers.NewAuxiliaries( + burn.Auxiliary, + mint.Auxiliary, + renumerate.Auxiliary, + transfer.Auxiliary, + ) +} diff --git a/modules/splits/auxiliaries/prototype_test.go b/modules/splits/auxiliaries/prototype_test.go new file mode 100644 index 000000000..c834d3df7 --- /dev/null +++ b/modules/splits/auxiliaries/prototype_test.go @@ -0,0 +1,25 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package auxiliaries + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/splits/auxiliaries/burn" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/mint" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/renumerate" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Get("transfer").GetName(), baseHelpers.NewAuxiliaries( + burn.Auxiliary, + mint.Auxiliary, + renumerate.Auxiliary, + transfer.Auxiliary, + ).Get("transfer").GetName()) +} diff --git a/modules/splits/auxiliaries/renumerate/auxiliary.go b/modules/splits/auxiliaries/renumerate/auxiliary.go new file mode 100644 index 000000000..83ff81fc1 --- /dev/null +++ b/modules/splits/auxiliaries/renumerate/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package renumerate + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "renumerate", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "renumerate", + keeperPrototypeMock, +) diff --git a/modules/splits/auxiliaries/renumerate/keeper.go b/modules/splits/auxiliaries/renumerate/keeper.go new file mode 100644 index 000000000..34ef7ea4e --- /dev/null +++ b/modules/splits/auxiliaries/renumerate/keeper.go @@ -0,0 +1,48 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package renumerate + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/splits/internal/utilities" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + splits := auxiliaryKeeper.mapper.NewCollection(context) + + switch totalSplitsValue := utilities.GetOwnableTotalSplitsValue(splits, auxiliaryRequest.OwnableID); { + case totalSplitsValue.LT(auxiliaryRequest.Value): + if _, err := utilities.AddSplits(splits, auxiliaryRequest.OwnerID, auxiliaryRequest.OwnableID, auxiliaryRequest.Value.Sub(totalSplitsValue)); err != nil { + return newAuxiliaryResponse(err) + } + case totalSplitsValue.GT(auxiliaryRequest.Value): + if _, err := utilities.SubtractSplits(splits, auxiliaryRequest.OwnerID, auxiliaryRequest.OwnableID, totalSplitsValue.Sub(auxiliaryRequest.Value)); err != nil { + return newAuxiliaryResponse(err) + } + case totalSplitsValue.IsZero(): + return newAuxiliaryResponse(constants.EntityNotFound) + default: + return newAuxiliaryResponse(nil) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeper{mapper: mapper} +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/splits/auxiliaries/renumerate/keeper_mock.go b/modules/splits/auxiliaries/renumerate/keeper_mock.go new file mode 100644 index 000000000..68e1339c7 --- /dev/null +++ b/modules/splits/auxiliaries/renumerate/keeper_mock.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package renumerate + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(_ sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + if auxiliaryRequest.OwnerID.String() == "burnError" { + return newAuxiliaryResponse(constants.MockError) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/splits/auxiliaries/renumerate/keeper_test.go b/modules/splits/auxiliaries/renumerate/keeper_test.go index 5fbbcfcdc..2010ab596 100644 --- a/modules/splits/auxiliaries/renumerate/keeper_test.go +++ b/modules/splits/auxiliaries/renumerate/keeper_test.go @@ -1,41 +1,46 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package renumerate import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" ) type TestKeepers struct { - SplitsKeeper helpers.AuxiliaryKeeper + RenumerateKeeper helpers.AuxiliaryKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() @@ -56,65 +61,99 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) keepers := TestKeepers{ - SplitsKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.AuxiliaryKeeper), + RenumerateKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.AuxiliaryKeeper), } - return context, keepers - + return context, keepers, Mapper, Parameters } -func Test_Burn_Aux_Keeper_Help(t *testing.T) { - - context, keepers := CreateTestInput(t) - - ownerID := base.NewID("ownerID") - ownableID := base.NewID("ownableID") - - ownerID2 := base.NewID("ownerID2") - ownableID2 := base.NewID("ownableID2") - - splitID := key.NewSplitID(ownerID, ownableID) - splitID2 := key.NewSplitID(ownerID2, ownableID2) - splits := sdkTypes.NewDec(10) - - keepers.SplitsKeeper.(auxiliaryKeeper).mapper.NewCollection(context).Add(mappable.NewSplit(splitID, splits)).Add(mappable.NewSplit(splitID2, splits)) - - t.Run("PositiveCase- mutate split", func(t *testing.T) { - want := newAuxiliaryResponse(nil) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(ownerID, ownableID, sdkTypes.NewDec(1))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("PositiveCase- remove split", func(t *testing.T) { - want := newAuxiliaryResponse(nil) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(ownerID2, ownableID2, sdkTypes.NewDec(10))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase-Nil Value", func(t *testing.T) { - t.Parallel() - want := newAuxiliaryResponse(errors.EntityNotFound) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(base.NewID("negativeTestOwner"), base.NewID("negativeTestOwnable"), sdkTypes.NewDec(-1))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_auxiliaryKeeper_Help(t *testing.T) { + context, keepers, Mapper, _ := createTestInput(t) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testOwnerIdentityID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + testRate := sdkTypes.NewDec(1) + split := baseTypes.NewSplit(testOwnerIdentityID, testOwnableID, testRate) + keepers.RenumerateKeeper.(auxiliaryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(split)) + type fields struct { + mapper helpers.Mapper + } + type args struct { + context sdkTypes.Context + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + fields fields + args args + want helpers.AuxiliaryResponse + }{ + {"+ve", fields{Mapper}, args{context, NewAuxiliaryRequest(testOwnerIdentityID, testOwnableID, testRate)}, newAuxiliaryResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryKeeper := auxiliaryKeeper{ + mapper: tt.fields.mapper, + } + if got := auxiliaryKeeper.Help(tt.args.context, tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Help() = %v, want %v", got, tt.want) + } + }) + } +} - t.Run("NegativeCase-Insufficient Balance", func(t *testing.T) { - t.Parallel() - want := newAuxiliaryResponse(errors.InsufficientBalance) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(ownerID, ownableID, sdkTypes.NewDec(1234))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_auxiliaryKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + in2 []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper}, args{Mapper, Parameters, []interface{}{}}, auxiliaryKeeper{Mapper}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + au := auxiliaryKeeper{ + mapper: tt.fields.mapper, + } + if got := au.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.AuxiliaryKeeper + }{ + {"+ve", auxiliaryKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/auxiliaries/renumerate/request.go b/modules/splits/auxiliaries/renumerate/request.go index 7da65e66c..176f4b3dd 100644 --- a/modules/splits/auxiliaries/renumerate/request.go +++ b/modules/splits/auxiliaries/renumerate/request.go @@ -1,24 +1,20 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package renumerate import ( - "fmt" "github.com/asaskevich/govalidator" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" ) type auxiliaryRequest struct { - OwnerID types.ID `json:"ownerID" valid:"required~required field ownerID missing"` - OwnableID types.ID `json:"ownableID" valid:"required~required field ownableID missing"` - Value sdkTypes.Dec `json:"value" valid:"required~required field value missing"` + OwnerID ids.IdentityID `json:"ownerID" valid:"required~required field ownerID missing"` + ids.OwnableID `json:"ownableID" valid:"required~required field ownableID missing"` + Value sdkTypes.Dec `json:"value" valid:"required~required field value missing"` } var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) @@ -37,10 +33,10 @@ func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRe } } -func NewAuxiliaryRequest(ownerID fmt.Stringer, ownableID fmt.Stringer, value sdkTypes.Dec) helpers.AuxiliaryRequest { +func NewAuxiliaryRequest(ownerID ids.IdentityID, ownableID ids.OwnableID, value sdkTypes.Dec) helpers.AuxiliaryRequest { return auxiliaryRequest{ - OwnerID: base.NewID(ownerID.String()), - OwnableID: base.NewID(ownableID.String()), + OwnerID: ownerID, + OwnableID: ownableID, Value: value, } } diff --git a/modules/splits/auxiliaries/renumerate/request_test.go b/modules/splits/auxiliaries/renumerate/request_test.go index 1b8be77c0..27b0d6de5 100644 --- a/modules/splits/auxiliaries/renumerate/request_test.go +++ b/modules/splits/auxiliaries/renumerate/request_test.go @@ -1,27 +1,102 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package renumerate import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" ) -func Test_Burn_Request(t *testing.T) { +func createTestInput1() (ids.IdentityID, ids.OwnableID, types.Dec) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testOwnerID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + testValue := types.NewDec(1) + return testOwnerID, testOwnableID, testValue +} - ownerID := base.NewID("ownerID") - ownableID := base.NewID("ownableID") - testValue := sdkTypes.NewDec(10) - testAuxiliaryRequest := NewAuxiliaryRequest(ownerID, ownableID, testValue) +func TestNewAuxiliaryRequest(t *testing.T) { + testOwnerID, testOwnableID, testValue := createTestInput1() + type args struct { + ownerID ids.IdentityID + ownableID ids.OwnableID + value types.Dec + } + tests := []struct { + name string + args args + want helpers.AuxiliaryRequest + }{ + {"+ve", args{testOwnerID, testOwnableID, testValue}, NewAuxiliaryRequest(testOwnerID, testOwnableID, testValue)}, + {"+ve with nil", args{baseIds.PrototypeIdentityID(), baseIds.PrototypeOwnableID(), testValue}, NewAuxiliaryRequest(baseIds.PrototypeIdentityID(), baseIds.PrototypeOwnableID(), testValue)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewAuxiliaryRequest(tt.args.ownerID, tt.args.ownableID, tt.args.value); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewAuxiliaryRequest() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, auxiliaryRequest{OwnerID: ownerID, OwnableID: ownableID, Value: testValue}, testAuxiliaryRequest) - require.Equal(t, nil, testAuxiliaryRequest.Validate()) - require.Equal(t, testAuxiliaryRequest, auxiliaryRequestFromInterface(testAuxiliaryRequest)) - require.Equal(t, auxiliaryRequest{}, auxiliaryRequestFromInterface(nil)) +func Test_auxiliaryRequestFromInterface(t *testing.T) { + testOwnerID, testOwnableID, testValue := createTestInput1() + type args struct { + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + args args + want auxiliaryRequest + }{ + {"+ve", args{NewAuxiliaryRequest(testOwnerID, testOwnableID, testValue)}, auxiliaryRequest{testOwnerID, testOwnableID, testValue}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := auxiliaryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("auxiliaryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_auxiliaryRequest_Validate(t *testing.T) { + testOwnerID, testOwnableID, testValue := createTestInput1() + type fields struct { + OwnerID ids.IdentityID + OwnableID ids.OwnableID + Value types.Dec + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testOwnerID, testOwnableID, testValue}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryRequest := auxiliaryRequest{ + OwnerID: tt.fields.OwnerID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if err := auxiliaryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/splits/auxiliaries/renumerate/response.go b/modules/splits/auxiliaries/renumerate/response.go new file mode 100644 index 000000000..8f8c2b3a2 --- /dev/null +++ b/modules/splits/auxiliaries/renumerate/response.go @@ -0,0 +1,31 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package renumerate + +import "github.com/AssetMantle/modules/schema/helpers" + +type auxiliaryResponse struct { + Success bool `json:"success"` + Error error `json:"error"` +} + +var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) + +func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { + return auxiliaryResponse.Success +} +func (auxiliaryResponse auxiliaryResponse) GetError() error { + return auxiliaryResponse.Error +} +func newAuxiliaryResponse(error error) helpers.AuxiliaryResponse { + success := true + if error != nil { + success = false + } + + return auxiliaryResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/splits/auxiliaries/renumerate/response_test.go b/modules/splits/auxiliaries/renumerate/response_test.go index 772450704..44bed58ce 100644 --- a/modules/splits/auxiliaries/renumerate/response_test.go +++ b/modules/splits/auxiliaries/renumerate/response_test.go @@ -1,25 +1,24 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package renumerate import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/stretchr/testify/require" "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" ) func Test_Burn_Response(t *testing.T) { - testAuxiliaryResponse := newAuxiliaryResponse(nil) require.Equal(t, auxiliaryResponse{Success: true, Error: nil}, testAuxiliaryResponse) require.Equal(t, true, testAuxiliaryResponse.IsSuccessful()) require.Equal(t, nil, testAuxiliaryResponse.GetError()) - testAuxiliaryResponse2 := newAuxiliaryResponse(errors.IncorrectFormat) - require.Equal(t, auxiliaryResponse{Success: false, Error: errors.IncorrectFormat}, testAuxiliaryResponse2) + testAuxiliaryResponse2 := newAuxiliaryResponse(constants.IncorrectFormat) + require.Equal(t, auxiliaryResponse{Success: false, Error: constants.IncorrectFormat}, testAuxiliaryResponse2) require.Equal(t, false, testAuxiliaryResponse2.IsSuccessful()) - require.Equal(t, errors.IncorrectFormat, testAuxiliaryResponse2.GetError()) + require.Equal(t, constants.IncorrectFormat, testAuxiliaryResponse2.GetError()) } diff --git a/modules/splits/auxiliaries/transfer/auxiliary.go b/modules/splits/auxiliaries/transfer/auxiliary.go new file mode 100644 index 000000000..bb1299534 --- /dev/null +++ b/modules/splits/auxiliaries/transfer/auxiliary.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transfer + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +var Auxiliary = baseHelpers.NewAuxiliary( + "transfer", + keeperPrototype, +) + +var AuxiliaryMock = baseHelpers.NewAuxiliary( + "transfer", + keeperPrototypeMock, +) diff --git a/modules/splits/auxiliaries/transfer/keeper.go b/modules/splits/auxiliaries/transfer/keeper.go new file mode 100644 index 000000000..8955dfee1 --- /dev/null +++ b/modules/splits/auxiliaries/transfer/keeper.go @@ -0,0 +1,65 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transfer + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/types" + "github.com/AssetMantle/modules/schema/types/base" +) + +type auxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeper)(nil) + +func (auxiliaryKeeper auxiliaryKeeper) Help(context sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + if auxiliaryRequest.Value.LTE(sdkTypes.ZeroDec()) { + return newAuxiliaryResponse(constants.NotAuthorized) + } + + splits := auxiliaryKeeper.mapper.NewCollection(context) + + fromSplitID := baseIDs.NewSplitID(auxiliaryRequest.FromID, auxiliaryRequest.OwnableID) + Mappable := splits.Fetch(key.NewKey(fromSplitID)).Get(key.NewKey(fromSplitID)) + if Mappable == nil { + return newAuxiliaryResponse(constants.EntityNotFound) + } + fromSplit := Mappable.(types.Split) + + switch fromSplit = fromSplit.(types.Split).Send(auxiliaryRequest.Value); { + case fromSplit.(types.Split).GetValue().LT(sdkTypes.ZeroDec()): + return newAuxiliaryResponse(constants.NotAuthorized) + case fromSplit.(types.Split).GetValue().Equal(sdkTypes.ZeroDec()): + splits.Remove(mappable.NewMappable(fromSplit)) + default: + splits.Mutate(mappable.NewMappable(fromSplit)) + } + + toSplitID := baseIDs.NewSplitID(auxiliaryRequest.ToID, auxiliaryRequest.OwnableID) + + if toSplit, ok := splits.Fetch(key.NewKey(toSplitID)).Get(key.NewKey(toSplitID)).(types.Split); !ok { + splits.Add(mappable.NewMappable(base.NewSplit(auxiliaryRequest.ToID, auxiliaryRequest.OwnableID, auxiliaryRequest.Value))) + } else { + splits.Mutate(mappable.NewMappable(toSplit.Receive(auxiliaryRequest.Value))) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeper{mapper: mapper} +} + +func keeperPrototype() helpers.AuxiliaryKeeper { + return auxiliaryKeeper{} +} diff --git a/modules/splits/auxiliaries/transfer/keeper_mock.go b/modules/splits/auxiliaries/transfer/keeper_mock.go new file mode 100644 index 000000000..3dd525117 --- /dev/null +++ b/modules/splits/auxiliaries/transfer/keeper_mock.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transfer + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type auxiliaryKeeperMock struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*auxiliaryKeeperMock)(nil) + +func (auxiliaryKeeper auxiliaryKeeperMock) Help(_ sdkTypes.Context, request helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + auxiliaryRequest := auxiliaryRequestFromInterface(request) + if auxiliaryRequest.OwnableID.String() == "transferError" { + return newAuxiliaryResponse(constants.MockError) + } + + return newAuxiliaryResponse(nil) +} + +func (auxiliaryKeeperMock) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return auxiliaryKeeperMock{mapper: mapper} +} +func keeperPrototypeMock() helpers.AuxiliaryKeeper { + return auxiliaryKeeperMock{} +} diff --git a/modules/splits/auxiliaries/transfer/keeper_test.go b/modules/splits/auxiliaries/transfer/keeper_test.go index 64d660089..fbbaed84a 100644 --- a/modules/splits/auxiliaries/transfer/keeper_test.go +++ b/modules/splits/auxiliaries/transfer/keeper_test.go @@ -1,41 +1,47 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package transfer import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" ) type TestKeepers struct { - SplitsKeeper helpers.AuxiliaryKeeper + TransferKeeper helpers.AuxiliaryKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() @@ -56,73 +62,102 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) keepers := TestKeepers{ - SplitsKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.AuxiliaryKeeper), + TransferKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.AuxiliaryKeeper), } - return context, keepers - + return context, keepers, Mapper, Parameters } -func Test_Transfer_Aux_Keeper_Help(t *testing.T) { - - context, keepers := CreateTestInput(t) - ownerID := base.NewID("ownerID") - ownableID := base.NewID("ownableID") - - toID := base.NewID("toID") - defaultSplitID := key.NewSplitID(ownerID, ownableID) - splits := sdkTypes.NewDec(123) - keepers.SplitsKeeper.(auxiliaryKeeper).mapper.NewCollection(context).Add(mappable.NewSplit(defaultSplitID, splits)) - - t.Run("Positive case- Value transfer", func(t *testing.T) { - want := newAuxiliaryResponse(nil) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(ownerID, toID, ownableID, sdkTypes.NewDec(1))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("Positive case- Value transfer", func(t *testing.T) { - want := newAuxiliaryResponse(nil) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(ownerID, toID, ownableID, sdkTypes.NewDec(1))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("Positive case- Value transfer", func(t *testing.T) { - want := newAuxiliaryResponse(nil) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(toID, ownerID, ownableID, sdkTypes.NewDec(2))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase-0 Value transfer", func(t *testing.T) { - want := newAuxiliaryResponse(errors.NotAuthorized) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(ownerID, toID, ownableID, sdkTypes.NewDec(0))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_auxiliaryKeeper_Help(t *testing.T) { + context, keepers, Mapper, _ := createTestInput(t) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testOwnerIdentityID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + testRate := sdkTypes.NewDec(1) + split := baseTypes.NewSplit(testOwnerIdentityID, testOwnableID, testRate) + keepers.TransferKeeper.(auxiliaryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(split)) + + type fields struct { + mapper helpers.Mapper + } + type args struct { + context sdkTypes.Context + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + fields fields + args args + want helpers.AuxiliaryResponse + }{ + {"+ve", fields{Mapper}, args{context, NewAuxiliaryRequest(testOwnerIdentityID, testOwnerIdentityID, testOwnableID, testRate)}, newAuxiliaryResponse(nil)}, + {"+ve Not Authorized", fields{Mapper}, args{context, NewAuxiliaryRequest(testOwnerIdentityID, testOwnerIdentityID, testOwnableID, sdkTypes.ZeroDec())}, newAuxiliaryResponse(errorConstants.NotAuthorized)}, + {"+ve Entity Not Found", fields{Mapper}, args{context, NewAuxiliaryRequest(testOwnerIdentityID, testOwnerIdentityID, baseIds.NewOwnableID(baseIds.NewStringID("test")), testRate)}, newAuxiliaryResponse(errorConstants.EntityNotFound)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryKeeper := auxiliaryKeeper{ + mapper: tt.fields.mapper, + } + if got := auxiliaryKeeper.Help(tt.args.context, tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Help() = %v, want %v", got, tt.want) + } + }) + } +} - t.Run("NegativeCase-No Value Present", func(t *testing.T) { - t.Parallel() - want := newAuxiliaryResponse(errors.EntityNotFound) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(ownerID, toID, base.NewID("ownableIDNotPresent"), sdkTypes.NewDec(1))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_auxiliaryKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + in2 []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper}, args{Mapper, Parameters, []interface{}{}}, auxiliaryKeeper{Mapper}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + au := auxiliaryKeeper{ + mapper: tt.fields.mapper, + } + if got := au.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} - t.Run("NegativeCase-Transfer More than available splits", func(t *testing.T) { - t.Parallel() - want := newAuxiliaryResponse(errors.NotAuthorized) - if got := keepers.SplitsKeeper.Help(context, NewAuxiliaryRequest(ownerID, toID, ownableID, sdkTypes.NewDec(1234))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.AuxiliaryKeeper + }{ + {"+ve", auxiliaryKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/auxiliaries/transfer/request.go b/modules/splits/auxiliaries/transfer/request.go new file mode 100644 index 000000000..f045def40 --- /dev/null +++ b/modules/splits/auxiliaries/transfer/request.go @@ -0,0 +1,44 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transfer + +import ( + "github.com/asaskevich/govalidator" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" +) + +type auxiliaryRequest struct { + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ToID ids.IdentityID `json:"toID" valid:"required~required field toID missing"` + OwnableID ids.OwnableID `json:"ownableID" valid:"required~required field ownableID missing"` + Value sdkTypes.Dec `json:"value" valid:"required~required field value missing"` +} + +var _ helpers.AuxiliaryRequest = (*auxiliaryRequest)(nil) + +func (auxiliaryRequest auxiliaryRequest) Validate() error { + _, err := govalidator.ValidateStruct(auxiliaryRequest) + return err +} + +func auxiliaryRequestFromInterface(request helpers.AuxiliaryRequest) auxiliaryRequest { + switch value := request.(type) { + case auxiliaryRequest: + return value + default: + return auxiliaryRequest{} + } +} + +func NewAuxiliaryRequest(fromID ids.IdentityID, toID ids.IdentityID, ownableID ids.OwnableID, value sdkTypes.Dec) helpers.AuxiliaryRequest { + return auxiliaryRequest{ + FromID: fromID, + ToID: toID, + OwnableID: ownableID, + Value: value, + } +} diff --git a/modules/splits/auxiliaries/transfer/request_test.go b/modules/splits/auxiliaries/transfer/request_test.go index b46b54419..90da4a800 100644 --- a/modules/splits/auxiliaries/transfer/request_test.go +++ b/modules/splits/auxiliaries/transfer/request_test.go @@ -1,27 +1,105 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package transfer import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" ) -func Test_Transfer_Request(t *testing.T) { - fromID := base.NewID("fromID") - toID := base.NewID("toID") - ownableID := base.NewID("ownableID") - splits := sdkTypes.NewDec(10) - testAuxiliaryRequest := NewAuxiliaryRequest(fromID, toID, ownableID, splits) +func createTestInput1() (ids.IdentityID, ids.OwnableID, types.Dec) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testOwnerID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + testValue := types.NewDec(1) + return testOwnerID, testOwnableID, testValue +} + +func TestNewAuxiliaryRequest(t *testing.T) { + testOwnerID, testOwnableID, testValue := createTestInput1() + type args struct { + fromID ids.IdentityID + toID ids.IdentityID + ownableID ids.OwnableID + value types.Dec + } + tests := []struct { + name string + args args + want helpers.AuxiliaryRequest + }{ + {"+ve", args{testOwnerID, testOwnerID, testOwnableID, testValue}, NewAuxiliaryRequest(testOwnerID, testOwnerID, testOwnableID, testValue)}, + {"+ve with nil", args{testOwnerID, baseIds.PrototypeIdentityID(), baseIds.PrototypeOwnableID(), testValue}, NewAuxiliaryRequest(testOwnerID, baseIds.PrototypeIdentityID(), baseIds.PrototypeOwnableID(), testValue)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewAuxiliaryRequest(tt.args.fromID, tt.args.toID, tt.args.ownableID, tt.args.value); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewAuxiliaryRequest() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, auxiliaryRequest{FromID: fromID, ToID: toID, OwnableID: ownableID, Value: splits}, testAuxiliaryRequest) - require.Equal(t, nil, testAuxiliaryRequest.Validate()) - require.Equal(t, testAuxiliaryRequest, auxiliaryRequestFromInterface(testAuxiliaryRequest)) - require.Equal(t, auxiliaryRequest{}, auxiliaryRequestFromInterface(nil)) +func Test_auxiliaryRequestFromInterface(t *testing.T) { + testOwnerID, testOwnableID, testValue := createTestInput1() + type args struct { + request helpers.AuxiliaryRequest + } + tests := []struct { + name string + args args + want auxiliaryRequest + }{ + {"+ve", args{NewAuxiliaryRequest(testOwnerID, testOwnerID, testOwnableID, testValue)}, auxiliaryRequest{testOwnerID, testOwnerID, testOwnableID, testValue}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := auxiliaryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("auxiliaryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_auxiliaryRequest_Validate(t *testing.T) { + testOwnerID, testOwnableID, testValue := createTestInput1() + type fields struct { + FromID ids.IdentityID + ToID ids.IdentityID + OwnableID ids.OwnableID + Value types.Dec + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testOwnerID, testOwnerID, testOwnableID, testValue}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliaryRequest := auxiliaryRequest{ + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if err := auxiliaryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/splits/auxiliaries/transfer/response.go b/modules/splits/auxiliaries/transfer/response.go new file mode 100644 index 000000000..ee7bacf3a --- /dev/null +++ b/modules/splits/auxiliaries/transfer/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transfer + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type auxiliaryResponse struct { + Success bool `json:"success"` + Error error `json:"error"` +} + +var _ helpers.AuxiliaryResponse = (*auxiliaryResponse)(nil) + +func (auxiliaryResponse auxiliaryResponse) IsSuccessful() bool { + return auxiliaryResponse.Success +} +func (auxiliaryResponse auxiliaryResponse) GetError() error { + return auxiliaryResponse.Error +} +func newAuxiliaryResponse(error error) helpers.AuxiliaryResponse { + success := true + if error != nil { + success = false + } + + return auxiliaryResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/splits/auxiliaries/transfer/response_test.go b/modules/splits/auxiliaries/transfer/response_test.go new file mode 100644 index 000000000..5ee0d2bdd --- /dev/null +++ b/modules/splits/auxiliaries/transfer/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transfer + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Transfer_Response(t *testing.T) { + testAuxiliaryResponse := newAuxiliaryResponse(nil) + require.Equal(t, auxiliaryResponse{Success: true, Error: nil}, testAuxiliaryResponse) + require.Equal(t, true, testAuxiliaryResponse.IsSuccessful()) + require.Equal(t, nil, testAuxiliaryResponse.GetError()) + + testAuxiliaryResponse2 := newAuxiliaryResponse(constants.IncorrectFormat) + require.Equal(t, auxiliaryResponse{Success: false, Error: constants.IncorrectFormat}, testAuxiliaryResponse2) + require.Equal(t, false, testAuxiliaryResponse2.IsSuccessful()) + require.Equal(t, constants.IncorrectFormat, testAuxiliaryResponse2.GetError()) +} diff --git a/modules/splits/doc.go b/modules/splits/doc.go new file mode 100644 index 000000000..8551103af --- /dev/null +++ b/modules/splits/doc.go @@ -0,0 +1,5 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +// Package splits defines the splits' module. +package splits diff --git a/modules/splits/internal/block/block.go b/modules/splits/internal/block/block.go new file mode 100644 index 000000000..2b406cdb0 --- /dev/null +++ b/modules/splits/internal/block/block.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package block + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + abciTypes "github.com/tendermint/tendermint/abci/types" + + "github.com/AssetMantle/modules/schema/helpers" +) + +type block struct { + mapper helpers.Mapper + parameters helpers.Parameters +} + +var _ helpers.Block = (*block)(nil) + +func (block block) Begin(_ sdkTypes.Context, _ abciTypes.RequestBeginBlock) { + +} + +func (block block) End(_ sdkTypes.Context, _ abciTypes.RequestEndBlock) { + +} + +func Prototype() helpers.Block { + return block{} +} + +func (block block) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, _ ...interface{}) helpers.Block { + block.mapper, block.parameters = mapper, parameters + return block +} diff --git a/modules/splits/internal/block/block_test.go b/modules/splits/internal/block/block_test.go new file mode 100644 index 000000000..2cfa9919a --- /dev/null +++ b/modules/splits/internal/block/block_test.go @@ -0,0 +1,57 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package block + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/splits/internal/mapper" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" +) + +func CreateTestInput(t *testing.T) sdkTypes.Context { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + return context +} + +func Test_Block_Methods(t *testing.T) { + block := Prototype() + block.Initialize(mapper.Prototype(), parameters.Prototype(), []helpers.Auxiliary{}) + context := CreateTestInput(t) + block.Begin(context, abciTypes.RequestBeginBlock{}) + block.End(context, abciTypes.RequestEndBlock{}) +} diff --git a/modules/splits/internal/common/codec.go b/modules/splits/internal/common/codec.go new file mode 100644 index 000000000..4bd306d4f --- /dev/null +++ b/modules/splits/internal/common/codec.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package common + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/utilities/module" +) + +var Codec *codec.Codec + +func init() { + Codec = module.RegisterCodec(key.Prototype, mappable.Prototype) +} diff --git a/modules/splits/internal/genesis/genesis.go b/modules/splits/internal/genesis/genesis.go deleted file mode 100644 index 14edb9638..000000000 --- a/modules/splits/internal/genesis/genesis.go +++ /dev/null @@ -1,188 +0,0 @@ -package genesis - -import ( - "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ helpers.Genesis = (*Genesis)(nil) - -func (genesis Genesis) Default() helpers.Genesis { - return genesis.Initialize(genesis.GetMappableList(), genesis.GetParameterList()) -} - -func (genesis Genesis) Validate() error { - if len(genesis.ParameterList) != len(genesis.DefaultParameterList) { - return errors.InvalidParameter - } - - for _, parameter := range genesis.ParameterList { - var isPresent bool - for _, defaultParameter := range genesis.DefaultParameterList { - isPresent = false - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - isPresent = true - break - } - } - - if !isPresent { - return errors.InvalidParameter - } - - if Error := parameter.Validate(); Error != nil { - return Error - } - } - - _, Error := govalidator.ValidateStruct(genesis) - - return Error -} - -func (genesis Genesis) Import(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) { - for _, mappableValue := range genesis.MappableList { - mapper.Create(context, &mappableValue) - } - - for _, parameter := range genesis.ParameterList { - parameters.Mutate(context, ¶meter) - } -} - -func (genesis Genesis) Export(context sdkTypes.Context, mapper helpers.Mapper, parameters helpers.Parameters) helpers.Genesis { - var mappableList []helpers.Mappable - - appendMappableList := func(mappable helpers.Mappable) bool { - mappableList = append(mappableList, mappable) - return false - } - mapper.Iterate(context, key.Prototype(), appendMappableList) - - for _, defaultParameter := range genesis.DefaultParameterList { - parameters = parameters.Fetch(context, defaultParameter.GetID()) - } - - return genesis.Initialize(mappableList, parameters.GetList()) -} - -func (genesis Genesis) LegacyAminoEncode() []byte { - legacyAminoCodec := codec.NewLegacyAmino() - bytes, Error := legacyAminoCodec.MarshalJSON(genesis) - if Error != nil { - panic(Error) - } - - return bytes -} -func (genesis Genesis) LegacyAminoDecode(byte []byte) helpers.Genesis { - var newGenesis Genesis - legacyAminoCodec := codec.NewLegacyAmino() - if Error := legacyAminoCodec.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(genesis.DefaultMappableList, genesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Encode(cdc codec.JSONMarshaler) []byte { - bytes, Error := cdc.MarshalJSON(&genesis) - if Error != nil { - panic(Error) - } - - return bytes -} - -func (genesis Genesis) Decode(cdc codec.JSONMarshaler, byte []byte) helpers.Genesis { - var newGenesis Genesis - if Error := cdc.UnmarshalJSON(byte, &newGenesis); Error != nil { - panic(Error) - } - - return NewGenesis(genesis.DefaultMappableList, genesis.DefaultParameterList).Initialize(newGenesis.GetMappableList(), newGenesis.GetParameterList()) -} - -func (genesis Genesis) Initialize(mappableList []helpers.Mappable, parameterList []types.Parameter) helpers.Genesis { - newParametersList := make([]dummy.DummyParameter, len(parameterList)) - for i, _ := range parameterList { - newParametersList[i] = *dummy.NewParameter(parameterList[i].GetID(), parameterList[i].GetData()) - } - newMappableList := make([]mappable.Split, len(mappableList)) - for i, _ := range mappableList { - newMappableList[i] = *mappableList[i].(*mappable.Split) - } - newParameter := dummy.Parameter.Mutate(dummy.Parameter.GetData()) - genesis.DefaultParameterList = []dummy.DummyParameter{*dummy.NewParameter(newParameter.GetID(), newParameter.GetData())} - if len(newMappableList) == 0 { - genesis.MappableList = genesis.DefaultMappableList - } else { - genesis.MappableList = newMappableList - } - - if len(newParametersList) == 0 { - genesis.ParameterList = genesis.DefaultParameterList - } else { - for _, defaultParameter := range genesis.DefaultParameterList { - for i, parameter := range newParametersList { - if defaultParameter.GetID().Compare(parameter.GetID()) == 0 { - newParametersList[i] = *dummy.NewParameter(defaultParameter.Mutate(parameter.GetData()).GetID(), defaultParameter.Mutate(parameter.GetData()).GetData()) - } - } - } - genesis.ParameterList = newParametersList - } - - if Error := genesis.Validate(); Error != nil { - panic(Error) - } - - return &genesis -} - -func (genesis Genesis) GetParameterList() []types.Parameter { - newParameterList := make([]types.Parameter, len(genesis.ParameterList)) - for i, _ := range genesis.ParameterList { - newParameterList[i] = &genesis.ParameterList[i] - } - return newParameterList -} -func (genesis Genesis) GetMappableList() []helpers.Mappable { - newMappableList := make([]helpers.Mappable, len(genesis.MappableList)) - for i, _ := range genesis.MappableList { - newMappableList[i] = &genesis.MappableList[i] - } - return newMappableList -} - -func (genesis Genesis) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*helpers.Key)(nil), - &key.SplitID{}, - ) - registry.RegisterImplementations((*helpers.Mappable)(nil), - &mappable.Split{}, - ) - registry.RegisterImplementations((*types.Parameter)(nil), - &dummy.DummyParameter{}, - ) - registry.RegisterImplementations((*helpers.Genesis)(nil), - &Genesis{}, - ) -} - -func NewGenesis(defaultMappableList []mappable.Split, defaultParameterList []dummy.DummyParameter) *Genesis { - return &Genesis{ - DefaultMappableList: defaultMappableList, - DefaultParameterList: defaultParameterList, - MappableList: []mappable.Split{}, - ParameterList: []dummy.DummyParameter{}, - } -} diff --git a/modules/splits/internal/genesis/genesis.pb.go b/modules/splits/internal/genesis/genesis.pb.go deleted file mode 100644 index 10951cdf3..000000000 --- a/modules/splits/internal/genesis/genesis.pb.go +++ /dev/null @@ -1,499 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/splits/internal/genesis/genesis.proto - -package genesis - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - mappable "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable" - dummy "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters/dummy" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Genesis struct { - DefaultMappableList []mappable.Split `protobuf:"bytes,1,rep,name=defaultMappableList,proto3" json:"defaultMappableList"` - DefaultParameterList []dummy.DummyParameter `protobuf:"bytes,2,rep,name=defaultParameterList,proto3" json:"defaultParameterList"` - MappableList []mappable.Split `protobuf:"bytes,3,rep,name=MappableList,proto3" json:"MappableList"` - ParameterList []dummy.DummyParameter `protobuf:"bytes,4,rep,name=ParameterList,proto3" json:"ParameterList"` -} - -func (m *Genesis) Reset() { *m = Genesis{} } -func (m *Genesis) String() string { return proto.CompactTextString(m) } -func (*Genesis) ProtoMessage() {} -func (*Genesis) Descriptor() ([]byte, []int) { - return fileDescriptor_9d4cfc0c5645c2fe, []int{0} -} -func (m *Genesis) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Genesis) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Genesis.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Genesis) XXX_Merge(src proto.Message) { - xxx_messageInfo_Genesis.Merge(m, src) -} -func (m *Genesis) XXX_Size() int { - return m.Size() -} -func (m *Genesis) XXX_DiscardUnknown() { - xxx_messageInfo_Genesis.DiscardUnknown(m) -} - -var xxx_messageInfo_Genesis proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Genesis)(nil), "persistence_sdk.modules.splits.internal.genesis.Genesis") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/splits/internal/genesis/genesis.proto", fileDescriptor_9d4cfc0c5645c2fe) -} - -var fileDescriptor_9d4cfc0c5645c2fe = []byte{ - // 327 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x2d, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0x2f, 0x2e, 0xc8, 0xc9, 0x2c, 0x29, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, - 0xca, 0x4b, 0xcc, 0xd1, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0x86, 0xd1, 0x7a, 0x05, 0x45, - 0xf9, 0x25, 0xf9, 0x42, 0xfa, 0x68, 0xda, 0xf5, 0xa0, 0xda, 0xf5, 0x20, 0xda, 0xf5, 0x60, 0xda, - 0xf5, 0xa0, 0xda, 0xa4, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x7a, 0xf5, 0x41, 0x2c, 0x88, 0x31, - 0x52, 0x1e, 0xc4, 0xba, 0xa2, 0x20, 0xb1, 0x28, 0x31, 0x37, 0xb5, 0x24, 0xb5, 0xa8, 0x58, 0x3f, - 0xa5, 0x34, 0x37, 0xb7, 0x12, 0x21, 0x00, 0x35, 0xc9, 0x86, 0x58, 0x93, 0x72, 0x13, 0x0b, 0x0a, - 0x12, 0x93, 0x72, 0x52, 0x21, 0x12, 0x10, 0xdd, 0x4a, 0xf7, 0x98, 0xb9, 0xd8, 0xdd, 0x21, 0x2e, - 0x15, 0xca, 0xe7, 0x12, 0x4e, 0x49, 0x4d, 0x4b, 0x2c, 0xcd, 0x29, 0xf1, 0x85, 0x2a, 0xf5, 0xc9, - 0x2c, 0x2e, 0x91, 0x60, 0x54, 0x60, 0xd6, 0xe0, 0x36, 0x32, 0xd7, 0x23, 0xd6, 0xe3, 0x30, 0x7b, - 0xf4, 0x82, 0x41, 0x12, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, 0x04, 0x61, 0x33, 0x59, 0xa8, 0x89, - 0x91, 0x4b, 0x04, 0x2a, 0x1e, 0x00, 0xf3, 0x15, 0xd8, 0x4a, 0x26, 0xb0, 0x95, 0x1e, 0x44, 0x5b, - 0x89, 0x08, 0x24, 0x3d, 0x70, 0x20, 0xe9, 0xb9, 0x80, 0x48, 0xb8, 0x99, 0x50, 0x37, 0x60, 0xb5, - 0x4b, 0x28, 0x91, 0x8b, 0x07, 0xc5, 0xbb, 0xcc, 0xd4, 0xf0, 0x2e, 0x8a, 0x91, 0x42, 0x25, 0x5c, - 0xbc, 0xa8, 0xfe, 0x63, 0xa1, 0x89, 0xff, 0x50, 0x2d, 0xb1, 0x62, 0xe9, 0x58, 0x20, 0xcf, 0xe0, - 0x94, 0x74, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, - 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x1e, 0xe9, 0x99, 0x25, - 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xc8, 0x89, 0xda, 0x3f, 0x2f, 0x15, 0x99, 0x1b, 0xec, - 0xe2, 0x4d, 0x28, 0x87, 0x24, 0xb1, 0x81, 0xd3, 0x92, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x2b, - 0xe3, 0x93, 0x38, 0x5b, 0x03, 0x00, 0x00, -} - -func (m *Genesis) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Genesis) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Genesis) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ParameterList) > 0 { - for iNdEx := len(m.ParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.MappableList) > 0 { - for iNdEx := len(m.MappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.DefaultParameterList) > 0 { - for iNdEx := len(m.DefaultParameterList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultParameterList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if len(m.DefaultMappableList) > 0 { - for iNdEx := len(m.DefaultMappableList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.DefaultMappableList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Genesis) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.DefaultMappableList) > 0 { - for _, e := range m.DefaultMappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.DefaultParameterList) > 0 { - for _, e := range m.DefaultParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.MappableList) > 0 { - for _, e := range m.MappableList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ParameterList) > 0 { - for _, e := range m.ParameterList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Genesis) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Genesis: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Genesis: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultMappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultMappableList = append(m.DefaultMappableList, mappable.Split{}) - if err := m.DefaultMappableList[len(m.DefaultMappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DefaultParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DefaultParameterList = append(m.DefaultParameterList, dummy.DummyParameter{}) - if err := m.DefaultParameterList[len(m.DefaultParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MappableList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MappableList = append(m.MappableList, mappable.Split{}) - if err := m.MappableList[len(m.MappableList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ParameterList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ParameterList = append(m.ParameterList, dummy.DummyParameter{}) - if err := m.ParameterList[len(m.ParameterList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenesis(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenesis - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenesis - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenesis - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenesis - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/splits/internal/genesis/prototype.go b/modules/splits/internal/genesis/prototype.go index f3899dd50..148aea393 100644 --- a/modules/splits/internal/genesis/prototype.go +++ b/modules/splits/internal/genesis/prototype.go @@ -1,16 +1,16 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package genesis import ( - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" ) func Prototype() helpers.Genesis { - return NewGenesis([]mappable.Split{}, []dummy.DummyParameter{}) + return baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{}, parameters.Prototype().GetList()) } diff --git a/modules/splits/internal/genesis/prototype_test.go b/modules/splits/internal/genesis/prototype_test.go new file mode 100644 index 000000000..4ce056de7 --- /dev/null +++ b/modules/splits/internal/genesis/prototype_test.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package genesis + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Panics(t, func() { + require.Equal(t, Prototype(), baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, []helpers.Mappable{}, parameters.Prototype().GetList())) + }) +} diff --git a/modules/splits/internal/key/key.go b/modules/splits/internal/key/key.go new file mode 100644 index 000000000..012ca56a0 --- /dev/null +++ b/modules/splits/internal/key/key.go @@ -0,0 +1,55 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package key + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/splits/internal/module" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +type key struct { + ids.SplitID +} + +var _ helpers.Key = (*key)(nil) + +func (key key) GenerateStoreKeyBytes() []byte { + return module.StoreKeyPrefix.GenerateStoreKey(key.Bytes()) +} +func (key) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, key{}) +} +func (key key) IsPartial() bool { + return len(key.SplitID.GetOwnableID().Bytes()) == 0 +} +func (key key) Equals(compareKey helpers.Key) bool { + if compareKey, err := keyFromInterface(compareKey); err != nil { + return false + } else { + return key.SplitID.Compare(compareKey.SplitID) == 0 + } +} +func keyFromInterface(i interface{}) (key, error) { + switch value := i.(type) { + case key: + return value, nil + default: + return key{}, constants.MetaDataError + } +} + +func NewKey(splitID ids.SplitID) helpers.Key { + return key{ + SplitID: splitID, + } +} + +func Prototype() helpers.Key { + return key{} +} diff --git a/modules/splits/internal/key/key_test.go b/modules/splits/internal/key/key_test.go index e3869aec0..f0279d159 100644 --- a/modules/splits/internal/key/key_test.go +++ b/modules/splits/internal/key/key_test.go @@ -4,6 +4,11 @@ package key import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/AssetMantle/modules/modules/splits/internal/module" baseData "github.com/AssetMantle/modules/schema/data/base" "github.com/AssetMantle/modules/schema/helpers" @@ -12,9 +17,6 @@ import ( baseLists "github.com/AssetMantle/modules/schema/lists/base" baseProperties "github.com/AssetMantle/modules/schema/properties/base" baseQualified "github.com/AssetMantle/modules/schema/qualified/base" - "github.com/cosmos/cosmos-sdk/codec" - "reflect" - "testing" ) var ( diff --git a/modules/splits/internal/key/splitID.go b/modules/splits/internal/key/splitID.go deleted file mode 100644 index 84b4724cc..000000000 --- a/modules/splits/internal/key/splitID.go +++ /dev/null @@ -1,60 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - "bytes" - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "strings" -) - -var _ types.ID = (*SplitID)(nil) -var _ helpers.Key = (*SplitID)(nil) - -func (splitID SplitID) GetStructReference() codec.ProtoMarshaler { - return &splitID -} -func (splitID SplitID) Bytes() []byte { - return append( - splitID.OwnerID.Bytes(), - splitID.OwnableID.Bytes()...) -} -func (splitID SplitID) String() string { - var values []string - values = append(values, splitID.OwnerID.String()) - values = append(values, splitID.OwnableID.String()) - - return strings.Join(values, constants.SecondOrderCompositeIDSeparator) -} -func (splitID SplitID) Compare(id types.ID) int { - return bytes.Compare(splitID.Bytes(), id.Bytes()) -} -func (splitID SplitID) GenerateStoreKeyBytes() []byte { - return module.StoreKeyPrefix.GenerateStoreKey(splitID.Bytes()) -} -func (SplitID) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, SplitID{}) -} -func (splitID SplitID) IsPartial() bool { - return len(splitID.OwnableID.Bytes()) == 0 -} -func (splitID SplitID) Equals(key helpers.Key) bool { - id := splitIDFromInterface(key) - return splitID.Compare(&id) == 0 -} - -func NewSplitID(ownerID types.ID, ownableID types.ID) types.ID { - return &SplitID{ - OwnerID: ownerID, - OwnableID: ownableID, - } -} diff --git a/modules/splits/internal/key/splitID.pb.go b/modules/splits/internal/key/splitID.pb.go deleted file mode 100644 index c6dadbee1..000000000 --- a/modules/splits/internal/key/splitID.pb.go +++ /dev/null @@ -1,367 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/splits/internal/key/splitID.proto - -package key - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - github_com_persistenceOne_persistenceSDK_schema_types "github.com/persistenceOne/persistenceSDK/schema/types" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type SplitID struct { - OwnerID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,1,opt,name=owner_i_d,json=ownerID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"owner_i_d"` - OwnableID github_com_persistenceOne_persistenceSDK_schema_types.ID `protobuf:"bytes,2,opt,name=ownable_i_d,json=ownableID,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types.ID" json:"ownable_i_d"` -} - -func (m *SplitID) Reset() { *m = SplitID{} } -func (*SplitID) ProtoMessage() {} -func (*SplitID) Descriptor() ([]byte, []int) { - return fileDescriptor_6779bb553020d011, []int{0} -} -func (m *SplitID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SplitID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SplitID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *SplitID) XXX_Merge(src proto.Message) { - xxx_messageInfo_SplitID.Merge(m, src) -} -func (m *SplitID) XXX_Size() int { - return m.Size() -} -func (m *SplitID) XXX_DiscardUnknown() { - xxx_messageInfo_SplitID.DiscardUnknown(m) -} - -var xxx_messageInfo_SplitID proto.InternalMessageInfo - -func init() { - proto.RegisterType((*SplitID)(nil), "persistence_sdk.modules.splits.internal.key.SplitID") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/splits/internal/key/splitID.proto", fileDescriptor_6779bb553020d011) -} - -var fileDescriptor_6779bb553020d011 = []byte{ - // 258 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x2c, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0x2f, 0x2e, 0xc8, 0xc9, 0x2c, 0x29, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, - 0xca, 0x4b, 0xcc, 0xd1, 0xcf, 0x4e, 0xad, 0x84, 0x88, 0x79, 0xba, 0xe8, 0x15, 0x14, 0xe5, 0x97, - 0xe4, 0x0b, 0x69, 0xa3, 0x69, 0xd5, 0x83, 0x6a, 0xd5, 0x83, 0x68, 0xd5, 0x83, 0x69, 0xd5, 0xcb, - 0x4e, 0xad, 0x94, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0xeb, 0xd3, 0x07, 0xb1, 0x20, 0x46, 0x28, - 0x9d, 0x67, 0xe4, 0x62, 0x0f, 0x86, 0x18, 0x2a, 0x14, 0xc3, 0xc5, 0x99, 0x5f, 0x9e, 0x97, 0x5a, - 0x14, 0x9f, 0x19, 0x9f, 0x22, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0xe9, 0xe4, 0x70, 0xe2, 0x9e, 0x3c, - 0xc3, 0xad, 0x7b, 0xf2, 0x16, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, - 0x48, 0x96, 0xfa, 0xe7, 0xa5, 0x22, 0x73, 0x83, 0x5d, 0xbc, 0xf5, 0x8b, 0x93, 0x33, 0x52, 0x73, - 0x13, 0xf5, 0x4b, 0x2a, 0x0b, 0x52, 0x8b, 0xf5, 0x3c, 0x5d, 0x82, 0xd8, 0xc1, 0x46, 0x7a, 0xba, - 0x08, 0x25, 0x70, 0x71, 0xe7, 0x97, 0xe7, 0x25, 0x26, 0xe5, 0xa4, 0x82, 0xcd, 0x67, 0xa2, 0x92, - 0xf9, 0x9c, 0x50, 0x43, 0x3d, 0x5d, 0xac, 0x58, 0x66, 0x2c, 0x90, 0x67, 0x70, 0x8a, 0x3b, 0xf1, - 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, - 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0x17, 0xa2, 0x2d, 0xc1, 0x13, 0x05, 0x49, - 0x6c, 0xe0, 0x80, 0x33, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x28, 0xac, 0x6b, 0xbe, 0xb8, 0x01, - 0x00, 0x00, -} - -func (m *SplitID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *SplitID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SplitID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.OwnableID.Size() - i -= size - if _, err := m.OwnableID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintSplitID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.OwnerID.Size() - i -= size - if _, err := m.OwnerID.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintSplitID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintSplitID(dAtA []byte, offset int, v uint64) int { - offset -= sovSplitID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *SplitID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.OwnerID.Size() - n += 1 + l + sovSplitID(uint64(l)) - l = m.OwnableID.Size() - n += 1 + l + sovSplitID(uint64(l)) - return n -} - -func sovSplitID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozSplitID(x uint64) (n int) { - return sovSplitID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *SplitID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSplitID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: SplitID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SplitID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OwnerID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSplitID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSplitID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSplitID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OwnerID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OwnableID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSplitID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSplitID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSplitID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OwnableID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSplitID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSplitID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipSplitID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSplitID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSplitID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSplitID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthSplitID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupSplitID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthSplitID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthSplitID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowSplitID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupSplitID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/splits/internal/key/splitID_test.go b/modules/splits/internal/key/splitID_test.go deleted file mode 100644 index 4e8201a2f..000000000 --- a/modules/splits/internal/key/splitID_test.go +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" - "strings" - "testing" -) - -func Test_SplitID_Methods(t *testing.T) { - - ownerID := base.NewID("ownerID") - ownableID := base.NewID("ownableID") - - testSplitID := NewSplitID(ownerID, ownableID).(SplitID) - testSplitID2 := NewSplitID(base.NewID(""), base.NewID("")).(SplitID) - require.NotPanics(t, func() { - require.Equal(t, strings.Join([]string{ownerID.String(), ownableID.String()}, constants.SecondOrderCompositeIDSeparator), testSplitID.String()) - require.Equal(t, true, testSplitID.Equals(testSplitID)) - require.Equal(t, false, testSplitID.Equals(testSplitID2)) - require.Equal(t, false, testSplitID.IsPartial()) - require.Equal(t, true, testSplitID2.IsPartial()) - - require.Equal(t, true, testSplitID.Equals(testSplitID)) - require.Equal(t, false, testSplitID.Equals(testSplitID2)) - require.Equal(t, false, testSplitID.Equals(nil)) - require.Equal(t, testSplitID, FromID(&testSplitID)) - require.Equal(t, testSplitID2, FromID(base.NewID(""))) - require.Equal(t, SplitID{OwnerID: base.NewID("ID1"), OwnableID: base.NewID("ID2")}, readSplitID("ID1*ID2")) - }) -} diff --git a/modules/splits/internal/key/utilities.go b/modules/splits/internal/key/utilities.go deleted file mode 100644 index 687eddd1f..000000000 --- a/modules/splits/internal/key/utilities.go +++ /dev/null @@ -1,54 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package key - -import ( - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "strings" -) - -func readSplitID(splitIDString string) SplitID { - idList := strings.Split(splitIDString, constants.SecondOrderCompositeIDSeparator) - if len(idList) == 2 { - return SplitID{ - OwnerID: base.NewID(idList[0]), - OwnableID: base.NewID(idList[1]), - } - } - - return SplitID{OwnerID: base.NewID(""), OwnableID: base.NewID("")} -} - -func splitIDFromInterface(i interface{}) SplitID { - switch value := i.(type) { - case SplitID: - return value - case types.ID: - return splitIDFromInterface(readSplitID(value.String())) - default: - panic(i) - } -} - -func ReadOwnableID(id types.ID) types.ID { - return splitIDFromInterface(id).OwnableID -} - -func ReadOwnerID(id types.ID) types.ID { - return splitIDFromInterface(id).OwnerID -} - -func FromID(id types.ID) helpers.Key { - return splitIDFromInterface(id) -} - -func ToID(key helpers.Key) types.ID { - id := splitIDFromInterface(key) - return &id -} diff --git a/modules/splits/internal/mappable/mappable.go b/modules/splits/internal/mappable/mappable.go new file mode 100644 index 000000000..1ca6529e0 --- /dev/null +++ b/modules/splits/internal/mappable/mappable.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mappable + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/types" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +type mappable struct { + types.Split +} + +var _ helpers.Mappable = (*mappable)(nil) + +func (mappable mappable) GetKey() helpers.Key { + return key.NewKey(base.NewSplitID(mappable.Split.GetOwnerID(), mappable.Split.GetOwnableID())) +} +func (mappable) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, mappable{}) +} + +func NewMappable(split types.Split) helpers.Mappable { + return mappable{Split: split} +} + +func Prototype() helpers.Mappable { + return mappable{} +} diff --git a/modules/splits/internal/mappable/mappable_test.go b/modules/splits/internal/mappable/mappable_test.go index b84a8fa7f..57cee0cb3 100644 --- a/modules/splits/internal/mappable/mappable_test.go +++ b/modules/splits/internal/mappable/mappable_test.go @@ -4,6 +4,12 @@ package mappable import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/AssetMantle/modules/modules/splits/internal/key" baseData "github.com/AssetMantle/modules/schema/data/base" "github.com/AssetMantle/modules/schema/helpers" @@ -13,10 +19,6 @@ import ( baseQualified "github.com/AssetMantle/modules/schema/qualified/base" "github.com/AssetMantle/modules/schema/types" baseTypes "github.com/AssetMantle/modules/schema/types/base" - "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "reflect" - "testing" ) var ( diff --git a/modules/splits/internal/mappable/prototype.go b/modules/splits/internal/mappable/prototype.go deleted file mode 100644 index 61f275b4b..000000000 --- a/modules/splits/internal/mappable/prototype.go +++ /dev/null @@ -1,12 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import "github.com/persistenceOne/persistenceSDK/schema/helpers" - -func Prototype() helpers.Mappable { - return &Split{} -} diff --git a/modules/splits/internal/mappable/split.go b/modules/splits/internal/mappable/split.go deleted file mode 100644 index 7364d927d..000000000 --- a/modules/splits/internal/mappable/split.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import ( - "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/mappables" - "github.com/persistenceOne/persistenceSDK/schema/traits" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" -) - -var _ mappables.Split = (*Split)(nil) - -func (split Split) GetStructReference() codec.ProtoMarshaler { - return &split -} -func (split Split) GetID() types.ID { return &split.ID } -func (split Split) GetOwnerID() types.ID { - return key.ReadOwnerID(&split.ID) -} -func (split Split) GetOwnableID() types.ID { - return key.ReadOwnableID(&split.ID) -} -func (split Split) GetValue() sdkTypes.Dec { - return split.Value -} -func (split Split) Send(outValue sdkTypes.Dec) traits.Transactional { - result := split.Value.Sub(outValue) - split.Value = result - return split -} -func (split Split) Receive(inValue sdkTypes.Dec) traits.Transactional { - result := split.Value.Add(inValue) - split.Value = result - return split -} -func (split Split) CanSend(outValue sdkTypes.Dec) bool { - return split.Value.GTE(outValue) -} -func (split Split) GetKey() helpers.Key { - return key.FromID(&split.ID) -} -func (Split) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Split{}) -} - -func NewSplit(splitID types.ID, value sdkTypes.Dec) mappables.Split { - return &Split{ - ID: *base.NewID(splitID.String()), - Value: value, - } -} diff --git a/modules/splits/internal/mappable/split.pb.go b/modules/splits/internal/mappable/split.pb.go deleted file mode 100644 index 9a3020e9d..000000000 --- a/modules/splits/internal/mappable/split.pb.go +++ /dev/null @@ -1,370 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/splits/internal/mappable/split.proto - -package mappable - -import ( - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Split struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - Value github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=value,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"value"` -} - -func (m *Split) Reset() { *m = Split{} } -func (m *Split) String() string { return proto.CompactTextString(m) } -func (*Split) ProtoMessage() {} -func (*Split) Descriptor() ([]byte, []int) { - return fileDescriptor_03f63749cdee6543, []int{0} -} -func (m *Split) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Split) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Split.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Split) XXX_Merge(src proto.Message) { - xxx_messageInfo_Split.Merge(m, src) -} -func (m *Split) XXX_Size() int { - return m.Size() -} -func (m *Split) XXX_DiscardUnknown() { - xxx_messageInfo_Split.DiscardUnknown(m) -} - -var xxx_messageInfo_Split proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Split)(nil), "persistence_sdk.modules.splits.internal.mappable.Split") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/splits/internal/mappable/split.proto", fileDescriptor_03f63749cdee6543) -} - -var fileDescriptor_03f63749cdee6543 = []byte{ - // 295 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x29, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0x2f, 0x2e, 0xc8, 0xc9, 0x2c, 0x29, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, - 0xca, 0x4b, 0xcc, 0xd1, 0xcf, 0x4d, 0x2c, 0x28, 0x48, 0x4c, 0xca, 0x49, 0x85, 0x48, 0xe8, 0x15, - 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0x19, 0xa0, 0xe9, 0xd6, 0x83, 0xea, 0xd6, 0x83, 0xe8, 0xd6, 0x83, - 0xe9, 0xd6, 0x83, 0xe9, 0x96, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x6b, 0xd6, 0x07, 0xb1, 0x20, - 0xe6, 0x48, 0x69, 0xa1, 0xbb, 0xa2, 0x38, 0x39, 0x23, 0x35, 0x37, 0x51, 0xbf, 0xa4, 0xb2, 0x20, - 0xb5, 0x58, 0x3f, 0x29, 0xb1, 0x38, 0x55, 0x3f, 0x33, 0x05, 0xa2, 0x56, 0x69, 0x22, 0x23, 0x17, - 0x6b, 0x30, 0xc8, 0x78, 0x21, 0x1b, 0x2e, 0xe6, 0xcc, 0xf8, 0x14, 0x09, 0x46, 0x05, 0x46, 0x0d, - 0x6e, 0x23, 0x55, 0x3d, 0x74, 0xb7, 0x40, 0xcc, 0xd0, 0x03, 0x9b, 0xa1, 0x07, 0x32, 0x43, 0xcf, - 0xd3, 0xc5, 0x89, 0xe5, 0xc4, 0x3d, 0x79, 0x86, 0x20, 0xa6, 0x4c, 0x17, 0x21, 0x17, 0x2e, 0xd6, - 0xb2, 0xc4, 0x9c, 0xd2, 0x54, 0x09, 0x26, 0x05, 0x46, 0x0d, 0x4e, 0x27, 0x3d, 0x90, 0xc4, 0xad, - 0x7b, 0xf2, 0x6a, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xc9, 0xf9, - 0xc5, 0xb9, 0xf9, 0xc5, 0x50, 0x4a, 0x17, 0xe4, 0x2e, 0x88, 0x61, 0x2e, 0xa9, 0xc9, 0x41, 0x10, - 0xcd, 0x56, 0x2c, 0x1d, 0x0b, 0xe4, 0x19, 0x9c, 0x92, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, - 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, - 0x58, 0x8e, 0x21, 0xca, 0x13, 0xc9, 0x38, 0x24, 0x07, 0xfa, 0xe7, 0xa5, 0x22, 0x73, 0x83, 0x5d, - 0xbc, 0x09, 0x06, 0x7c, 0x12, 0x1b, 0xd8, 0xff, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x45, - 0x20, 0xa1, 0xc9, 0xb3, 0x01, 0x00, 0x00, -} - -func (m *Split) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Split) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Split) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Value.Size() - i -= size - if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintSplit(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSplit(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintSplit(dAtA []byte, offset int, v uint64) int { - offset -= sovSplit(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Split) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovSplit(uint64(l)) - l = m.Value.Size() - n += 1 + l + sovSplit(uint64(l)) - return n -} - -func sovSplit(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozSplit(x uint64) (n int) { - return sovSplit(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Split) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSplit - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Split: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Split: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSplit - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSplit - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSplit - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSplit - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSplit - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSplit - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSplit(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSplit - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipSplit(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSplit - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSplit - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSplit - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthSplit - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupSplit - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthSplit - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthSplit = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowSplit = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupSplit = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/splits/internal/mappable/split_test.go b/modules/splits/internal/mappable/split_test.go deleted file mode 100644 index 281634423..000000000 --- a/modules/splits/internal/mappable/split_test.go +++ /dev/null @@ -1,35 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package mappable - -import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" - "testing" -) - -func Test_Split_Methods(t *testing.T) { - - ownerID := base.NewID("ownerID") - ownableID := base.NewID("ownableID") - - testSplitID := key.NewSplitID(ownerID, ownableID) - testValue := sdkTypes.NewDec(12) - testSplit := NewSplit(testSplitID, testValue).(split) - - require.Equal(t, split{ID: testSplitID, Value: testValue}, testSplit) - require.Equal(t, testSplitID, testSplit.GetID()) - require.Equal(t, ownerID, testSplit.GetOwnerID()) - require.Equal(t, ownableID, testSplit.GetOwnableID()) - require.Equal(t, testValue, testSplit.GetValue()) - require.Equal(t, NewSplit(testSplitID, sdkTypes.NewDec(11)).(split), testSplit.Send(sdkTypes.NewDec(1))) - require.Equal(t, NewSplit(testSplitID, sdkTypes.NewDec(13)).(split), testSplit.Receive(sdkTypes.NewDec(1))) - require.Equal(t, true, testSplit.CanSend(sdkTypes.NewDec(5))) - require.Equal(t, false, testSplit.CanSend(sdkTypes.NewDec(15))) - require.Equal(t, testSplitID, testSplit.GetKey()) -} diff --git a/modules/splits/internal/mapper/prototype.go b/modules/splits/internal/mapper/prototype.go new file mode 100644 index 000000000..84b7bb38d --- /dev/null +++ b/modules/splits/internal/mapper/prototype.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package mapper + +import ( + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Mapper { + return baseHelpers.NewMapper(key.Prototype, mappable.Prototype) +} diff --git a/modules/splits/internal/module/constants.go b/modules/splits/internal/module/constants.go new file mode 100644 index 000000000..1a3f2f839 --- /dev/null +++ b/modules/splits/internal/module/constants.go @@ -0,0 +1,12 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package module + +import ( + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +const Name = "splits" + +var StoreKeyPrefix = constants.SplitsStoreKeyPrefix diff --git a/modules/splits/internal/parameters/dummy/constants.go b/modules/splits/internal/parameters/dummy/constants.go new file mode 100644 index 000000000..770f437dc --- /dev/null +++ b/modules/splits/internal/parameters/dummy/constants.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package dummy + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +var ID = baseIDs.NewStringID("dummy") + +var DefaultData = baseData.NewDecData(sdkTypes.SmallestDec()) diff --git a/modules/splits/internal/parameters/dummy/parameter.go b/modules/splits/internal/parameters/dummy/parameter.go index e78fdc8d0..5ffc0eaf5 100644 --- a/modules/splits/internal/parameters/dummy/parameter.go +++ b/modules/splits/internal/parameters/dummy/parameter.go @@ -1,59 +1,10 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "encoding/json" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" ) -var _ types.Parameter = (*DummyParameter)(nil) - -func (dummyParameter DummyParameter) String() string { - bytes, Error := json.Marshal(dummyParameter) - if Error != nil { - return Error.Error() - } - return string(bytes) -} - -func (dummyParameter DummyParameter) Equal(compareParameter types.Parameter) bool { - if compareParameter == nil { - return false - } - return dummyParameter.Data.Compare(compareParameter.GetData()) == 0 -} - -func (dummyParameter DummyParameter) Validate() error { - return validator(dummyParameter) -} - -func (dummyParameter DummyParameter) GetID() types.ID { - return &dummyParameter.ID -} - -func (dummyParameter DummyParameter) GetData() types.Data { - return &dummyParameter.Data -} - -func (dummyParameter DummyParameter) GetValidator() func(interface{}) error { - return validator -} - -func (dummyParameter DummyParameter) Mutate(data types.Data) types.Parameter { - decData, _ := data.AsDec() - dummyParameter.Data = *base.NewDummyDecData(decData) - return &dummyParameter -} - -func NewParameter(id types.ID, data types.Data) *DummyParameter { - decData, _ := data.AsDec() - return &DummyParameter{ - ID: *base.NewID(id.String()), - Data: *base.NewDummyDecData(decData), - } -} +var Parameter = baseTypes.NewParameter(ID, DefaultData, validator) diff --git a/modules/splits/internal/parameters/dummy/parameter.pb.go b/modules/splits/internal/parameters/dummy/parameter.pb.go deleted file mode 100644 index 0a580d6a2..000000000 --- a/modules/splits/internal/parameters/dummy/parameter.pb.go +++ /dev/null @@ -1,367 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/splits/internal/parameters/dummy/parameter.proto - -package dummy - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type DummyParameter struct { - ID base.ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - Data base.DecData `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` -} - -func (m *DummyParameter) Reset() { *m = DummyParameter{} } -func (*DummyParameter) ProtoMessage() {} -func (*DummyParameter) Descriptor() ([]byte, []int) { - return fileDescriptor_019dc62849d8b105, []int{0} -} -func (m *DummyParameter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DummyParameter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DummyParameter.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DummyParameter) XXX_Merge(src proto.Message) { - xxx_messageInfo_DummyParameter.Merge(m, src) -} -func (m *DummyParameter) XXX_Size() int { - return m.Size() -} -func (m *DummyParameter) XXX_DiscardUnknown() { - xxx_messageInfo_DummyParameter.DiscardUnknown(m) -} - -var xxx_messageInfo_DummyParameter proto.InternalMessageInfo - -func init() { - proto.RegisterType((*DummyParameter)(nil), "persistence_sdk.modules.splits.internal.parameters.dummy.DummyParameter") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/splits/internal/parameters/dummy/parameter.proto", fileDescriptor_019dc62849d8b105) -} - -var fileDescriptor_019dc62849d8b105 = []byte{ - // 304 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xf2, 0x28, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0xcf, 0xcd, 0x4f, 0x29, - 0xcd, 0x49, 0x2d, 0xd6, 0x2f, 0x2e, 0xc8, 0xc9, 0x2c, 0x29, 0xd6, 0xcf, 0xcc, 0x2b, 0x49, 0x2d, - 0xca, 0x4b, 0xcc, 0xd1, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x4d, 0x2d, 0x49, 0x2d, 0x2a, 0xd6, 0x4f, - 0x29, 0xcd, 0xcd, 0xad, 0x44, 0x08, 0xe8, 0x15, 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0x59, 0xa0, 0x99, - 0xa4, 0x07, 0x35, 0x49, 0x0f, 0x62, 0x92, 0x1e, 0xcc, 0x24, 0x3d, 0x84, 0x49, 0x7a, 0x60, 0x93, - 0xa4, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x86, 0xe8, 0x83, 0x58, 0x10, 0xf3, 0xa4, 0xf4, 0xd1, - 0x5d, 0x56, 0x9c, 0x9c, 0x91, 0x9a, 0x9b, 0xa8, 0x5f, 0x52, 0x59, 0x90, 0x5a, 0xac, 0x9f, 0x94, - 0x58, 0x9c, 0xaa, 0x9f, 0x92, 0x9a, 0xec, 0x92, 0x58, 0x92, 0x08, 0xd5, 0xa0, 0x45, 0x58, 0x43, - 0x66, 0x0a, 0x44, 0xad, 0xd2, 0x3c, 0x46, 0x2e, 0x3e, 0x17, 0x90, 0xe5, 0x01, 0x30, 0xc7, 0x08, - 0xd9, 0x70, 0x31, 0x67, 0xc6, 0xa7, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x1b, 0xa9, 0xea, 0xa1, - 0xfb, 0x06, 0x62, 0x98, 0x1e, 0xd8, 0x30, 0x3d, 0x90, 0x61, 0x7a, 0x9e, 0x2e, 0x4e, 0x2c, 0x27, - 0xee, 0xc9, 0x33, 0x04, 0x31, 0x65, 0xba, 0x08, 0xb9, 0x70, 0xb1, 0xa4, 0x24, 0x96, 0x24, 0x4a, - 0x30, 0x81, 0xb5, 0x6b, 0x11, 0xa1, 0xdd, 0x05, 0xe2, 0x78, 0xa8, 0x19, 0x60, 0xdd, 0x56, 0x1c, - 0x1d, 0x0b, 0xe4, 0x19, 0x66, 0x2c, 0x90, 0x67, 0x70, 0xca, 0x3e, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, - 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, - 0xc6, 0x63, 0x39, 0x86, 0xa8, 0xc0, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, - 0xe4, 0x20, 0xf2, 0xcf, 0x4b, 0x45, 0xe6, 0x06, 0xbb, 0x78, 0x13, 0x1d, 0x95, 0x49, 0x6c, 0xe0, - 0x40, 0x31, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x4c, 0x0a, 0x64, 0x9e, 0x0d, 0x02, 0x00, 0x00, -} - -func (m *DummyParameter) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DummyParameter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DummyParameter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Data.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintParameter(dAtA []byte, offset int, v uint64) int { - offset -= sovParameter(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *DummyParameter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovParameter(uint64(l)) - l = m.Data.Size() - n += 1 + l + sovParameter(uint64(l)) - return n -} - -func sovParameter(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParameter(x uint64) (n int) { - return sovParameter(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *DummyParameter) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DummyParameter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DummyParameter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParameter(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParameter - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParameter(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParameter - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParameter - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParameter - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParameter = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParameter = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParameter = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/splits/internal/parameters/dummy/prototype.go b/modules/splits/internal/parameters/dummy/prototype.go deleted file mode 100644 index b390a673e..000000000 --- a/modules/splits/internal/parameters/dummy/prototype.go +++ /dev/null @@ -1,3 +0,0 @@ -package dummy - -var Parameter = NewParameter(ID, DefaultData) diff --git a/modules/splits/internal/parameters/dummy/validator.go b/modules/splits/internal/parameters/dummy/validator.go index cc0d80a52..2bb100018 100644 --- a/modules/splits/internal/parameters/dummy/validator.go +++ b/modules/splits/internal/parameters/dummy/validator.go @@ -1,32 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package dummy import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/parameters" ) func validator(i interface{}) error { switch value := i.(type) { - case DummyParameter: - data, Error := value.GetData().AsDec() - if Error != nil || value.GetID().Compare(ID) != 0 || data.IsNegative() { - return errors.InvalidParameter + case parameters.Parameter: + if value.GetID().Compare(ID) != 0 || value.GetData().(data.DecData).Get().IsNegative() { + return constants.InvalidParameter } return nil - case types.Data: - data, Error := value.AsDec() - if Error != nil || data.IsNegative() { - return errors.InvalidParameter + case data.DecData: + if value.Get().IsNegative() { + return constants.InvalidParameter } return nil default: - return errors.IncorrectFormat + return constants.IncorrectFormat } } diff --git a/modules/splits/internal/parameters/dummy/validator_test.go b/modules/splits/internal/parameters/dummy/validator_test.go new file mode 100644 index 000000000..6915a0b78 --- /dev/null +++ b/modules/splits/internal/parameters/dummy/validator_test.go @@ -0,0 +1,21 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package dummy + +import ( + "testing" + + "github.com/stretchr/testify/require" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/errors/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" +) + +func Test_Validator(t *testing.T) { + require.Equal(t, constants.IncorrectFormat, validator(baseIDs.NewStringID(""))) + require.Equal(t, nil, validator(Parameter)) + require.Equal(t, constants.InvalidParameter, validator(baseTypes.NewParameter(baseIDs.NewStringID(""), baseData.NewStringData(""), validator))) +} diff --git a/modules/splits/internal/parameters/prototype.go b/modules/splits/internal/parameters/prototype.go new file mode 100644 index 000000000..186ac1dbd --- /dev/null +++ b/modules/splits/internal/parameters/prototype.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package parameters + +import ( + "github.com/AssetMantle/modules/modules/splits/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Parameters { + return baseHelpers.NewParameters(dummy.Parameter) +} diff --git a/modules/splits/internal/queries/ownable/grpc_query.go b/modules/splits/internal/queries/ownable/grpc_query.go deleted file mode 100644 index 5474c1668..000000000 --- a/modules/splits/internal/queries/ownable/grpc_query.go +++ /dev/null @@ -1,27 +0,0 @@ -package ownable - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/utilities" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type queryServer struct { - queryKeeper -} - -var _ QueryServer = queryServer{} - -func (queryServer queryServer) Enquire(ctx context.Context, queryRequest *QueryRequest) (*QueryResponse, error) { - cntx := sdkTypes.UnwrapSDKContext(ctx) - collection := queryServer.queryKeeper.mapper.NewCollection(cntx) - value := utilities.GetOwnableTotalSplitsValue(collection, base.NewID(queryRequestFromInterface(queryRequest).OwnableID.IdString)) - response := newQueryResponse(value, nil) - return &response, response.GetError() - -} - -func NewQueryServerImpl(keeper queryKeeper) QueryServer { - return &queryServer{keeper} -} diff --git a/modules/splits/internal/queries/ownable/keeper.go b/modules/splits/internal/queries/ownable/keeper.go new file mode 100644 index 000000000..af58cfdb7 --- /dev/null +++ b/modules/splits/internal/queries/ownable/keeper.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package ownable + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/splits/internal/utilities" + "github.com/AssetMantle/modules/schema/helpers" +) + +type queryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.QueryKeeper = (*queryKeeper)(nil) + +func (queryKeeper queryKeeper) Enquire(context sdkTypes.Context, queryRequest helpers.QueryRequest) helpers.QueryResponse { + return newQueryResponse(utilities.GetOwnableTotalSplitsValue(queryKeeper.mapper.NewCollection(context), queryRequestFromInterface(queryRequest).OwnableID), nil) +} + +func (queryKeeper queryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + queryKeeper.mapper = mapper + return queryKeeper +} + +func keeperPrototype() helpers.QueryKeeper { + return queryKeeper{} +} diff --git a/modules/splits/internal/queries/ownable/keeper_test.go b/modules/splits/internal/queries/ownable/keeper_test.go index e3a6755df..b5de778a3 100644 --- a/modules/splits/internal/queries/ownable/keeper_test.go +++ b/modules/splits/internal/queries/ownable/keeper_test.go @@ -1,79 +1,159 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package ownable import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "testing" + + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" ) -func CreateTestInput2(t *testing.T) (sdkTypes.Context, helpers.Keeper) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +type TestKeepers struct { + OwnableKeeper helpers.QueryKeeper +} + +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() + storeKey := sdkTypes.NewKVStoreKey("test") paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) - mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) - paramsKeeper := params.NewKeeper( - Codec, - paramsStoreKey, - paramsTransientStoreKeys, - ) - Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) - - testQueryKeeper := keeperPrototype().Initialize(mapper, Parameters, []interface{}{}) + keepers := TestKeepers{ + OwnableKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.QueryKeeper), + } - return context, testQueryKeeper + return context, keepers, Mapper, Parameters } -func Test_Query_Keeper_Split(t *testing.T) { - - context, keepers := CreateTestInput2(t) - - ownerID := base.NewID("ownerID") - ownableID := base.NewID("ownableID") - splitID := key.NewSplitID(ownerID, ownableID) - keepers.(queryKeeper).mapper.NewCollection(context).Add(mappable.NewSplit(splitID, sdkTypes.NewDec(123))) +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryKeeper + }{ + {"+ve", queryKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - testQueryRequest := newQueryRequest(splitID) - require.Panics(t, func() { - require.Equal(t, queryResponse{Success: true, Value: sdkTypes.NewDec(123)}, keepers.(queryKeeper).LegacyEnquire(context, testQueryRequest)) - }) +func Test_queryKeeper_Enquire(t *testing.T) { + context, keepers, Mapper, _ := createTestInput(t) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testOwnerIdentityID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + testRate := sdkTypes.NewDec(1) + split := baseTypes.NewSplit(testOwnerIdentityID, testOwnableID, testRate) + keepers.OwnableKeeper.(queryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(split)) + type fields struct { + mapper helpers.Mapper + } + type args struct { + context sdkTypes.Context + queryRequest helpers.QueryRequest + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryResponse + }{ + {"+ve", fields{Mapper}, args{context, newQueryRequest(testOwnableID)}, newQueryResponse(testRate, nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryKeeper := queryKeeper{ + mapper: tt.fields.mapper, + } + if got := queryKeeper.Enquire(tt.args.context, tt.args.queryRequest); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Enquire() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_queryKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + in2 []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper}, args{Mapper, Parameters, []interface{}{}}, queryKeeper{Mapper}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryKeeper := queryKeeper{ + mapper: tt.fields.mapper, + } + if got := queryKeeper.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/internal/queries/ownable/query.go b/modules/splits/internal/queries/ownable/query.go new file mode 100644 index 000000000..bf961b972 --- /dev/null +++ b/modules/splits/internal/queries/ownable/query.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package ownable + +import ( + "github.com/AssetMantle/modules/modules/splits/internal/module" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Query = baseHelpers.NewQuery( + "ownables", + "", + "", + + module.Name, + + requestPrototype, + responsePrototype, + keeperPrototype, + + constants.OwnableID, +) diff --git a/modules/splits/internal/queries/ownable/query.pb.go b/modules/splits/internal/queries/ownable/query.pb.go deleted file mode 100644 index 9117c5da6..000000000 --- a/modules/splits/internal/queries/ownable/query.pb.go +++ /dev/null @@ -1,664 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/splits/internal/queries/ownable/query.proto - -package ownable - -import ( - context "context" - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type QueryRequest struct { - OwnableID base.ID `protobuf:"bytes,1,opt,name=ownable_i_d,json=ownableID,proto3" json:"ownable_i_d" valid:"required~required OwnableID missing"` -} - -func (m *QueryRequest) Reset() { *m = QueryRequest{} } -func (m *QueryRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRequest) ProtoMessage() {} -func (*QueryRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_845976b6477d0a88, []int{0} -} -func (m *QueryRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRequest.Merge(m, src) -} -func (m *QueryRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRequest proto.InternalMessageInfo - -type QueryResponse struct { - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` - Value github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,3,opt,name=value,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"value"` -} - -func (m *QueryResponse) Reset() { *m = QueryResponse{} } -func (m *QueryResponse) String() string { return proto.CompactTextString(m) } -func (*QueryResponse) ProtoMessage() {} -func (*QueryResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_845976b6477d0a88, []int{1} -} -func (m *QueryResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryResponse.Merge(m, src) -} -func (m *QueryResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryRequest)(nil), "persistence_sdk.modules.splits.internal.queries.ownable.QueryRequest") - proto.RegisterType((*QueryResponse)(nil), "persistence_sdk.modules.splits.internal.queries.ownable.QueryResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/splits/internal/queries/ownable/query.proto", fileDescriptor_845976b6477d0a88) -} - -var fileDescriptor_845976b6477d0a88 = []byte{ - // 466 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0x31, 0x6f, 0xd4, 0x30, - 0x18, 0x86, 0xe3, 0xa2, 0xa3, 0x6d, 0x0a, 0x4b, 0xd4, 0xe1, 0x74, 0x40, 0xee, 0x14, 0x04, 0xaa, - 0x40, 0xd8, 0x52, 0x3b, 0x20, 0x75, 0x3c, 0x52, 0xa4, 0x8a, 0xa1, 0x10, 0x36, 0x96, 0x93, 0x2f, - 0xf9, 0x94, 0x1a, 0x12, 0x3b, 0xe7, 0xcf, 0x29, 0x2a, 0x03, 0x03, 0x13, 0x1b, 0x48, 0xf0, 0x03, - 0xfa, 0x47, 0x98, 0xe9, 0x58, 0x89, 0x05, 0x31, 0x9c, 0xd0, 0x1d, 0x03, 0x33, 0xbf, 0x00, 0x25, - 0x4e, 0x44, 0x74, 0x13, 0x82, 0x29, 0x7e, 0x9d, 0xf8, 0xc9, 0xe3, 0x37, 0x8e, 0xfb, 0xa0, 0x00, - 0x8d, 0x02, 0x0d, 0xc8, 0x18, 0x26, 0x98, 0xbc, 0x60, 0xb9, 0x4a, 0xca, 0x0c, 0x90, 0x61, 0x91, - 0x09, 0x83, 0x4c, 0x48, 0x03, 0x5a, 0xf2, 0x8c, 0xcd, 0x4a, 0xd0, 0x02, 0x90, 0xa9, 0x97, 0x92, - 0x4f, 0x33, 0xa8, 0xf3, 0x29, 0x2d, 0xb4, 0x32, 0xca, 0xbb, 0xbf, 0x02, 0xa1, 0x0d, 0x84, 0x5a, - 0x08, 0x6d, 0x21, 0xb4, 0x81, 0xd0, 0x06, 0x32, 0xd8, 0x4e, 0x55, 0xaa, 0x6a, 0x06, 0xab, 0x46, - 0x16, 0x37, 0xb8, 0x9e, 0x2a, 0x95, 0x66, 0xc0, 0x78, 0x21, 0x18, 0x97, 0x52, 0x19, 0x6e, 0x84, - 0x92, 0xd8, 0xdc, 0xbd, 0xb3, 0x6a, 0x8c, 0xf1, 0x31, 0xe4, 0x9c, 0x99, 0xd3, 0x02, 0x90, 0x4d, - 0x39, 0x02, 0x13, 0x89, 0x7d, 0x36, 0xf8, 0x48, 0xdc, 0x2b, 0x4f, 0x2a, 0xd1, 0x08, 0x66, 0x25, - 0xa0, 0xf1, 0x5e, 0xb9, 0x5b, 0xcd, 0xbb, 0x27, 0x62, 0x92, 0xf4, 0xc9, 0x88, 0xec, 0x6c, 0xed, - 0xde, 0xa2, 0xab, 0xfe, 0x16, 0x49, 0x6b, 0x24, 0xad, 0x90, 0xf4, 0x30, 0x1c, 0xef, 0x9d, 0xcf, - 0x87, 0xce, 0xaf, 0xf9, 0xf0, 0xee, 0x09, 0xcf, 0x44, 0xb2, 0x1f, 0x68, 0x98, 0x95, 0x42, 0x43, - 0xf2, 0xba, 0x1d, 0x8c, 0x8e, 0x2c, 0xfa, 0x30, 0x1c, 0xe5, 0x02, 0x51, 0xc8, 0x34, 0x88, 0x36, - 0x55, 0x3b, 0xb7, 0xbf, 0xf1, 0xf6, 0x6c, 0xe8, 0xfc, 0x3c, 0x1b, 0x3a, 0xc1, 0x3b, 0xe2, 0x5e, - 0x6d, 0xb4, 0xb0, 0x50, 0x12, 0xc1, 0xeb, 0xbb, 0xeb, 0x58, 0xc6, 0x31, 0x20, 0xd6, 0x4e, 0x1b, - 0x51, 0x1b, 0xbd, 0x6d, 0xb7, 0x07, 0x5a, 0x2b, 0xdd, 0x5f, 0x1b, 0x91, 0x9d, 0xcd, 0xc8, 0x06, - 0x2f, 0x74, 0x7b, 0x27, 0x3c, 0x2b, 0xa1, 0x7f, 0xa9, 0x9a, 0x1d, 0xd3, 0x4a, 0xed, 0xdb, 0x7c, - 0x78, 0x3b, 0x15, 0xe6, 0xb8, 0x9c, 0xd2, 0x58, 0xe5, 0x2c, 0x56, 0x98, 0x2b, 0x6c, 0x2e, 0xf7, - 0xaa, 0xa2, 0xec, 0x76, 0x42, 0x88, 0x23, 0xbb, 0xf8, 0x8f, 0xd1, 0xee, 0x67, 0xe2, 0xf6, 0x6a, - 0x23, 0xef, 0x13, 0x71, 0xd7, 0x0f, 0x64, 0xbd, 0x21, 0xef, 0x80, 0xfe, 0xe3, 0x87, 0xa5, 0xdd, - 0xd2, 0x07, 0x0f, 0xff, 0x17, 0x63, 0x4b, 0x0a, 0x6e, 0xbe, 0xf9, 0xf2, 0xe3, 0xc3, 0xda, 0x0d, - 0xef, 0x1a, 0xeb, 0xf0, 0xda, 0x83, 0xda, 0x2c, 0x19, 0x3f, 0x3f, 0x5f, 0xf8, 0xe4, 0x62, 0xe1, - 0x93, 0xef, 0x0b, 0x9f, 0xbc, 0x5f, 0xfa, 0xce, 0xc5, 0xd2, 0x77, 0xbe, 0x2e, 0x7d, 0xe7, 0xd9, - 0xe3, 0x4e, 0x39, 0x1d, 0xc0, 0x91, 0x84, 0x6e, 0x7c, 0x1a, 0x3e, 0xfa, 0xdb, 0x7f, 0x60, 0x7a, - 0xb9, 0x3e, 0x65, 0x7b, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0x87, 0xc6, 0xcd, 0x5d, 0x45, 0x03, - 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) { - out := new(QueryResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.splits.internal.queries.ownable.Query/Enquire", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - Enquire(context.Context, *QueryRequest) (*QueryResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Enquire(ctx context.Context, req *QueryRequest) (*QueryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Enquire not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Enquire_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Enquire(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.splits.internal.queries.ownable.Query/Enquire", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Enquire(ctx, req.(*QueryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.splits.internal.queries.ownable.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Enquire", - Handler: _Query_Enquire_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/splits/internal/queries/ownable/query.proto", -} - -func (m *QueryRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.OwnableID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Value.Size() - i -= size - if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.Error) > 0 { - i -= len(m.Error) - copy(dAtA[i:], m.Error) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Error))) - i-- - dAtA[i] = 0x12 - } - if m.Success { - i-- - if m.Success { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.OwnableID.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Success { - n += 2 - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.Value.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OwnableID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OwnableID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Success = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/splits/internal/queries/ownable/query.pb.gw.go b/modules/splits/internal/queries/ownable/query.pb.gw.go deleted file mode 100644 index 2a0f9fc34..000000000 --- a/modules/splits/internal/queries/ownable/query.pb.gw.go +++ /dev/null @@ -1,166 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: persistence_sdk/modules/splits/internal/queries/ownable/query.proto - -/* -Package ownable is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package ownable - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage - -var ( - filter_Query_Enquire_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Enquire(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Enquire(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features (such as grpc.SendHeader, etc) to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Enquire_0(rctx, inboundMarshaler, server, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Enquire_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Enquire_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"persistence", "splits", "ownable"}, "", runtime.AssumeColonVerbOpt(true))) -) - -var ( - forward_Query_Enquire_0 = runtime.ForwardResponseMessage -) diff --git a/modules/splits/internal/queries/ownable/request.go b/modules/splits/internal/queries/ownable/request.go index a123d8d84..39ba353e9 100644 --- a/modules/splits/internal/queries/ownable/request.go +++ b/modules/splits/internal/queries/ownable/request.go @@ -1,81 +1,75 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package ownable import ( "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/cosmos/cosmos-sdk/client/context" + + "github.com/AssetMantle/modules/modules/splits/internal/common" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" ) -// QueryRequest godoc +type queryRequest struct { + ids.OwnableID `json:"ownableID" valid:"required~required field ownableID missing"` +} + +var _ helpers.QueryRequest = (*queryRequest)(nil) + +// Validate godoc // @Summary Query asset using asset id -// @Descrption Able to query the asset +// @Description Able to query the asset // @Accept json // @Produce json // @Tags Splits // @Param ownableID path string true "ownable ID" -// @Success 200 {object} queryResponse "A succesful query response" -// @Failure default {object} queryResponse "An unexpected error response." +// @Success 200 {object} queryResponse "Message for a successful query response" +// @Failure default {object} queryResponse "Message for an unexpected error response." // @Router /ownable/{ownableID} [get] -var _ helpers.QueryRequest = (*QueryRequest)(nil) - -func (queryRequest QueryRequest) Validate() error { - _, Error := govalidator.ValidateStruct(queryRequest) - return Error -} - -func (queryRequest QueryRequest) FromCLI(cliCommand helpers.CLICommand, _ client.Context) helpers.QueryRequest { - return newQueryRequest(base.NewID(cliCommand.ReadString(flags.OwnableID))) +func (queryRequest queryRequest) Validate() error { + _, err := govalidator.ValidateStruct(queryRequest) + return err } -func (queryRequest QueryRequest) FromMap(vars map[string]string) helpers.QueryRequest { - return newQueryRequest(base.NewID(vars[Query.GetName()])) -} -func (queryRequest QueryRequest) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryRequest) +func (queryRequest) FromCLI(cliCommand helpers.CLICommand, _ context.CLIContext) (helpers.QueryRequest, error) { + if ownableID, err := baseIDs.ReadOwnableID(cliCommand.ReadString(constants.OwnableID)); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(ownableID), nil + } } - -func (queryRequest QueryRequest) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryRequest, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest) FromMap(vars map[string]string) (helpers.QueryRequest, error) { + if ownableID, err := baseIDs.ReadOwnableID(vars[Query.GetName()]); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(ownableID), nil } - - return queryRequest, nil } - -func (queryRequest QueryRequest) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryRequest) +func (queryRequest queryRequest) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryRequest) } - -func (queryRequest QueryRequest) LegacyAminoDecode(bytes []byte) (helpers.QueryRequest, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest queryRequest) Decode(bytes []byte) (helpers.QueryRequest, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryRequest); err != nil { + return nil, err } return queryRequest, nil } func requestPrototype() helpers.QueryRequest { - return QueryRequest{} + return queryRequest{} } - -func queryRequestFromInterface(request helpers.QueryRequest) QueryRequest { +func queryRequestFromInterface(request helpers.QueryRequest) queryRequest { switch value := request.(type) { - case QueryRequest: + case queryRequest: return value default: - return QueryRequest{} + return queryRequest{} } } - -func newQueryRequest(ownableID types.ID) helpers.QueryRequest { - return QueryRequest{OwnableID: *base.NewID(ownableID.String())} +func newQueryRequest(ownableID ids.OwnableID) helpers.QueryRequest { + return queryRequest{OwnableID: ownableID} } diff --git a/modules/splits/internal/queries/ownable/request_test.go b/modules/splits/internal/queries/ownable/request_test.go index b0247f2ec..222fc1b54 100644 --- a/modules/splits/internal/queries/ownable/request_test.go +++ b/modules/splits/internal/queries/ownable/request_test.go @@ -1,60 +1,246 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package ownable import ( - "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/common" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/spf13/viper" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/splits/internal/common" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIds "github.com/AssetMantle/modules/schema/ids/base" ) -func Test_Split_Request(t *testing.T) { +var ( + testOwnableID = baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) +) + +func Test_newQueryRequest(t *testing.T) { + type args struct { + ownableID ids.OwnableID + } + tests := []struct { + name string + args args + want helpers.QueryRequest + }{ + {"+ve", args{testOwnableID}, newQueryRequest(testOwnableID)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newQueryRequest(tt.args.ownableID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newQueryRequest() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequestFromInterface(t *testing.T) { + type args struct { + request helpers.QueryRequest + } + tests := []struct { + name string + args args + want queryRequest + }{ + {"+ve", args{newQueryRequest(testOwnableID)}, newQueryRequest(testOwnableID).(queryRequest)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := queryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("queryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} - var Codec = codec.New() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() +func Test_queryRequest_Decode(t *testing.T) { + encodedReq, err := common.Codec.MarshalJSON(newQueryRequest(testOwnableID)) + require.NoError(t, err) + encodedReq1, err1 := common.Codec.MarshalJSON(newQueryRequest(baseIds.PrototypeOwnableID())) + require.NoError(t, err1) + type fields struct { + OwnableID ids.OwnableID + } + type args struct { + bytes []byte + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testOwnableID}, args{encodedReq}, newQueryRequest(testOwnableID), false}, + {"+ve", fields{baseIds.PrototypeOwnableID()}, args{encodedReq1}, newQueryRequest(baseIds.PrototypeOwnableID()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + OwnableID: tt.fields.OwnableID, + } + got, err := queryRequest.Decode(tt.args.bytes) + if (err != nil) != tt.wantErr { + t.Errorf("Decode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Decode() got = %v, want %v", got, tt.want) + } + }) + } +} - testSplitID := base.NewID("OwnableID") - testQueryRequest := newQueryRequest(testSplitID) - require.Equal(t, nil, testQueryRequest.Validate()) - require.Equal(t, queryRequest{}, requestPrototype()) +func Test_queryRequest_Encode(t *testing.T) { + encodedReq, err := common.Codec.MarshalJSON(newQueryRequest(testOwnableID)) + require.NoError(t, err) + encodedReq1, err1 := common.Codec.MarshalJSON(newQueryRequest(baseIds.PrototypeOwnableID())) + require.NoError(t, err1) + type fields struct { + OwnableID ids.OwnableID + } + tests := []struct { + name string + fields fields + want []byte + wantErr bool + }{ + {"+ve", fields{testOwnableID}, encodedReq, false}, + {"+ve", fields{baseIds.PrototypeOwnableID()}, encodedReq1, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + OwnableID: tt.fields.OwnableID, + } + got, err := queryRequest.Encode() + if (err != nil) != tt.wantErr { + t.Errorf("Encode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Encode() got = %v, want %v", got, tt.want) + } + }) + } +} - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.SplitID}) - cliContext := context.NewCLIContext().WithCodec(Codec) - require.Panics(t, func() { - require.Equal(t, newQueryRequest(base.NewID("")), queryRequest{}.FromCLI(cliCommand, cliContext)) - }) +func Test_queryRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.OwnableID}) + viper.Set(constants.OwnableID.GetName(), testOwnableID.String()) + type fields struct { + OwnableID ids.OwnableID + } + type args struct { + cliCommand helpers.CLICommand + in1 context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testOwnableID}, args{cliCommand, context.NewCLIContext()}, newQueryRequest(testOwnableID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + OwnableID: tt.fields.OwnableID, + } + got, err := qu.FromCLI(tt.args.cliCommand, tt.args.in1) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} +func Test_queryRequest_FromMap(t *testing.T) { vars := make(map[string]string) - vars["ownables"] = "randomString" - require.Equal(t, newQueryRequest(base.NewID("randomString")), queryRequest{}.FromMap(vars)) - - encodedRequest, Error := testQueryRequest.LegacyAminoEncode() - encodedResult, _ := common.LegacyAminoCodec.MarshalJSON(testQueryRequest) - require.Equal(t, encodedResult, encodedRequest) - require.Nil(t, Error) - - decodedRequest, Error := queryRequest{}.LegacyAminoDecode(encodedRequest) - require.Equal(t, testQueryRequest, decodedRequest) - require.Equal(t, nil, Error) - - randomDecode, _ := queryRequest{}.LegacyAminoDecode(base.NewID("").Bytes()) - require.Equal(t, nil, randomDecode) - require.Equal(t, testQueryRequest, queryRequestFromInterface(testQueryRequest)) - require.Equal(t, queryRequest{}, queryRequestFromInterface(nil)) + vars[Query.GetName()] = testOwnableID.String() + type fields struct { + OwnableID ids.OwnableID + } + type args struct { + vars map[string]string + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{testOwnableID}, args{vars}, newQueryRequest(testOwnableID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + OwnableID: tt.fields.OwnableID, + } + got, err := qu.FromMap(tt.args.vars) + if (err != nil) != tt.wantErr { + t.Errorf("FromMap() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromMap() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequest_Validate(t *testing.T) { + type fields struct { + OwnableID ids.OwnableID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testOwnableID}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + OwnableID: tt.fields.OwnableID, + } + if err := queryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryRequest + }{ + {"+ve", queryRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/internal/queries/ownable/response.go b/modules/splits/internal/queries/ownable/response.go index b7a27b07e..6f648956e 100644 --- a/modules/splits/internal/queries/ownable/response.go +++ b/modules/splits/internal/queries/ownable/response.go @@ -1,63 +1,51 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package ownable import ( - "errors" - "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + + "github.com/AssetMantle/modules/modules/splits/internal/common" + "github.com/AssetMantle/modules/schema/helpers" ) -var _ helpers.QueryResponse = (*QueryResponse)(nil) +type queryResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` + Value sdkTypes.Dec `json:"value" swaggertype:"string"` +} + +var _ helpers.QueryResponse = (*queryResponse)(nil) -func (queryResponse QueryResponse) IsSuccessful() bool { +func (queryResponse queryResponse) IsSuccessful() bool { return queryResponse.Success } -func (queryResponse QueryResponse) GetError() error { - return errors.New(queryResponse.Error) +func (queryResponse queryResponse) GetError() error { + return queryResponse.Error } -func (queryResponse QueryResponse) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryResponse) +func (queryResponse queryResponse) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryResponse) } -func (queryResponse QueryResponse) LegacyAminoDecode(bytes []byte) (helpers.QueryResponse, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error +func (queryResponse queryResponse) Decode(bytes []byte) (helpers.QueryResponse, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryResponse); err != nil { + return nil, err } - return &queryResponse, nil + return queryResponse, nil } -func (queryResponse QueryResponse) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryResponse) -} - -func (queryResponse QueryResponse) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryResponse, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error - } - return &queryResponse, nil -} - func responsePrototype() helpers.QueryResponse { - return &QueryResponse{} + return queryResponse{} } -func newQueryResponse(value sdkTypes.Dec, error error) QueryResponse { +func newQueryResponse(value sdkTypes.Dec, error error) helpers.QueryResponse { success := true if error != nil { success = false - return QueryResponse{ - Success: success, - Error: "yes", - Value: value, - } } - return QueryResponse{ + + return queryResponse{ Success: success, - Error: "no", + Error: error, Value: value, } } diff --git a/modules/splits/internal/queries/ownable/response_test.go b/modules/splits/internal/queries/ownable/response_test.go index 6fb008d0b..5981aceaf 100644 --- a/modules/splits/internal/queries/ownable/response_test.go +++ b/modules/splits/internal/queries/ownable/response_test.go @@ -1,74 +1,37 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package ownable import ( "testing" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/stretchr/testify/require" - abciTypes "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - tendermintDB "github.com/tendermint/tm-db" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/common" - "github.com/persistenceOne/persistenceSDK/schema" + "github.com/AssetMantle/modules/modules/splits/internal/common" + "github.com/AssetMantle/modules/schema/errors/constants" ) -func CreateTestInput(t *testing.T) sdkTypes.Context { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - - storeKey := sdkTypes.NewKVStoreKey("test") - paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") - - memDB := tendermintDB.NewMemDB() - commitMultiStore := store.NewCommitMultiStore(memDB) - commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - err := commitMultiStore.LoadLatestVersion() - require.Nil(t, err) - - context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ - ChainID: "test", - }, false, log.NewNopLogger()) - - return context -} - func Test_Split_Response(t *testing.T) { split := sdkTypes.SmallestDec() testQueryResponse := newQueryResponse(split, nil) - testQueryResponseWithError := newQueryResponse(split, errors.IncorrectFormat) + testQueryResponseWithError := newQueryResponse(split, constants.IncorrectFormat) require.Equal(t, true, testQueryResponse.IsSuccessful()) require.Equal(t, false, testQueryResponseWithError.IsSuccessful()) require.Equal(t, nil, testQueryResponse.GetError()) - require.Equal(t, errors.IncorrectFormat, testQueryResponseWithError.GetError()) + require.Equal(t, constants.IncorrectFormat, testQueryResponseWithError.GetError()) - encodedResponse, _ := testQueryResponse.LegacyAminoEncode() - bytes, _ := common.LegacyAminoCodec.MarshalJSON(testQueryResponse) + encodedResponse, _ := testQueryResponse.Encode() + bytes, _ := common.Codec.MarshalJSON(testQueryResponse) require.Equal(t, bytes, encodedResponse) - decodedResponse, _ := queryResponse{}.LegacyAminoDecode(bytes) + decodedResponse, _ := queryResponse{}.Decode(bytes) require.Equal(t, testQueryResponse, decodedResponse) - decodedResponse2, _ := queryResponse{}.LegacyAminoDecode([]byte{}) + decodedResponse2, _ := queryResponse{}.Decode([]byte{}) require.Equal(t, nil, decodedResponse2) require.Equal(t, queryResponse{}, responsePrototype()) diff --git a/modules/splits/internal/queries/prototype.go b/modules/splits/internal/queries/prototype.go new file mode 100644 index 000000000..5aa8cf131 --- /dev/null +++ b/modules/splits/internal/queries/prototype.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queries + +import ( + "github.com/AssetMantle/modules/modules/splits/internal/queries/ownable" + "github.com/AssetMantle/modules/modules/splits/internal/queries/split" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Queries { + return baseHelpers.NewQueries( + split.Query, + ownable.Query, + ) +} diff --git a/modules/splits/internal/queries/prototype_test.go b/modules/splits/internal/queries/prototype_test.go new file mode 100644 index 000000000..e18e26466 --- /dev/null +++ b/modules/splits/internal/queries/prototype_test.go @@ -0,0 +1,27 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queries + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/splits/internal/queries/ownable" + "github.com/AssetMantle/modules/modules/splits/internal/queries/split" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Panics(t, func() { + require.Equal(t, Prototype().Get("splits").GetName(), baseHelpers.NewQueries( + split.Query, + ownable.Query, + ).Get("splits").GetName()) + require.Equal(t, Prototype().Get("ownable").GetName(), baseHelpers.NewQueries( + split.Query, + ownable.Query, + ).Get("ownable").GetName()) + }) +} diff --git a/modules/splits/internal/queries/split/grpc_query.go b/modules/splits/internal/queries/split/grpc_query.go deleted file mode 100644 index 93553d554..000000000 --- a/modules/splits/internal/queries/split/grpc_query.go +++ /dev/null @@ -1,29 +0,0 @@ -package split - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type queryServer struct { - queryKeeper -} - -var _ QueryServer = queryServer{} - -func (queryServer queryServer) Enquire(ctx context.Context, queryRequest *QueryRequest) (*QueryResponse, error) { - cntx := sdkTypes.UnwrapSDKContext(ctx) - - keyr := key.FromID(base.NewID(queryRequest.SplitID.String())) - - collection := queryServer.queryKeeper.mapper.NewCollection(cntx) - response := newQueryResponse(collection.Fetch(keyr), nil) - return &response, response.GetError() - -} - -func NewQueryServerImpl(keeper queryKeeper) QueryServer { - return &queryServer{keeper} -} diff --git a/modules/splits/internal/queries/split/keeper.go b/modules/splits/internal/queries/split/keeper.go new file mode 100644 index 000000000..b80ca1201 --- /dev/null +++ b/modules/splits/internal/queries/split/keeper.go @@ -0,0 +1,30 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package split + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/schema/helpers" +) + +type queryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.QueryKeeper = (*queryKeeper)(nil) + +func (queryKeeper queryKeeper) Enquire(context sdkTypes.Context, queryRequest helpers.QueryRequest) helpers.QueryResponse { + return newQueryResponse(queryKeeper.mapper.NewCollection(context).Fetch(key.NewKey(queryRequestFromInterface(queryRequest).SplitID)), nil) +} + +func (queryKeeper queryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + queryKeeper.mapper = mapper + return queryKeeper +} + +func keeperPrototype() helpers.QueryKeeper { + return queryKeeper{} +} diff --git a/modules/splits/internal/queries/split/keeper_test.go b/modules/splits/internal/queries/split/keeper_test.go index 3ed02977d..1cd4dfbb3 100644 --- a/modules/splits/internal/queries/split/keeper_test.go +++ b/modules/splits/internal/queries/split/keeper_test.go @@ -1,11 +1,11 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package split import ( + "fmt" + "reflect" "testing" "github.com/cosmos/cosmos-sdk/codec" @@ -18,26 +18,43 @@ import ( "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" ) -func CreateTestInput2(t *testing.T) (sdkTypes.Context, helpers.Keeper) { +type TestKeepers struct { + SplitKeeper helpers.QueryKeeper +} + +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { var Codec = codec.New() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() + storeKey := sdkTypes.NewKVStoreKey("test") paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + paramsKeeper := params.NewKeeper( + Codec, + paramsStoreKey, + paramsTransientStoreKeys, + ) + Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) @@ -51,28 +68,92 @@ func CreateTestInput2(t *testing.T) (sdkTypes.Context, helpers.Keeper) { ChainID: "test", }, false, log.NewNopLogger()) - mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) - paramsKeeper := params.NewKeeper( - Codec, - paramsStoreKey, - paramsTransientStoreKeys, - ) - Parameters := parameters.Prototype().Initialize(paramsKeeper.Subspace("test")) + keepers := TestKeepers{ + SplitKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.QueryKeeper), + } - testQueryKeeper := keeperPrototype().Initialize(mapper, Parameters, []interface{}{}) - - return context, testQueryKeeper + return context, keepers, Mapper, Parameters } -func Test_Query_Keeper_Split(t *testing.T) { - context, keepers := CreateTestInput2(t) - - ownerID := base.NewID("ownerID") - ownableID := base.NewID("ownableID") - splitID := key.NewSplitID(ownerID, ownableID) - keepers.(queryKeeper).mapper.NewCollection(context).Add(mappable.NewSplit(splitID, sdkTypes.NewDec(123))) +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryKeeper + }{ + {"+ve", queryKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - testQueryRequest := newQueryRequest(splitID) - require.Equal(t, queryResponse{Success: true, Error: nil, List: keepers.(queryKeeper).mapper.NewCollection(context).Fetch(key.FromID(splitID)).GetList()}, keepers.(queryKeeper).LegacyEnquire(context, testQueryRequest)) +func Test_queryKeeper_Enquire(t *testing.T) { + context, keepers, Mapper, _ := createTestInput(t) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testOwnerIdentityID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + splitID := baseIds.NewSplitID(testOwnerIdentityID, testOwnableID) + testRate := sdkTypes.NewDec(1) + split := baseTypes.NewSplit(testOwnerIdentityID, testOwnableID, testRate) + type fields struct { + mapper helpers.Mapper + } + type args struct { + context sdkTypes.Context + queryRequest helpers.QueryRequest + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryResponse + }{ + {"+ve", fields{Mapper}, args{context, newQueryRequest(splitID)}, newQueryResponse(keepers.SplitKeeper.(queryKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(split)), nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryKeeper := queryKeeper{ + mapper: tt.fields.mapper, + } + if got := queryKeeper.Enquire(tt.args.context, tt.args.queryRequest); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Enquire() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_queryKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + } + type args struct { + mapper helpers.Mapper + in1 helpers.Parameters + in2 []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper}, args{Mapper, Parameters, []interface{}{}}, queryKeeper{Mapper}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryKeeper := queryKeeper{ + mapper: tt.fields.mapper, + } + if got := queryKeeper.Initialize(tt.args.mapper, tt.args.in1, tt.args.in2); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/internal/queries/split/query.go b/modules/splits/internal/queries/split/query.go new file mode 100644 index 000000000..95288a630 --- /dev/null +++ b/modules/splits/internal/queries/split/query.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package split + +import ( + "github.com/AssetMantle/modules/modules/splits/internal/module" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Query = baseHelpers.NewQuery( + "splits", + "", + "", + + module.Name, + + requestPrototype, + responsePrototype, + keeperPrototype, + + constants.SplitID, +) diff --git a/modules/splits/internal/queries/split/query.pb.go b/modules/splits/internal/queries/split/query.pb.go deleted file mode 100644 index 1df240b80..000000000 --- a/modules/splits/internal/queries/split/query.pb.go +++ /dev/null @@ -1,673 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/splits/internal/queries/split/query.proto - -package split - -import ( - context "context" - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - github_com_persistenceOne_persistenceSDK_schema_helpers "github.com/persistenceOne/persistenceSDK/schema/helpers" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - _ "google.golang.org/genproto/googleapis/api/annotations" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type QueryRequest struct { - SplitID base.ID `protobuf:"bytes,1,opt,name=split_i_d,json=splitID,proto3" json:"split_i_d" valid:"required~required splitID missing"` -} - -func (m *QueryRequest) Reset() { *m = QueryRequest{} } -func (m *QueryRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRequest) ProtoMessage() {} -func (*QueryRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_5ff44211585be9f7, []int{0} -} -func (m *QueryRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRequest.Merge(m, src) -} -func (m *QueryRequest) XXX_Size() int { - return m.Size() -} -func (m *QueryRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRequest proto.InternalMessageInfo - -type QueryResponse struct { - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` - List []github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable `protobuf:"bytes,3,rep,name=list,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable" json:"list"` -} - -func (m *QueryResponse) Reset() { *m = QueryResponse{} } -func (m *QueryResponse) String() string { return proto.CompactTextString(m) } -func (*QueryResponse) ProtoMessage() {} -func (*QueryResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5ff44211585be9f7, []int{1} -} -func (m *QueryResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *QueryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *QueryResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryResponse.Merge(m, src) -} -func (m *QueryResponse) XXX_Size() int { - return m.Size() -} -func (m *QueryResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryRequest)(nil), "persistence_sdk.modules.splits.internal.queries.split.QueryRequest") - proto.RegisterType((*QueryResponse)(nil), "persistence_sdk.modules.splits.internal.queries.split.QueryResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/splits/internal/queries/split/query.proto", fileDescriptor_5ff44211585be9f7) -} - -var fileDescriptor_5ff44211585be9f7 = []byte{ - // 461 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0x31, 0x8b, 0xd4, 0x40, - 0x14, 0xc7, 0x33, 0x77, 0x9e, 0x7b, 0x1b, 0xb5, 0x09, 0x57, 0xac, 0xab, 0x24, 0x31, 0x20, 0xac, - 0x16, 0x33, 0x78, 0x62, 0x73, 0x95, 0xae, 0x2b, 0x78, 0x88, 0x8a, 0xb1, 0x13, 0x61, 0x99, 0x4d, - 0x1e, 0xd9, 0xc1, 0xec, 0x4c, 0x76, 0xde, 0x44, 0xb8, 0xc6, 0xc2, 0xca, 0x4a, 0x04, 0xbf, 0xc0, - 0x75, 0x7e, 0x04, 0x6b, 0xbb, 0x2b, 0x0f, 0x6c, 0xc4, 0x62, 0x91, 0x5d, 0x0b, 0x6b, 0x3f, 0x81, - 0x64, 0x92, 0xe0, 0xb2, 0xd5, 0xa1, 0x55, 0xe6, 0xff, 0x26, 0xfc, 0xf2, 0x7b, 0x6f, 0x26, 0xee, - 0xbd, 0x02, 0x34, 0x0a, 0x34, 0x20, 0x13, 0x18, 0x63, 0xfa, 0x8a, 0xcd, 0x54, 0x5a, 0xe6, 0x80, - 0x0c, 0x8b, 0x5c, 0x18, 0x64, 0x42, 0x1a, 0xd0, 0x92, 0xe7, 0x6c, 0x5e, 0x82, 0x16, 0x6d, 0xdd, - 0xa6, 0x23, 0x5a, 0x68, 0x65, 0x94, 0x77, 0x67, 0x03, 0x41, 0x1b, 0x04, 0xad, 0x11, 0xb4, 0x45, - 0xd0, 0x06, 0x51, 0xd7, 0xfb, 0x7b, 0x99, 0xca, 0x94, 0x25, 0xb0, 0x6a, 0x55, 0xc3, 0xfa, 0x57, - 0x33, 0xa5, 0xb2, 0x1c, 0x18, 0x2f, 0x04, 0xe3, 0x52, 0x2a, 0xc3, 0x8d, 0x50, 0x12, 0x9b, 0xdd, - 0x9b, 0x9b, 0xb6, 0x98, 0x4c, 0x61, 0xc6, 0x99, 0x39, 0x2a, 0x00, 0xd9, 0x84, 0x23, 0x30, 0x91, - 0xd6, 0xef, 0x46, 0xef, 0x89, 0x7b, 0xf1, 0x59, 0xa5, 0x19, 0xc3, 0xbc, 0x04, 0x34, 0x9e, 0x71, - 0xbb, 0xf6, 0xcb, 0x63, 0x31, 0x4e, 0x7b, 0x24, 0x24, 0x83, 0x0b, 0xfb, 0xd7, 0xe9, 0xa6, 0x7b, - 0x0d, 0xa4, 0x16, 0x48, 0x2b, 0x20, 0x3d, 0x1c, 0x0d, 0x6f, 0x9d, 0x2c, 0x02, 0xe7, 0xf7, 0x22, - 0xb8, 0xf1, 0x9a, 0xe7, 0x22, 0x3d, 0x88, 0x34, 0xcc, 0x4b, 0xa1, 0x21, 0x7d, 0xd3, 0x2e, 0x42, - 0x0b, 0x3e, 0x1c, 0x85, 0x33, 0x81, 0x28, 0x64, 0x16, 0xc5, 0x9d, 0xa6, 0x72, 0xb0, 0xfb, 0xee, - 0x38, 0x70, 0x7e, 0x1d, 0x07, 0x4e, 0xf4, 0x89, 0xb8, 0x97, 0x1a, 0x21, 0x2c, 0x94, 0x44, 0xf0, - 0x7a, 0x6e, 0x07, 0xcb, 0x24, 0x01, 0x44, 0xeb, 0xb3, 0x1b, 0xb7, 0xd1, 0xdb, 0x73, 0x77, 0x40, - 0x6b, 0xa5, 0x7b, 0x5b, 0x21, 0x19, 0x74, 0xe3, 0x3a, 0x78, 0x2f, 0xdd, 0x73, 0xb9, 0x40, 0xd3, - 0xdb, 0x0e, 0xb7, 0x07, 0xdd, 0xe1, 0xc3, 0xca, 0xea, 0xfb, 0x22, 0xb8, 0x9b, 0x09, 0x33, 0x2d, - 0x27, 0x34, 0x51, 0x33, 0xb6, 0xd6, 0xce, 0x53, 0x09, 0xeb, 0xf1, 0xf9, 0xe8, 0x51, 0x3b, 0xad, - 0x29, 0xe4, 0xd5, 0x06, 0x7d, 0xcc, 0x8b, 0x82, 0x4f, 0x72, 0x88, 0x2d, 0xf5, 0xaf, 0xe9, 0xfe, - 0x17, 0xe2, 0xee, 0x58, 0x53, 0xef, 0x33, 0x71, 0x3b, 0x0f, 0xa4, 0x6d, 0xd2, 0xbb, 0x4f, 0xff, - 0xe9, 0xa0, 0xe9, 0xfa, 0x21, 0xf4, 0x47, 0xff, 0x07, 0xa9, 0x07, 0x17, 0x5d, 0x7b, 0xfb, 0xf5, - 0xe7, 0xc7, 0xad, 0x2b, 0xde, 0xe5, 0xf5, 0x0e, 0xdb, 0x2b, 0x6b, 0x1f, 0xc3, 0xe9, 0xc9, 0xd2, - 0x27, 0xa7, 0x4b, 0x9f, 0xfc, 0x58, 0xfa, 0xe4, 0xc3, 0xca, 0x77, 0x4e, 0x57, 0xbe, 0xf3, 0x6d, - 0xe5, 0x3b, 0x2f, 0x9e, 0x9c, 0x79, 0x5e, 0x67, 0xfa, 0x17, 0x26, 0xe7, 0xed, 0x7d, 0xbb, 0xfd, - 0x27, 0x00, 0x00, 0xff, 0xff, 0x0d, 0x62, 0x10, 0xc2, 0x4b, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Enquire(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) { - out := new(QueryResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.splits.internal.queries.split.Query/Enquire", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - Enquire(context.Context, *QueryRequest) (*QueryResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} - -func (*UnimplementedQueryServer) Enquire(ctx context.Context, req *QueryRequest) (*QueryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Enquire not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Enquire_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Enquire(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.splits.internal.queries.split.Query/Enquire", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Enquire(ctx, req.(*QueryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.splits.internal.queries.split.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Enquire", - Handler: _Query_Enquire_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/splits/internal/queries/split/query.proto", -} - -func (m *QueryRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.SplitID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.List) > 0 { - for iNdEx := len(m.List) - 1; iNdEx >= 0; iNdEx-- { - { - size := m.List[iNdEx].Size() - i -= size - if _, err := m.List[iNdEx].MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Error) > 0 { - i -= len(m.Error) - copy(dAtA[i:], m.Error) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Error))) - i-- - dAtA[i] = 0x12 - } - if m.Success { - i-- - if m.Success { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *QueryRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.SplitID.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Success { - n += 2 - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - if len(m.List) > 0 { - for _, e := range m.List { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *QueryRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SplitID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.SplitID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *QueryResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Success", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Success = bool(v != 0) - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field List", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var v github_com_persistenceOne_persistenceSDK_schema_helpers.Mappable - m.List = append(m.List, v) - if err := m.List[len(m.List)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/splits/internal/queries/split/query.pb.gw.go b/modules/splits/internal/queries/split/query.pb.gw.go deleted file mode 100644 index 18a3c1de0..000000000 --- a/modules/splits/internal/queries/split/query.pb.gw.go +++ /dev/null @@ -1,166 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: persistence_sdk/modules/splits/internal/queries/split/query.proto - -/* -Package split is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package split - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var _ codes.Code -var _ io.Reader -var _ status.Status -var _ = runtime.String -var _ = utilities.NewDoubleArray -var _ = descriptor.ForMessage - -var ( - filter_Query_Enquire_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} -) - -func request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Enquire(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err - -} - -func local_request_Query_Enquire_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRequest - var metadata runtime.ServerMetadata - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_Enquire_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Enquire(ctx, &protoReq) - return msg, metadata, err - -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features (such as grpc.SendHeader, etc) to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Enquire_0(rctx, inboundMarshaler, server, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - - mux.Handle("GET", pattern_Query_Enquire_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Enquire_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Enquire_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - - }) - - return nil -} - -var ( - pattern_Query_Enquire_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"persistence", "splits", "split"}, "", runtime.AssumeColonVerbOpt(true))) -) - -var ( - forward_Query_Enquire_0 = runtime.ForwardResponseMessage -) diff --git a/modules/splits/internal/queries/split/request.go b/modules/splits/internal/queries/split/request.go index 21049a602..6b182194c 100644 --- a/modules/splits/internal/queries/split/request.go +++ b/modules/splits/internal/queries/split/request.go @@ -1,76 +1,75 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package split import ( "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/cosmos/cosmos-sdk/client/context" + + "github.com/AssetMantle/modules/modules/splits/internal/common" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" ) -var _ helpers.QueryRequest = (*QueryRequest)(nil) +type queryRequest struct { + ids.SplitID `json:"splitID" valid:"required~required field splitID missing"` +} + +var _ helpers.QueryRequest = (*queryRequest)(nil) -// QueryRequest godoc +// Validate godoc // @Summary Query split using split id -// @Descrption Able to query the asset +// @Description Able to query the asset // @Accept json // @Produce json // @Tags Splits // @Param splitID path string true "split ID" -// @Success 200 {object} queryResponse "A successful query response" -// @Failure default {object} queryResponse "An unexpected error response." +// @Success 200 {object} queryResponse "Message for a successful query response" +// @Failure default {object} queryResponse "Message for an unexpected error response." // @Router /splits/splits/{splitID} [get] -func (queryRequest QueryRequest) Validate() error { - _, Error := govalidator.ValidateStruct(queryRequest) - return Error +func (queryRequest queryRequest) Validate() error { + _, err := govalidator.ValidateStruct(queryRequest) + return err } -func (queryRequest QueryRequest) FromCLI(cliCommand helpers.CLICommand, _ client.Context) helpers.QueryRequest { - return newQueryRequest(base.NewID(cliCommand.ReadString(flags.SplitID))) -} -func (queryRequest QueryRequest) FromMap(vars map[string]string) helpers.QueryRequest { - return newQueryRequest(base.NewID(vars[Query.GetName()])) -} -func (queryRequest QueryRequest) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryRequest) +func (queryRequest) FromCLI(cliCommand helpers.CLICommand, _ context.CLIContext) (helpers.QueryRequest, error) { + if splitID, err := baseIDs.ReadSplitID(cliCommand.ReadString(constants.SplitID)); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(splitID), nil + } } - -func (queryRequest QueryRequest) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryRequest, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest) FromMap(vars map[string]string) (helpers.QueryRequest, error) { + if splitID, err := baseIDs.ReadSplitID(vars[Query.GetName()]); err != nil { + return queryRequest{}, err + } else { + return newQueryRequest(splitID), nil } - - return queryRequest, nil } -func (queryRequest QueryRequest) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryRequest) +func (queryRequest queryRequest) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryRequest) } -func (queryRequest QueryRequest) LegacyAminoDecode(bytes []byte) (helpers.QueryRequest, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryRequest); Error != nil { - return nil, Error +func (queryRequest queryRequest) Decode(bytes []byte) (helpers.QueryRequest, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryRequest); err != nil { + return nil, err } return queryRequest, nil } func requestPrototype() helpers.QueryRequest { - return QueryRequest{} + return queryRequest{} } -func queryRequestFromInterface(request helpers.QueryRequest) QueryRequest { +func queryRequestFromInterface(request helpers.QueryRequest) queryRequest { switch value := request.(type) { - case QueryRequest: + case queryRequest: return value default: - return QueryRequest{} + return queryRequest{} } } -func newQueryRequest(splitID types.ID) helpers.QueryRequest { - return QueryRequest{SplitID: *base.NewID(splitID.String())} +func newQueryRequest(splitID ids.SplitID) helpers.QueryRequest { + return queryRequest{SplitID: splitID} } diff --git a/modules/splits/internal/queries/split/request_test.go b/modules/splits/internal/queries/split/request_test.go index cf13899d2..13b208040 100644 --- a/modules/splits/internal/queries/split/request_test.go +++ b/modules/splits/internal/queries/split/request_test.go @@ -1,58 +1,255 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package split import ( - "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/common" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/spf13/viper" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/splits/internal/common" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" ) -func Test_Split_Request(t *testing.T) { +var ( + immutables = baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables = baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID = baseIds.NewClassificationID(immutables, mutables) + testOwnerIdentityID = baseIds.NewIdentityID(classificationID, immutables) + testOwnableID = baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + splitID = baseIds.NewSplitID(testOwnerIdentityID, testOwnableID) +) + +func Test_newQueryRequest(t *testing.T) { + type args struct { + splitID ids.SplitID + } + tests := []struct { + name string + args args + want helpers.QueryRequest + }{ + {"+ve", args{splitID}, newQueryRequest(splitID)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newQueryRequest(tt.args.splitID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newQueryRequest() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequestFromInterface(t *testing.T) { + type args struct { + request helpers.QueryRequest + } + tests := []struct { + name string + args args + want queryRequest + }{ + {"+ve", args{newQueryRequest(splitID)}, newQueryRequest(splitID).(queryRequest)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := queryRequestFromInterface(tt.args.request); !reflect.DeepEqual(got, tt.want) { + t.Errorf("queryRequestFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() +func Test_queryRequest_Decode(t *testing.T) { + encodedReq, err := common.Codec.MarshalJSON(newQueryRequest(splitID)) + require.NoError(t, err) + encodedReq1, err1 := common.Codec.MarshalJSON(newQueryRequest(baseIds.PrototypeSplitID())) + require.NoError(t, err1) + type fields struct { + SplitID ids.SplitID + } + type args struct { + bytes []byte + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{splitID}, args{encodedReq}, newQueryRequest(splitID), false}, + {"+ve", fields{baseIds.PrototypeSplitID()}, args{encodedReq1}, newQueryRequest(baseIds.PrototypeSplitID()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + SplitID: tt.fields.SplitID, + } + got, err := queryRequest.Decode(tt.args.bytes) + if (err != nil) != tt.wantErr { + t.Errorf("Decode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Decode() got = %v, want %v", got, tt.want) + } + }) + } +} - testSplitID := base.NewID("SplitID") - testQueryRequest := newQueryRequest(testSplitID) - require.Equal(t, nil, testQueryRequest.Validate()) - require.Equal(t, queryRequest{}, requestPrototype()) +func Test_queryRequest_Encode(t *testing.T) { + encodedReq, err := common.Codec.MarshalJSON(newQueryRequest(splitID)) + require.NoError(t, err) + encodedReq1, err1 := common.Codec.MarshalJSON(newQueryRequest(baseIds.PrototypeSplitID())) + require.NoError(t, err1) + type fields struct { + SplitID ids.SplitID + } + tests := []struct { + name string + fields fields + want []byte + wantErr bool + }{ + {"+ve", fields{splitID}, encodedReq, false}, + {"+ve", fields{baseIds.PrototypeSplitID()}, encodedReq1, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + SplitID: tt.fields.SplitID, + } + got, err := queryRequest.Encode() + if (err != nil) != tt.wantErr { + t.Errorf("Encode() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Encode() got = %v, want %v", got, tt.want) + } + }) + } +} - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.SplitID}) - cliContext := context.NewCLIContext().WithCodec(Codec) - require.Equal(t, newQueryRequest(base.NewID("")), queryRequest{}.FromCLI(cliCommand, cliContext)) +func Test_queryRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.SplitID}) + viper.Set(constants.SplitID.GetName(), splitID.String()) + type fields struct { + SplitID ids.SplitID + } + type args struct { + cliCommand helpers.CLICommand + in1 context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{splitID}, args{cliCommand, context.NewCLIContext()}, newQueryRequest(splitID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + SplitID: tt.fields.SplitID, + } + got, err := qu.FromCLI(tt.args.cliCommand, tt.args.in1) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} +func Test_queryRequest_FromMap(t *testing.T) { vars := make(map[string]string) - vars["splits"] = "randomString" - require.Equal(t, newQueryRequest(base.NewID("randomString")), queryRequest{}.FromMap(vars)) - - encodedRequest, Error := testQueryRequest.LegacyAminoEncode() - encodedResult, _ := common.LegacyAminoCodec.MarshalJSON(testQueryRequest) - require.Equal(t, encodedResult, encodedRequest) - require.Nil(t, Error) - - decodedRequest, Error := queryRequest{}.LegacyAminoDecode(encodedRequest) - require.Equal(t, testQueryRequest, decodedRequest) - require.Equal(t, nil, Error) - - randomDecode, _ := queryRequest{}.LegacyAminoDecode(base.NewID("").Bytes()) - require.Equal(t, nil, randomDecode) - require.Equal(t, testQueryRequest, queryRequestFromInterface(testQueryRequest)) - require.Equal(t, queryRequest{}, queryRequestFromInterface(nil)) + vars[Query.GetName()] = splitID.String() + type fields struct { + SplitID ids.SplitID + } + type args struct { + vars map[string]string + } + tests := []struct { + name string + fields fields + args args + want helpers.QueryRequest + wantErr bool + }{ + {"+ve", fields{splitID}, args{vars}, newQueryRequest(splitID), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + qu := queryRequest{ + SplitID: tt.fields.SplitID, + } + got, err := qu.FromMap(tt.args.vars) + if (err != nil) != tt.wantErr { + t.Errorf("FromMap() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromMap() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_queryRequest_Validate(t *testing.T) { + type fields struct { + SplitID ids.SplitID + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{splitID}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queryRequest := queryRequest{ + SplitID: tt.fields.SplitID, + } + if err := queryRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.QueryRequest + }{ + {"+ve", queryRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/internal/queries/split/response.go b/modules/splits/internal/queries/split/response.go index 0ad9ad022..01b74a7d9 100644 --- a/modules/splits/internal/queries/split/response.go +++ b/modules/splits/internal/queries/split/response.go @@ -1,64 +1,49 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package split import ( - "errors" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/common" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/modules/splits/internal/common" + "github.com/AssetMantle/modules/schema/helpers" ) -var _ helpers.QueryResponse = (*QueryResponse)(nil) +type queryResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` + List []helpers.Mappable `json:"list"` +} + +var _ helpers.QueryResponse = (*queryResponse)(nil) -func (queryResponse QueryResponse) IsSuccessful() bool { +func (queryResponse queryResponse) IsSuccessful() bool { return queryResponse.Success } -func (queryResponse QueryResponse) GetError() error { - return errors.New(queryResponse.Error) +func (queryResponse queryResponse) GetError() error { + return queryResponse.Error } -func (queryResponse QueryResponse) LegacyAminoEncode() ([]byte, error) { - return common.LegacyAminoCodec.MarshalJSON(queryResponse) +func (queryResponse queryResponse) Encode() ([]byte, error) { + return common.Codec.MarshalJSON(queryResponse) } -func (queryResponse QueryResponse) LegacyAminoDecode(bytes []byte) (helpers.QueryResponse, error) { - if Error := common.LegacyAminoCodec.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error +func (queryResponse queryResponse) Decode(bytes []byte) (helpers.QueryResponse, error) { + if err := common.Codec.UnmarshalJSON(bytes, &queryResponse); err != nil { + return nil, err } - return &queryResponse, nil -} -func (queryResponse QueryResponse) Encode(cdc codec.JSONMarshaler) ([]byte, error) { - return cdc.MarshalJSON(&queryResponse) -} - -func (queryResponse QueryResponse) Decode(cdc codec.JSONMarshaler, bytes []byte) (helpers.QueryResponse, error) { - if Error := cdc.UnmarshalJSON(bytes, &queryResponse); Error != nil { - return nil, Error - } - return &queryResponse, nil + return queryResponse, nil } - func responsePrototype() helpers.QueryResponse { - return &QueryResponse{} + return queryResponse{} } - -func newQueryResponse(collection helpers.Collection, error error) QueryResponse { +func newQueryResponse(collection helpers.Collection, error error) helpers.QueryResponse { success := true if error != nil { success = false - return QueryResponse{ - Success: success, - Error: "yes", - List: collection.GetList(), - } } - return QueryResponse{ + + return queryResponse{ Success: success, - Error: "no", + Error: error, List: collection.GetList(), } - } diff --git a/modules/splits/internal/queries/split/response_test.go b/modules/splits/internal/queries/split/response_test.go index df500d9db..244bfa025 100644 --- a/modules/splits/internal/queries/split/response_test.go +++ b/modules/splits/internal/queries/split/response_test.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package split @@ -17,17 +15,17 @@ import ( "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mapper" - "github.com/persistenceOne/persistenceSDK/schema" + "github.com/AssetMantle/modules/modules/splits/internal/common" + "github.com/AssetMantle/modules/modules/splits/internal/mapper" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/errors/constants" ) func CreateTestInput(t *testing.T) sdkTypes.Context { var Codec = codec.New() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() @@ -56,21 +54,21 @@ func Test_Split_Response(t *testing.T) { collection := mapper.Prototype().NewCollection(context) testQueryResponse := newQueryResponse(collection, nil) - testQueryResponseWithError := newQueryResponse(collection, errors.IncorrectFormat) + testQueryResponseWithError := newQueryResponse(collection, constants.IncorrectFormat) require.Equal(t, true, testQueryResponse.IsSuccessful()) require.Equal(t, false, testQueryResponseWithError.IsSuccessful()) require.Equal(t, nil, testQueryResponse.GetError()) - require.Equal(t, errors.IncorrectFormat, testQueryResponseWithError.GetError()) + require.Equal(t, constants.IncorrectFormat, testQueryResponseWithError.GetError()) - encodedResponse, _ := testQueryResponse.LegacyAminoEncode() - bytes, _ := common.LegacyAminoCodec.MarshalJSON(testQueryResponse) + encodedResponse, _ := testQueryResponse.Encode() + bytes, _ := common.Codec.MarshalJSON(testQueryResponse) require.Equal(t, bytes, encodedResponse) - decodedResponse, _ := queryResponse{}.LegacyAminoDecode(bytes) + decodedResponse, _ := queryResponse{}.Decode(bytes) require.Equal(t, testQueryResponse, decodedResponse) - decodedResponse2, _ := queryResponse{}.LegacyAminoDecode([]byte{}) + decodedResponse2, _ := queryResponse{}.Decode([]byte{}) require.Equal(t, nil, decodedResponse2) require.Equal(t, queryResponse{}, responsePrototype()) diff --git a/modules/splits/internal/simulator/constants.go b/modules/splits/internal/simulator/constants.go new file mode 100644 index 000000000..0e23f0a61 --- /dev/null +++ b/modules/splits/internal/simulator/constants.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +const OpWeightSubmitTextProposal = "op_weight_submit_text_proposal" +const DefaultWeightTextProposal = 1 + +const OpWeightMsg = "OpWeightMsg" +const DefaultWeightMsg = 1 diff --git a/modules/splits/internal/simulator/genesis.go b/modules/splits/internal/simulator/genesis.go new file mode 100644 index 000000000..a99ae7a87 --- /dev/null +++ b/modules/splits/internal/simulator/genesis.go @@ -0,0 +1,52 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "math/rand" + + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/simulation" + + "github.com/AssetMantle/modules/modules/splits/internal/common" + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + splitsModule "github.com/AssetMantle/modules/modules/splits/internal/module" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/modules/splits/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/data" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + parameters2 "github.com/AssetMantle/modules/schema/parameters" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/schema/types/base" + baseSimulation "github.com/AssetMantle/modules/simulation/schema/types/base" +) + +func (simulator) RandomizedGenesisState(simulationState *module.SimulationState) { + var Data data.Data + + simulationState.AppParams.GetOrGenerate( + simulationState.Cdc, + dummy.ID.String(), + &Data, + simulationState.Rand, + func(rand *rand.Rand) { Data = baseData.NewDecData(sdkTypes.NewDecWithPrec(int64(rand.Intn(99)), 2)) }, + ) + + mappableList := make([]helpers.Mappable, simulationState.Rand.Intn(99)) + + for i := range mappableList { + immutables := baseQualified.NewImmutables(baseSimulation.GenerateRandomPropertyList(simulationState.Rand)) + mutables := baseQualified.NewMutables(baseSimulation.GenerateRandomPropertyList(simulationState.Rand)) + mappableList[i] = mappable.NewMappable(base.NewSplit(baseIDs.NewIdentityID(baseIDs.NewClassificationID(immutables, mutables), immutables), baseIDs.NewOwnableID(baseIDs.NewStringID(simulation.RandStringOfLength(simulationState.Rand, simulationState.Rand.Intn(99)))), simulation.RandomDecAmount(simulationState.Rand, sdkTypes.NewDec(9999999999)))) + } + + genesisState := baseHelpers.NewGenesis(key.Prototype, mappable.Prototype, nil, parameters.Prototype().GetList()).Initialize(mappableList, []parameters2.Parameter{dummy.Parameter.Mutate(Data)}) + + simulationState.GenState[splitsModule.Name] = common.Codec.MustMarshalJSON(genesisState) +} diff --git a/modules/splits/internal/simulator/operations.go b/modules/splits/internal/simulator/operations.go index e97b97359..3c3884187 100644 --- a/modules/splits/internal/simulator/operations.go +++ b/modules/splits/internal/simulator/operations.go @@ -1,20 +1,18 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( + "math/rand" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" - sdkModuleSimulation "github.com/cosmos/cosmos-sdk/x/simulation" - "math/rand" + "github.com/cosmos/cosmos-sdk/x/simulation" ) -func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec.JSONMarshaler) simulation.WeightedOperation { +func (simulator) WeightedOperations(appParams simulation.AppParams, codec *codec.Codec) simulation.WeightedOperations { var weightMsg int appParams.GetOrGenerate(codec, OpWeightMsg, &weightMsg, nil, @@ -23,10 +21,12 @@ func (simulator) WeightedOperations(appParams simulation.AppParams, codec codec. }, ) - return sdkModuleSimulation.NewWeightedOperation( - weightMsg, - simulateMsg(), - ) + return simulation.WeightedOperations{ + simulation.NewWeightedOperation( + weightMsg, + simulateMsg(), + ), + } } func simulateMsg() simulation.Operation { diff --git a/modules/splits/internal/simulator/params.go b/modules/splits/internal/simulator/params.go index a3ffd0a32..7d7d148a4 100644 --- a/modules/splits/internal/simulator/params.go +++ b/modules/splits/internal/simulator/params.go @@ -1,29 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - simTypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/common" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters/dummy" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "math/rand" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/cosmos/cosmos-sdk/x/simulation" + + "github.com/AssetMantle/modules/modules/splits/internal/common" + "github.com/AssetMantle/modules/modules/splits/internal/module" + "github.com/AssetMantle/modules/modules/splits/internal/parameters/dummy" + "github.com/AssetMantle/modules/schema/data/base" ) -func (simulator) ParamChangeList(_ *rand.Rand) []simTypes.ParamChange { - return []simTypes.ParamChange{ +func (simulator) ParamChangeList(_ *rand.Rand) []simulation.ParamChange { + return []simulation.ParamChange{ simulation.NewSimParamChange(module.Name, dummy.ID.String(), func(r *rand.Rand) string { - bytes, Error := common.LegacyAminoCodec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdkTypes.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) - if Error != nil { - panic(Error) + bytes, err := common.Codec.MarshalJSON(dummy.Parameter.Mutate(base.NewDecData(sdk.NewDecWithPrec(int64(r.Intn(99)), 2))).GetData()) + if err != nil { + panic(err) } return string(bytes) }), diff --git a/modules/splits/internal/simulator/proposals.go b/modules/splits/internal/simulator/proposals.go index e12b080e4..ce4efd54f 100644 --- a/modules/splits/internal/simulator/proposals.go +++ b/modules/splits/internal/simulator/proposals.go @@ -1,33 +1,29 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulator import ( + "math/rand" + sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/gov/types" - simulation2 "github.com/cosmos/cosmos-sdk/x/simulation" - "math/rand" + "github.com/cosmos/cosmos-sdk/x/simulation" ) func (simulator) WeightedProposalContentList() []simulation.WeightedProposalContent { return []simulation.WeightedProposalContent{ - simulation2.NewWeightedProposalContent( - OpWeightSubmitTextProposal, - DefaultWeightTextProposal, - contentSimulatorFunc(), - ), + { + AppParamsKey: OpWeightSubmitTextProposal, + DefaultWeight: DefaultWeightTextProposal, + ContentSimulatorFn: simulateTextProposalContent, + }, } } -func contentSimulatorFunc() simulation.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simulation.Account) simulation.Content { - return types.NewTextProposal( - simulation.RandStringOfLength(r, 140), - simulation.RandStringOfLength(r, 5000), - ) - } +func simulateTextProposalContent(r *rand.Rand, _ sdk.Context, _ []simulation.Account) types.Content { + return types.NewTextProposal( + simulation.RandStringOfLength(r, 140), + simulation.RandStringOfLength(r, 5000), + ) } diff --git a/modules/splits/internal/simulator/prototype.go b/modules/splits/internal/simulator/prototype.go new file mode 100644 index 000000000..3da39d69f --- /dev/null +++ b/modules/splits/internal/simulator/prototype.go @@ -0,0 +1,10 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +func Prototype() helpers.Simulator { + return newSimulator() +} diff --git a/modules/splits/internal/simulator/prototype_test.go b/modules/splits/internal/simulator/prototype_test.go new file mode 100644 index 000000000..4352a8d45 --- /dev/null +++ b/modules/splits/internal/simulator/prototype_test.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype(), newSimulator()) +} diff --git a/modules/splits/internal/simulator/simulator.go b/modules/splits/internal/simulator/simulator.go new file mode 100644 index 000000000..d963561c2 --- /dev/null +++ b/modules/splits/internal/simulator/simulator.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package simulator + +import "github.com/AssetMantle/modules/schema/helpers" + +type simulator struct{} + +var _ helpers.Simulator = (*simulator)(nil) + +func newSimulator() helpers.Simulator { + return simulator{} +} diff --git a/modules/splits/internal/transactions/prototype.go b/modules/splits/internal/transactions/prototype.go new file mode 100644 index 000000000..3b2266bb1 --- /dev/null +++ b/modules/splits/internal/transactions/prototype.go @@ -0,0 +1,20 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transactions + +import ( + "github.com/AssetMantle/modules/modules/splits/internal/transactions/send" + "github.com/AssetMantle/modules/modules/splits/internal/transactions/unwrap" + "github.com/AssetMantle/modules/modules/splits/internal/transactions/wrap" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Transactions { + return baseHelpers.NewTransactions( + send.Transaction, + unwrap.Transaction, + wrap.Transaction, + ) +} diff --git a/modules/splits/internal/transactions/prototype_test.go b/modules/splits/internal/transactions/prototype_test.go index ee2280205..81531b5e0 100644 --- a/modules/splits/internal/transactions/prototype_test.go +++ b/modules/splits/internal/transactions/prototype_test.go @@ -5,13 +5,14 @@ package transactions import ( "fmt" + "reflect" + "testing" + "github.com/AssetMantle/modules/modules/splits/internal/transactions/send" "github.com/AssetMantle/modules/modules/splits/internal/transactions/unwrap" "github.com/AssetMantle/modules/modules/splits/internal/transactions/wrap" "github.com/AssetMantle/modules/schema/helpers" baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" - "reflect" - "testing" ) func TestPrototype(t *testing.T) { diff --git a/modules/splits/internal/transactions/send/keeper.go b/modules/splits/internal/transactions/send/keeper.go new file mode 100644 index 000000000..da059d9fc --- /dev/null +++ b/modules/splits/internal/transactions/send/keeper.go @@ -0,0 +1,65 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package send + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/supply" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/splits/internal/utilities" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + splits := transactionKeeper.mapper.NewCollection(context) + + if _, err := utilities.SubtractSplits(splits, message.FromID, message.OwnableID, message.Value); err != nil { + return newTransactionResponse(err) + } + + if _, err := utilities.AddSplits(splits, message.ToID, message.OwnableID, message.Value); err != nil { + return newTransactionResponse(err) + } + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case supply.Keeper: + case helpers.Auxiliary: + switch value.GetName() { + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + default: + break + } + default: + panic(constants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/splits/internal/transactions/send/keeper_test.go b/modules/splits/internal/transactions/send/keeper_test.go index 214e5fece..eea8f60b9 100644 --- a/modules/splits/internal/transactions/send/keeper_test.go +++ b/modules/splits/internal/transactions/send/keeper_test.go @@ -1,45 +1,51 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package send import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" - cryptoCodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/test" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" ) type TestKeepers struct { - SplitsKeeper helpers.TransactionKeeper + SendKeeper helpers.TransactionKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { +var ( + authenticateAuxiliary helpers.Auxiliary +) - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() @@ -60,77 +66,113 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) - verifyAuxiliary := verify.AuxiliaryMock.Initialize(Mapper, Parameters) keepers := TestKeepers{ - SplitsKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{verifyAuxiliary}).(helpers.TransactionKeeper), + SendKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), } - return context, keepers + return context, keepers, Mapper, Parameters } -func Test_transactionKeeper_Transact(t *testing.T) { +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - context, keepers := CreateTestInput(t) - defaultAddr := sdkTypes.AccAddress("addr") - verifyMockErrorAddress := sdkTypes.AccAddress("verifyError") - - fromID := base.NewID("fromID") - toID := base.NewID("toID") - ownableID := base.NewID("stake") - - keepers.SplitsKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewSplit(key.NewSplitID(fromID, ownableID), sdkTypes.NewDec(100))) - - t.Run("PositiveCase", func(t *testing.T) { - want := newTransactionResponse(nil) - if got := keepers.SplitsKeeper.Transact(context, newMessage(defaultAddr, fromID, toID, ownableID, sdkTypes.NewDec(1))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("Positive Case-Send All splits", func(t *testing.T) { - want := newTransactionResponse(nil) - if got := keepers.SplitsKeeper.Transact(context, newMessage(defaultAddr, toID, fromID, ownableID, sdkTypes.NewDec(1))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase-Verify Identity Failure", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.SplitsKeeper.Transact(context, newMessage(verifyMockErrorAddress, fromID, toID, ownableID, sdkTypes.NewDec(1))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase-Negative Value exchange", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(errors.NotAuthorized) - if got := keepers.SplitsKeeper.Transact(context, newMessage(defaultAddr, fromID, toID, ownableID, sdkTypes.NewDec(-1))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase-Value not found", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(errors.EntityNotFound) - if got := keepers.SplitsKeeper.Transact(context, newMessage(defaultAddr, base.NewID("fakeFromID"), toID, ownableID, sdkTypes.NewDec(1))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase-Send More than available splits", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(errors.NotAuthorized) - if got := keepers.SplitsKeeper.Transact(context, newMessage(defaultAddr, fromID, toID, ownableID, sdkTypes.NewDec(101))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters := createTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper, Parameters, authenticateAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, authenticateAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters := createTestInput(t) + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + fromID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + testRate := sdkTypes.NewDec(1) + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + split := baseTypes.NewSplit(fromID, testOwnableID, testRate) + keepers.SendKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(split)) + // keepers.SendKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(split)) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + context sdkTypes.Context + msg sdkTypes.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, Parameters, authenticateAuxiliary}, args{context, newMessage(fromAccAddress, fromID, fromID, testOwnableID, testRate)}, newTransactionResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/internal/transactions/send/message.go b/modules/splits/internal/transactions/send/message.go index 98a37b8dd..f57e1f352 100644 --- a/modules/splits/internal/transactions/send/message.go +++ b/modules/splits/internal/transactions/send/message.go @@ -1,71 +1,68 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package send import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/splits/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + ToID ids.IdentityID `json:"toID" valid:"required~required field toID missing"` + ids.OwnableID `json:"ownableID" valid:"required~required field ownableID missing"` + Value sdkTypes.Dec `json:"value" valid:"required~required field value missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, toID types.ID, ownableID types.ID, value sdkTypes.Dec) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - ToID: *base.NewID(toID.String()), - OwnableID: *base.NewID(ownableID.String()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, toID ids.IdentityID, ownableID ids.OwnableID, value sdkTypes.Dec) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + ToID: toID, + OwnableID: ownableID, Value: value, } } diff --git a/modules/splits/internal/transactions/send/message.pb.go b/modules/splits/internal/transactions/send/message.pb.go deleted file mode 100644 index 6f69a1cb9..000000000 --- a/modules/splits/internal/transactions/send/message.pb.go +++ /dev/null @@ -1,727 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/splits/internal/transactions/send/message.proto - -package send - -import ( - context "context" - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - ToID base.ID `protobuf:"bytes,3,opt,name=to_i_d,json=toID,proto3" json:"to_i_d" valid:"required~required field ToID missing"` - OwnableID base.ID `protobuf:"bytes,4,opt,name=ownable_i_d,json=ownableID,proto3" json:"ownable_i_d" valid:"required~required field OwnableID missing"` - Value github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=value,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"value" valid:"required~required field Value missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_3ea99a8a18df92f7, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_3ea99a8a18df92f7, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.splits.internal.transactions.send.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.splits.internal.transactions.send.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/splits/internal/transactions/send/message.proto", fileDescriptor_3ea99a8a18df92f7) -} - -var fileDescriptor_3ea99a8a18df92f7 = []byte{ - // 511 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x94, 0x4f, 0x6b, 0x13, 0x41, - 0x18, 0xc6, 0x77, 0x6c, 0x12, 0xdb, 0xe9, 0x6d, 0x55, 0x08, 0x39, 0xec, 0x86, 0x80, 0x52, 0xc4, - 0xce, 0x60, 0x15, 0xa1, 0xbd, 0x35, 0x44, 0x25, 0x48, 0x2d, 0xa4, 0xc5, 0x83, 0x97, 0xb0, 0xd9, - 0x79, 0xb3, 0x1d, 0xdc, 0x9d, 0x49, 0xf7, 0x9d, 0xb4, 0x78, 0x50, 0x3c, 0x7a, 0x11, 0xf4, 0xee, - 0xa1, 0x07, 0x3f, 0x4c, 0x8f, 0x3d, 0x8a, 0x87, 0x20, 0xc9, 0xc5, 0x73, 0x3e, 0x81, 0xec, 0x9f, - 0x90, 0x25, 0x0a, 0x49, 0xf5, 0x34, 0xb3, 0xc3, 0xf2, 0xfb, 0x3d, 0xbb, 0x3c, 0xef, 0xd0, 0xe7, - 0x03, 0x88, 0x51, 0xa2, 0x01, 0xe5, 0x43, 0x17, 0xc5, 0x1b, 0x1e, 0x69, 0x31, 0x0c, 0x01, 0x39, - 0x0e, 0x42, 0x69, 0x90, 0x4b, 0x65, 0x20, 0x56, 0x5e, 0xc8, 0x4d, 0xec, 0x29, 0xf4, 0x7c, 0x23, - 0xb5, 0x42, 0x8e, 0xa0, 0x04, 0x8f, 0x00, 0xd1, 0x0b, 0x80, 0x0d, 0x62, 0x6d, 0xb4, 0xbd, 0xbb, - 0x00, 0x62, 0x39, 0x88, 0x65, 0x20, 0x36, 0x03, 0xb1, 0x22, 0x88, 0x25, 0xa0, 0xda, 0xed, 0x40, - 0x07, 0x3a, 0xa5, 0xf0, 0x64, 0x97, 0x01, 0x6b, 0xf7, 0x17, 0x93, 0xa1, 0x7f, 0x02, 0x91, 0xc7, - 0xcd, 0xdb, 0x01, 0x20, 0xef, 0x79, 0x08, 0x5c, 0x8a, 0xec, 0xdd, 0xc6, 0xa7, 0x32, 0xbd, 0x79, - 0x90, 0xc5, 0xb1, 0xbf, 0x10, 0x5a, 0xea, 0xc7, 0x3a, 0xaa, 0x92, 0x3a, 0xd9, 0xda, 0x68, 0xbe, - 0xbb, 0x1c, 0xb9, 0xd6, 0x8f, 0x91, 0xfb, 0x34, 0x90, 0xe6, 0x64, 0xd8, 0x63, 0xbe, 0x8e, 0x78, - 0x81, 0x7c, 0xa8, 0xa0, 0xf8, 0x78, 0xd4, 0x7a, 0xf1, 0xa7, 0x87, 0xed, 0xfb, 0xfe, 0xbe, 0x10, - 0x31, 0x20, 0x4e, 0x47, 0xee, 0x83, 0x33, 0x2f, 0x94, 0x62, 0xaf, 0x11, 0xc3, 0xe9, 0x50, 0xc6, - 0x20, 0xde, 0xcf, 0x36, 0xf5, 0xbe, 0x84, 0x50, 0xd4, 0x9f, 0xc5, 0x3a, 0xaa, 0x47, 0x12, 0x51, - 0xaa, 0xa0, 0xd1, 0x49, 0xa3, 0xd8, 0xe7, 0x74, 0x3d, 0x59, 0xbb, 0xb2, 0x2b, 0xaa, 0x37, 0xea, - 0x64, 0x6b, 0x73, 0xe7, 0x2e, 0x5b, 0xfc, 0x5f, 0x99, 0x96, 0xa5, 0x5a, 0x96, 0x6a, 0xdb, 0xad, - 0xe6, 0x93, 0x24, 0xfd, 0x74, 0xe4, 0xb2, 0x15, 0xa4, 0xed, 0xd6, 0x5c, 0x5b, 0xe9, 0xa7, 0x07, - 0xf6, 0x29, 0xad, 0x18, 0x9d, 0x6a, 0xd7, 0xae, 0xa3, 0x7d, 0x9c, 0x6b, 0x97, 0x7d, 0xeb, 0xb1, - 0x2e, 0x4a, 0x4b, 0x46, 0xb7, 0x5b, 0xf6, 0x07, 0x42, 0x37, 0xf5, 0xb9, 0xf2, 0x7a, 0x21, 0xa4, - 0xe2, 0xd2, 0x75, 0xc4, 0xbb, 0xb9, 0xf8, 0xe1, 0x12, 0xf1, 0x61, 0x26, 0x28, 0xda, 0x37, 0xf4, - 0xec, 0xcc, 0x1e, 0xd2, 0xf2, 0x99, 0x17, 0x0e, 0xa1, 0x5a, 0x4e, 0x2b, 0xd0, 0xcd, 0x2b, 0x70, - 0xaf, 0x50, 0x01, 0x5f, 0x63, 0xa4, 0x31, 0x5f, 0xb6, 0x93, 0x7a, 0x65, 0x41, 0x5a, 0xe0, 0x4f, - 0x47, 0xee, 0xf6, 0x12, 0xfd, 0xab, 0x84, 0x3e, 0x57, 0x67, 0xb6, 0xbd, 0xf5, 0x8f, 0x17, 0xae, - 0xf5, 0xeb, 0xc2, 0xb5, 0x1a, 0x77, 0xe8, 0xad, 0xe3, 0x79, 0xcd, 0x3b, 0x80, 0x03, 0xad, 0x10, - 0x76, 0xbe, 0x11, 0xba, 0x76, 0x80, 0x81, 0xfd, 0x95, 0xd0, 0xd2, 0x11, 0x28, 0x61, 0x37, 0xd9, - 0x3f, 0x4f, 0x0d, 0xcb, 0xfb, 0x5e, 0x7b, 0xf9, 0x1f, 0x8c, 0xbf, 0x84, 0x6c, 0x58, 0xcd, 0xf0, - 0x72, 0xec, 0x90, 0xab, 0xb1, 0x43, 0x7e, 0x8e, 0x1d, 0xf2, 0x79, 0xe2, 0x58, 0x57, 0x13, 0xc7, - 0xfa, 0x3e, 0x71, 0xac, 0xd7, 0x9d, 0x95, 0x87, 0x68, 0xe5, 0x6b, 0xa4, 0x57, 0x49, 0x47, 0xf8, - 0xd1, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0xb4, 0x5d, 0xdf, 0xf8, 0x8a, 0x04, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Send(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Send(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.splits.internal.transactions.send.Msg/Send", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Send(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Send(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Send not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Send_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Send(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.splits.internal.transactions.send.Msg/Send", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Send(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.splits.internal.transactions.send.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Send", - Handler: _Msg_Send_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/splits/internal/transactions/send/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Value.Size() - i -= size - if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - { - size, err := m.OwnableID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.ToID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.ToID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.OwnableID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.Value.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ToID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ToID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OwnableID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OwnableID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/splits/internal/transactions/send/message_test.go b/modules/splits/internal/transactions/send/message_test.go index 7842c9beb..37b05a72d 100644 --- a/modules/splits/internal/transactions/send/message_test.go +++ b/modules/splits/internal/transactions/send/message_test.go @@ -1,40 +1,264 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package send import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/splits/internal/module" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Send_Message(t *testing.T) { - - testToID := base.NewID("toID") - testFromID := base.NewID("fromID") - testOwnableID := base.NewID("ownableID") - testSplit := sdkTypes.NewDec(2) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - testMessage := newMessage(fromAccAddress, testFromID, testToID, testOwnableID, testSplit) - require.Equal(t, message{From: fromAccAddress, FromID: testFromID, ToID: testToID, OwnableID: testOwnableID, Value: testSplit}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, message{}, messageFromInterface(nil)) - require.Equal(t, message{}, messagePrototype()) +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg types.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{newMessage(fromAccAddress, fromID, fromID, ownableID, testRate)}, message{fromAccAddress, fromID, fromID, ownableID, testRate}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + OwnableID ids.OwnableID + Value types.Dec + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, ownableID, testRate}, types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, fromID, fromID, ownableID, testRate}))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + OwnableID ids.OwnableID + Value types.Dec + } + tests := []struct { + name string + fields fields + want []types.AccAddress + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, ownableID, testRate}, []types.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + OwnableID ids.OwnableID + Value types.Dec + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, ownableID, testRate}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + OwnableID ids.OwnableID + Value types.Dec + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, ownableID, testRate}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + OwnableID ids.OwnableID + Value types.Dec + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, ownableID, testRate}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + ToID ids.IdentityID + OwnableID ids.OwnableID + Value types.Dec + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, fromID, fromID, ownableID, testRate}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from types.AccAddress + fromID ids.IdentityID + toID ids.IdentityID + ownableID ids.OwnableID + value types.Dec + } + tests := []struct { + name string + args args + want types.Msg + }{ + {"+ve", args{fromAccAddress, fromID, fromID, ownableID, testRate}, message{fromAccAddress, fromID, fromID, ownableID, testRate}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.toID, tt.args.ownableID, tt.args.value); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/internal/transactions/send/msg_server.go b/modules/splits/internal/transactions/send/msg_server.go deleted file mode 100644 index 1108c5bda..000000000 --- a/modules/splits/internal/transactions/send/msg_server.go +++ /dev/null @@ -1,37 +0,0 @@ -package send - -import ( - "context" - "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/utilities" -) - -type msgServer struct { - transactionKeeper -} - -func (msgServer msgServer) Send(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := types.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - splits := msgServer.transactionKeeper.mapper.NewCollection(ctx) - - if _, Error := utilities.SubtractSplits(splits, &message.FromID, &message.OwnableID, message.Value); Error != nil { - return nil, Error - } - - if _, Error := utilities.AddSplits(splits, &message.ToID, &message.OwnableID, message.Value); Error != nil { - return nil, Error - } - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} - -var _ MsgServer = msgServer{} diff --git a/modules/splits/internal/transactions/send/request.go b/modules/splits/internal/transactions/send/request.go index c04641e5a..ea422edc0 100644 --- a/modules/splits/internal/transactions/send/request.go +++ b/modules/splits/internal/transactions/send/request.go @@ -1,22 +1,21 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package send import ( "encoding/json" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -29,32 +28,32 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary send split transaction -// @Descrption send split transaction +// Validate godoc +// @Summary Send split transaction +// @Description Send split transaction // @Accept text/plain // @Produce json // @Tags Splits -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body body transactionRequest true "Request body to send split" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /splits/send [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.ToID), - cliCommand.ReadString(flags.OwnableID), - cliCommand.ReadString(flags.Value), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.ToID), + cliCommand.ReadString(constants.OwnableID), + cliCommand.ReadString(constants.Value), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -63,26 +62,41 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + value, err := sdkTypes.NewDecFromStr(transactionRequest.Value) + if err != nil { + return nil, err + } + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + toID, err := baseIDs.ReadIdentityID(transactionRequest.ToID) + if err != nil { + return nil, err } - value, Error := sdkTypes.NewDecFromStr(transactionRequest.Value) - if Error != nil { - return nil, Error + ownableID, err := baseIDs.ReadOwnableID(transactionRequest.OwnableID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.ToID), - base.NewID(transactionRequest.OwnableID), + fromID, + toID, + ownableID, value, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/splits/internal/transactions/send/request_test.go b/modules/splits/internal/transactions/send/request_test.go index d81f4d861..83f64e041 100644 --- a/modules/splits/internal/transactions/send/request_test.go +++ b/modules/splits/internal/transactions/send/request_test.go @@ -1,75 +1,301 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package send import ( "encoding/json" + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/spf13/viper" "github.com/stretchr/testify/require" - "testing" -) -func Test_Send_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.ToID, flags.OwnableID, flags.Value}) - cliContext := context.NewCLIContext().WithCodec(Codec) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "toID", "ownableID", "2") + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", ToID: "toID", OwnableID: "ownableID", Value: "2"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) +var ( + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = types.AccAddressFromBech32(fromAddress) + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + immutables = baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables = baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())))) + classificationID = baseIDs.NewClassificationID(immutables, mutables) + fromID = baseIDs.NewIdentityID(classificationID, immutables) + ownableID = baseIDs.NewOwnableID(baseIDs.NewStringID("ownableid")) + testRate = types.NewDec(1) +) - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", ToID: "", OwnableID: "", Value: ""}, requestFromCLI) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + toID string + ownableID string + value string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, fromID.String(), fromID.String(), ownableID.String(), testRate.String()}, transactionRequest{testBaseRequest, fromID.String(), fromID.String(), ownableID.String(), testRate.String()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.toID, tt.args.ownableID, tt.args.value); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.ToID, constants.FromID, constants.OwnableID, constants.Value}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.FromID.GetName(), fromID.String()) + viper.Set(constants.ToID.GetName(), fromID.String()) + viper.Set(constants.OwnableID.GetName(), ownableID.String()) + viper.Set(constants.Value.GetName(), testRate.String()) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + OwnableID string + Value string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), ownableID.String(), testRate.String()}, args{cliCommand, cliContext}, transactionRequest{testBaseRequest, fromID.String(), fromID.String(), ownableID.String(), testRate.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromJSON(t *testing.T) { + jsonMessage, err := json.Marshal(newTransactionRequest(testBaseRequest, fromID.String(), fromID.String(), ownableID.String(), testRate.String())) + require.NoError(t, err) + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + OwnableID string + Value string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), ownableID.String(), testRate.String()}, args{jsonMessage}, transactionRequest{testBaseRequest, fromID.String(), fromID.String(), ownableID.String(), testRate.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("toID"), base.NewID("ownableID"), sdkTypes.NewDec(2)), msg) - require.Nil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + OwnableID string + Value string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), ownableID.String(), testRate.String()}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error := newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", "toID", "ownableID", "2").MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + OwnableID string + Value string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), ownableID.String(), testRate.String()}, newMessage(fromAccAddress, fromID, fromID, ownableID, testRate), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error = newTransactionRequest(testBaseReq, "fromID", "toID", "ownableID", "randomString").MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + OwnableID string + Value string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), ownableID.String(), testRate.String()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + ToID string + OwnableID string + Value string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), fromID.String(), ownableID.String(), testRate.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + ToID: tt.fields.ToID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/splits/internal/transactions/send/response.go b/modules/splits/internal/transactions/send/response.go new file mode 100644 index 000000000..d16f15fbd --- /dev/null +++ b/modules/splits/internal/transactions/send/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package send + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/splits/internal/transactions/send/response_test.go b/modules/splits/internal/transactions/send/response_test.go new file mode 100644 index 000000000..6bc762032 --- /dev/null +++ b/modules/splits/internal/transactions/send/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package send + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Send_Response(t *testing.T) { + testTransactionResponse := newTransactionResponse(constants.IncorrectFormat) + testTransactionResponse2 := newTransactionResponse(nil) + + require.Equal(t, transactionResponse{Success: false, Error: constants.IncorrectFormat}, testTransactionResponse) + require.Equal(t, false, testTransactionResponse.IsSuccessful()) + require.Equal(t, true, testTransactionResponse2.IsSuccessful()) + + require.Equal(t, constants.IncorrectFormat, testTransactionResponse.GetError()) + require.Equal(t, nil, testTransactionResponse2.GetError()) +} diff --git a/modules/splits/internal/transactions/send/transaction.go b/modules/splits/internal/transactions/send/transaction.go new file mode 100644 index 000000000..eb4f3b074 --- /dev/null +++ b/modules/splits/internal/transactions/send/transaction.go @@ -0,0 +1,23 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package send + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "send", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + constants.FromID, + constants.ToID, + constants.OwnableID, + constants.Value, +) diff --git a/modules/splits/internal/transactions/unwrap/keeper.go b/modules/splits/internal/transactions/unwrap/keeper.go new file mode 100644 index 000000000..b79aedd81 --- /dev/null +++ b/modules/splits/internal/transactions/unwrap/keeper.go @@ -0,0 +1,67 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package unwrap + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/supply" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/splits/internal/module" + "github.com/AssetMantle/modules/modules/splits/internal/utilities" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplyKeeper supply.Keeper + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + splits := transactionKeeper.mapper.NewCollection(context) + if _, err := utilities.SubtractSplits(splits, message.FromID, message.OwnableID, sdkTypes.NewDecFromInt(message.Value)); err != nil { + return newTransactionResponse(err) + } + + if err := transactionKeeper.supplyKeeper.SendCoinsFromModuleToAccount(context, module.Name, message.From, sdkTypes.NewCoins(sdkTypes.NewCoin(message.OwnableID.String(), message.Value))); err != nil { + return newTransactionResponse(err) + } + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case supply.Keeper: + transactionKeeper.supplyKeeper = value + case helpers.Auxiliary: + switch value.GetName() { + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + default: + break + } + default: + panic(constants.UninitializedUsage) + } + } + + return transactionKeeper +} +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/splits/internal/transactions/unwrap/keeper_test.go b/modules/splits/internal/transactions/unwrap/keeper_test.go index d1ecf363d..716c25fb5 100644 --- a/modules/splits/internal/transactions/unwrap/keeper_test.go +++ b/modules/splits/internal/transactions/unwrap/keeper_test.go @@ -1,61 +1,78 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package unwrap import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/bank" - bankKeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/test" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/tendermint/tendermint/crypto/ed25519" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/modules/splits/internal/module" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" + + // "github.com/cosmos/cosmos-sdk/x/staking/keeper" + "github.com/cosmos/cosmos-sdk/x/supply" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" +) + +var ( + authenticateAuxiliary helpers.Auxiliary + delPk1 = ed25519.GenPrivKey().PubKey() + delAddr1 = sdkTypes.AccAddress(delPk1.Address()) + + // test addresses + TestAddrs = []sdkTypes.AccAddress{ + delAddr1, + } ) type TestKeepers struct { - SplitsKeeper helpers.TransactionKeeper - AccountKeeper auth.AccountKeeper - BankKeeper bankKeeper.Keeper + UnwrapKeeper helpers.TransactionKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters, supply.Keeper) { + var Codec = codec.New() + bank.RegisterCodec(Codec) + staking.RegisterCodec(Codec) + auth.RegisterCodec(Codec) + supply.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + types.RegisterCodec(Codec) // distr + schema.RegisterCodec(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) - supply.RegisterCodec(Codec) - params.RegisterCodec(Codec) - auth.RegisterCodec(Codec) Codec.Seal() storeKey := sdkTypes.NewKVStoreKey("test") paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") - authStoreKey := sdkTypes.NewKVStoreKey("testAuth") - supplyStoreKey := sdkTypes.NewKVStoreKey("testSupply") + keyAcc := sdkTypes.NewKVStoreKey(auth.StoreKey) + keyDistr := sdkTypes.NewKVStoreKey(types.StoreKey) + keyStaking := sdkTypes.NewKVStoreKey(staking.StoreKey) paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) paramsKeeper := params.NewKeeper( @@ -67,107 +84,165 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(keyDistr, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(keyStaking, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(keyAcc, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - commitMultiStore.MountStoreWithDB(authStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(supplyStoreKey, sdkTypes.StoreTypeIAVL, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) - accountKeeper := auth.NewAccountKeeper(Codec, authStoreKey, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) + feeCollectorAcc := supply.NewEmptyModuleAccount(auth.FeeCollectorName) + notBondedPool := supply.NewEmptyModuleAccount(staking.NotBondedPoolName, supply.Burner, supply.Staking) + bondPool := supply.NewEmptyModuleAccount(staking.BondedPoolName, supply.Burner, supply.Staking) + distrAcc := supply.NewEmptyModuleAccount(types.ModuleName) + splitAcc := supply.NewEmptyModuleAccount(module.Name) + + blacklistedAddrs := make(map[string]bool) + blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true + blacklistedAddrs[notBondedPool.GetAddress().String()] = true + blacklistedAddrs[bondPool.GetAddress().String()] = true + blacklistedAddrs[distrAcc.GetAddress().String()] = true + blacklistedAddrs[splitAcc.GetAddress().String()] = true + + accountKeeper := auth.NewAccountKeeper(Codec, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) + bankKeeper := bank.NewBaseKeeper(accountKeeper, paramsKeeper.Subspace(bank.DefaultParamspace), blacklistedAddrs) + + maccPerms := map[string][]string{ + auth.FeeCollectorName: nil, + types.ModuleName: nil, + module.Name: nil, + staking.NotBondedPoolName: {supply.Burner, supply.Staking}, + staking.BondedPoolName: {supply.Burner, supply.Staking}, + } + + supplyKeeper := supply.NewKeeper(Codec, storeKey, accountKeeper, bankKeeper, maccPerms) + + sk := staking.NewKeeper(Codec, keyStaking, supplyKeeper, paramsKeeper.Subspace(staking.DefaultParamspace)) + sk.SetParams(context, staking.DefaultParams()) + intToken := sdkTypes.TokensFromConsensusPower(100000000) + initCoins := sdkTypes.NewCoins(sdkTypes.NewCoin(sk.BondDenom(context), intToken)) + testCoin := sdkTypes.NewCoins(sdkTypes.NewCoin("stake", intToken)) + totalSupply := sdkTypes.NewCoins(sdkTypes.NewCoin(sk.BondDenom(context), intToken.MulRaw(int64(len(TestAddrs))))) + supplyKeeper.SetSupply(context, supply.NewSupply(totalSupply)) + + for _, addr := range TestAddrs { + _, err := bankKeeper.AddCoins(context, addr, initCoins) + require.Nil(t, err) + } + + // set module accounts + supplyKeeper.SetModuleAccount(context, feeCollectorAcc) + supplyKeeper.SetModuleAccount(context, notBondedPool) + supplyKeeper.SetModuleAccount(context, bondPool) + supplyKeeper.SetModuleAccount(context, distrAcc) + supplyKeeper.SetModuleAccount(context, splitAcc) + + _, err = bankKeeper.AddCoins(context, splitAcc.GetAddress(), testCoin) + require.Nil(t, err) - bankKeeper := bank.NewBaseKeeper(accountKeeper, paramsKeeper.Subspace(bank.DefaultParamspace), make(map[string]bool)) - supplyKeeper := supply.NewKeeper(Codec, supplyStoreKey, accountKeeper, bankKeeper, map[string][]string{module.Name: nil}) - verifyAuxiliary := verify.AuxiliaryMock.Initialize(Mapper, Parameters) keepers := TestKeepers{ - SplitsKeeper: keeperPrototype().Initialize(Mapper, Parameters, - []interface{}{verifyAuxiliary, supplyKeeper}).(helpers.TransactionKeeper), - AccountKeeper: accountKeeper, - BankKeeper: bankKeeper, - SupplyKeeper: supplyKeeper, + UnwrapKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), } - return context, keepers + return context, keepers, Mapper, Parameters, supplyKeeper } -func Test_transactionKeeper_Transact(t *testing.T) { +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - context, keepers := CreateTestInput(t) - defaultAddr := sdkTypes.AccAddress("addr") - verifyMockErrorAddress := sdkTypes.AccAddress("verifyError") - ownableID := base.NewID("stake") - fromID := base.NewID("fromID") - coins := func(amount int64) sdkTypes.Coins { - return sdkTypes.NewCoins(sdkTypes.NewCoin("stake", sdkTypes.NewInt(amount))) +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters, supplyKeeper := createTestInput(t) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplyKeeper supply.Keeper + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} } - Error := keepers.BankKeeper.SetCoins(context, defaultAddr, coins(1000)) - require.Equal(t, nil, Error) - Error = keepers.SupplyKeeper.SendCoinsFromAccountToModule(context, defaultAddr, module.Name, coins(1000)) - require.Equal(t, nil, Error) - keepers.SplitsKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewSplit(key.NewSplitID(fromID, ownableID), sdkTypes.NewDec(1000))) - - t.Run("PositiveCase- Send All", func(t *testing.T) { - want := newTransactionResponse(nil) - if got := keepers.SplitsKeeper.Transact(context, newMessage(defaultAddr, fromID, ownableID, sdkTypes.NewInt(1000))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - Error = keepers.SupplyKeeper.SendCoinsFromAccountToModule(context, defaultAddr, module.Name, coins(1000)) - require.Equal(t, nil, Error) - keepers.SplitsKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewSplit(key.NewSplitID(fromID, ownableID), sdkTypes.NewDec(1000))) - - t.Run("PositiveCase", func(t *testing.T) { - want := newTransactionResponse(nil) - if got := keepers.SplitsKeeper.Transact(context, newMessage(defaultAddr, fromID, ownableID, sdkTypes.NewInt(10))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase-Verify Identity Failure", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.SplitsKeeper.Transact(context, newMessage(verifyMockErrorAddress, fromID, ownableID, sdkTypes.NewInt(10))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase-Send Negative Balance", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(errors.NotAuthorized) - if got := keepers.SplitsKeeper.Transact(context, newMessage(defaultAddr, fromID, ownableID, sdkTypes.NewInt(-10))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase-Send More than own Balance", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(errors.InsufficientBalance) - if got := keepers.SplitsKeeper.Transact(context, newMessage(defaultAddr, fromID, ownableID, sdkTypes.NewInt(790))); !reflect.DeepEqual(got.IsSuccessful(), want.IsSuccessful()) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase-Value Not found", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(errors.EntityNotFound) - if got := keepers.SplitsKeeper.Transact(context, newMessage(defaultAddr, base.NewID("id"), ownableID, sdkTypes.NewInt(10))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - Error = keepers.SupplyKeeper.SendCoinsFromModuleToAccount(context, module.Name, defaultAddr, coins(900)) - require.Equal(t, nil, Error) - t.Run("NegativeCase-Module does not have enough coins", func(t *testing.T) { - want := newTransactionResponse(errors.InsufficientBalance) - if got := keepers.SplitsKeeper.Transact(context, newMessage(defaultAddr, fromID, ownableID, sdkTypes.NewInt(200))); !reflect.DeepEqual(got.IsSuccessful(), want.IsSuccessful()) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper, Parameters, supplyKeeper, authenticateAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, supplyKeeper, authenticateAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + supplyKeeper: tt.fields.supplyKeeper, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters, supplyKeeper := createTestInput(t) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("stake")) + testRate2 := sdkTypes.NewDec(1) + split := baseTypes.NewSplit(fromID, testOwnableID, testRate2) + keepers.UnwrapKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(split)) + + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplyKeeper supply.Keeper + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + context sdkTypes.Context + msg sdkTypes.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, Parameters, supplyKeeper, authenticateAuxiliary}, args{context, newMessage(delAddr1, fromID, testOwnableID, testRate)}, newTransactionResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + supplyKeeper: tt.fields.supplyKeeper, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/internal/transactions/unwrap/message.go b/modules/splits/internal/transactions/unwrap/message.go index c833fb36f..41bf77501 100644 --- a/modules/splits/internal/transactions/unwrap/message.go +++ b/modules/splits/internal/transactions/unwrap/message.go @@ -1,70 +1,66 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package unwrap import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/splits/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + OwnableID ids.OwnableID `json:"ownableID" valid:"required~required field ownableID missing"` + Value sdkTypes.Int `json:"value" valid:"required~required field value missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, ownableID types.ID, value sdkTypes.Int) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), - OwnableID: *base.NewID(ownableID.String()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, ownableID ids.OwnableID, value sdkTypes.Int) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, + OwnableID: ownableID, Value: value, } } diff --git a/modules/splits/internal/transactions/unwrap/message.pb.go b/modules/splits/internal/transactions/unwrap/message.pb.go deleted file mode 100644 index 77f885e4e..000000000 --- a/modules/splits/internal/transactions/unwrap/message.pb.go +++ /dev/null @@ -1,680 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/splits/internal/transactions/unwrap/message.proto - -package unwrap - -import ( - context "context" - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - OwnableID base.ID `protobuf:"bytes,3,opt,name=ownable_i_d,json=ownableID,proto3" json:"ownable_i_d" valid:"required~required field OwnableID missing"` - Value github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=value,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"value" valid:"required~required field Value missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_6898651feeee6a63, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_6898651feeee6a63, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.splits.internal.transactions.unwrap.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.splits.internal.transactions.unwrap.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/splits/internal/transactions/unwrap/message.proto", fileDescriptor_6898651feeee6a63) -} - -var fileDescriptor_6898651feeee6a63 = []byte{ - // 489 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0x4f, 0x6b, 0xd4, 0x40, - 0x18, 0xc6, 0x33, 0xb6, 0xae, 0x6d, 0x7a, 0x8b, 0x0a, 0xcb, 0x1e, 0x92, 0x10, 0x50, 0x8a, 0xd8, - 0x19, 0xac, 0x20, 0x58, 0x4f, 0x5d, 0x56, 0x61, 0x91, 0x52, 0xa9, 0xd5, 0x83, 0x97, 0x65, 0x36, - 0x79, 0x37, 0x1d, 0x4c, 0x66, 0xe2, 0xbc, 0x49, 0x17, 0x0f, 0x8a, 0x47, 0x8f, 0x7a, 0xf5, 0x54, - 0x3c, 0xfa, 0x49, 0x7a, 0xec, 0x51, 0x3c, 0x04, 0xd9, 0xbd, 0x78, 0xde, 0x4f, 0x20, 0xf9, 0xb3, - 0x6c, 0x58, 0x85, 0xb6, 0xf4, 0x34, 0x93, 0x21, 0xfc, 0x7e, 0x0f, 0xf3, 0x3e, 0x63, 0xf6, 0x13, - 0xd0, 0x28, 0x30, 0x05, 0xe9, 0xc3, 0x00, 0x83, 0xb7, 0x2c, 0x56, 0x41, 0x16, 0x01, 0x32, 0x4c, - 0x22, 0x91, 0x22, 0x13, 0x32, 0x05, 0x2d, 0x79, 0xc4, 0x52, 0xcd, 0x25, 0x72, 0x3f, 0x15, 0x4a, - 0x22, 0xcb, 0xe4, 0x58, 0xf3, 0x84, 0xc5, 0x80, 0xc8, 0x43, 0xa0, 0x89, 0x56, 0xa9, 0xb2, 0x9e, - 0x2c, 0xa1, 0x68, 0x8d, 0xa2, 0x15, 0x8a, 0xce, 0x51, 0xb4, 0x89, 0xa2, 0x15, 0xaa, 0x73, 0x2b, - 0x54, 0xa1, 0x2a, 0x39, 0xac, 0xd8, 0x55, 0xc8, 0xce, 0xbd, 0xe5, 0x74, 0xe8, 0x1f, 0x41, 0xcc, - 0x59, 0xfa, 0x3e, 0x01, 0x64, 0x43, 0x8e, 0xc0, 0x44, 0x50, 0xfd, 0xeb, 0x7d, 0x5b, 0x35, 0x6f, - 0xec, 0x55, 0x81, 0xac, 0xaf, 0xc4, 0x5c, 0x1d, 0x69, 0x15, 0xb7, 0x89, 0x4b, 0x36, 0xd7, 0xbb, - 0x1f, 0x4e, 0x73, 0xc7, 0xf8, 0x95, 0x3b, 0x4f, 0x43, 0x91, 0x1e, 0x65, 0x43, 0xea, 0xab, 0x98, - 0x35, 0xc8, 0xfb, 0x12, 0x9a, 0x9f, 0x2f, 0x7b, 0xcf, 0xff, 0xf5, 0xd0, 0x5d, 0xdf, 0xdf, 0x0d, - 0x02, 0x0d, 0x88, 0xb3, 0xdc, 0xb9, 0x7f, 0xcc, 0x23, 0x11, 0xec, 0x78, 0x1a, 0xde, 0x65, 0x42, - 0x43, 0xf0, 0x71, 0xbe, 0x71, 0x47, 0x02, 0xa2, 0xc0, 0x7d, 0xa6, 0x55, 0xec, 0xc6, 0x02, 0x51, - 0xc8, 0xd0, 0x3b, 0x28, 0xa3, 0x58, 0x63, 0x73, 0xad, 0x58, 0x07, 0x62, 0x10, 0xb4, 0xaf, 0xb9, - 0x64, 0x73, 0x63, 0xfb, 0x0e, 0x5d, 0xbe, 0xb1, 0x4a, 0x4b, 0x4b, 0x2d, 0x2d, 0xb5, 0xfd, 0x5e, - 0xf7, 0x51, 0x91, 0x7e, 0x96, 0x3b, 0xf4, 0x02, 0xd2, 0x7e, 0x6f, 0xa1, 0x6d, 0x8d, 0xca, 0x03, - 0xeb, 0x13, 0x31, 0x37, 0xd4, 0x58, 0xf2, 0x61, 0x04, 0xa5, 0x7c, 0xe5, 0x32, 0xf2, 0xc7, 0xb5, - 0xfc, 0xc1, 0x39, 0xf2, 0xfd, 0x4a, 0xd0, 0xf4, 0xaf, 0xab, 0xf9, 0x99, 0x95, 0x99, 0xd7, 0x8f, - 0x79, 0x94, 0x41, 0x7b, 0xb5, 0x9c, 0xc7, 0xa0, 0x9e, 0xc7, 0xdd, 0xc6, 0x3c, 0x7c, 0x85, 0xb1, - 0xc2, 0x7a, 0xd9, 0x2a, 0x66, 0x5d, 0x05, 0xe9, 0xcb, 0x74, 0x96, 0x3b, 0x5b, 0xe7, 0xe8, 0x5f, - 0x17, 0xf4, 0x85, 0xba, 0xb2, 0xed, 0xac, 0x7d, 0x3e, 0x71, 0x8c, 0x3f, 0x27, 0x8e, 0xe1, 0xdd, - 0x36, 0x6f, 0x1e, 0x2e, 0x5a, 0x77, 0x00, 0x98, 0x28, 0x89, 0xb0, 0xfd, 0x83, 0x98, 0x2b, 0x7b, - 0x18, 0x5a, 0xdf, 0x89, 0xd9, 0x7a, 0x55, 0x16, 0xd1, 0xea, 0xd1, 0x2b, 0xd4, 0x98, 0xd6, 0x05, - 0xec, 0xbc, 0xb8, 0x12, 0xe5, 0x3f, 0x51, 0x3d, 0xa3, 0x2b, 0x4f, 0x27, 0x36, 0x39, 0x9b, 0xd8, - 0xe4, 0xf7, 0xc4, 0x26, 0x5f, 0xa6, 0xb6, 0x71, 0x36, 0xb5, 0x8d, 0x9f, 0x53, 0xdb, 0x78, 0x73, - 0x78, 0xe1, 0x5e, 0x5f, 0xe2, 0x75, 0x0f, 0x5b, 0xe5, 0xbb, 0x7a, 0xf8, 0x37, 0x00, 0x00, 0xff, - 0xff, 0x7c, 0xc4, 0xe4, 0x72, 0x23, 0x04, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Unwrap(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Unwrap(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.splits.internal.transactions.unwrap.Msg/Unwrap", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Unwrap(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Unwrap(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Unwrap not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Unwrap_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Unwrap(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.splits.internal.transactions.unwrap.Msg/Unwrap", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Unwrap(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.splits.internal.transactions.unwrap.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Unwrap", - Handler: _Msg_Unwrap_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/splits/internal/transactions/unwrap/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Value.Size() - i -= size - if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - { - size, err := m.OwnableID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.OwnableID.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.Value.Size() - n += 1 + l + sovMessage(uint64(l)) - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OwnableID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OwnableID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/splits/internal/transactions/unwrap/message_test.go b/modules/splits/internal/transactions/unwrap/message_test.go index 1e99b53bf..6f7baed7e 100644 --- a/modules/splits/internal/transactions/unwrap/message_test.go +++ b/modules/splits/internal/transactions/unwrap/message_test.go @@ -1,39 +1,251 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package unwrap import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" - "github.com/stretchr/testify/require" + "reflect" "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/splits/internal/module" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Unwrap_Message(t *testing.T) { +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg types.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{newMessage(fromAccAddress, fromID, ownableID, testRate)}, message{fromAccAddress, fromID, ownableID, testRate}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + OwnableID ids.OwnableID + Value types.Int + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, fromID, ownableID, testRate}, types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, fromID, ownableID, testRate}))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + OwnableID ids.OwnableID + Value types.Int + } + tests := []struct { + name string + fields fields + want []types.AccAddress + }{ + {"+ve", fields{fromAccAddress, fromID, ownableID, testRate}, []types.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} - testFromID := base.NewID("fromID") - testOwnableID := base.NewID("ownableID") - testSplit := sdkTypes.NewInt(2) +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + OwnableID ids.OwnableID + Value types.Int + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, fromID, ownableID, testRate}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + me.RegisterCodec(tt.args.codec) + }) + } +} - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) +func Test_message_Route(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + OwnableID ids.OwnableID + Value types.Int + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, ownableID, testRate}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} - testMessage := newMessage(fromAccAddress, testFromID, testOwnableID, testSplit) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, OwnableID: testOwnableID, Value: testSplit}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +func Test_message_Type(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + OwnableID ids.OwnableID + Value types.Int + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, ownableID, testRate}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + OwnableID ids.OwnableID + Value types.Int + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, fromID, ownableID, testRate}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from types.AccAddress + fromID ids.IdentityID + ownableID ids.OwnableID + value types.Int + } + tests := []struct { + name string + args args + want types.Msg + }{ + {"+ve", args{fromAccAddress, fromID, ownableID, testRate}, message{fromAccAddress, fromID, ownableID, testRate}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.ownableID, tt.args.value); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/internal/transactions/unwrap/msg_server.go b/modules/splits/internal/transactions/unwrap/msg_server.go deleted file mode 100644 index 180fb29a5..000000000 --- a/modules/splits/internal/transactions/unwrap/msg_server.go +++ /dev/null @@ -1,37 +0,0 @@ -package unwrap - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/utilities" -) - -type msgServer struct { - transactionKeeper -} - -func (msgServer msgServer) Unwrap(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - splits := msgServer.transactionKeeper.mapper.NewCollection(ctx) - if _, Error := utilities.SubtractSplits(splits, &message.FromID, &message.OwnableID, sdkTypes.NewDecFromInt(message.Value)); Error != nil { - return nil, Error - } - - if Error := msgServer.transactionKeeper.bankKeeper.SendCoinsFromModuleToAccount(ctx, module.Name, message.From.AsSDKTypesAccAddress(), sdkTypes.NewCoins(sdkTypes.NewCoin(message.OwnableID.String(), message.Value))); Error != nil { - return nil, Error - } - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} - -var _ MsgServer = msgServer{} diff --git a/modules/splits/internal/transactions/unwrap/request.go b/modules/splits/internal/transactions/unwrap/request.go index 03e0742aa..1761d52c4 100644 --- a/modules/splits/internal/transactions/unwrap/request.go +++ b/modules/splits/internal/transactions/unwrap/request.go @@ -1,23 +1,22 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package unwrap import ( "encoding/json" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -29,31 +28,31 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary unwrap split transaction -// @Descrption unwrap split transaction +// Validate godoc +// @Summary Unwrap split transaction +// @Description Unwrap split transaction // @Accept text/plain // @Produce json // @Tags Splits -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body body transactionRequest true "Request body to unwrap split" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /splits/unwrap [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.OwnableID), - cliCommand.ReadString(flags.Value), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.OwnableID), + cliCommand.ReadString(constants.Value), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -62,25 +61,35 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err } value, ok := sdkTypes.NewIntFromString(transactionRequest.Value) if !ok { - return nil, xprtErrors.InvalidRequest + return nil, errorConstants.InvalidRequest + } + + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err + } + + ownableID, err := baseIDs.ReadOwnableID(transactionRequest.OwnableID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), - base.NewID(transactionRequest.OwnableID), + fromID, + ownableID, value, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/splits/internal/transactions/unwrap/request_test.go b/modules/splits/internal/transactions/unwrap/request_test.go index e536f8837..d7978097a 100644 --- a/modules/splits/internal/transactions/unwrap/request_test.go +++ b/modules/splits/internal/transactions/unwrap/request_test.go @@ -1,80 +1,288 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package unwrap import ( "encoding/json" + "fmt" + "math/big" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/spf13/viper" "github.com/stretchr/testify/require" - "testing" -) -func Test_Unwrap_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.OwnableID, flags.Value}) - cliContext := context.NewCLIContext().WithCodec(Codec) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "ownableID", "2") - - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", OwnableID: "ownableID", Value: "2"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", OwnableID: "", Value: ""}, requestFromCLI) +var ( + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = types.AccAddressFromBech32(fromAddress) + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + immutables = baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables = baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())))) + classificationID = baseIDs.NewClassificationID(immutables, mutables) + fromID = baseIDs.NewIdentityID(classificationID, immutables) + ownableID = baseIDs.NewOwnableID(baseIDs.NewStringID("ownableid")) + testRate = types.NewInt(1) +) - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + ownableID string + value string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, fromID.String(), ownableID.String(), testRate.String()}, transactionRequest{testBaseRequest, fromID.String(), ownableID.String(), testRate.String()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.ownableID, tt.args.value); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.OwnableID, constants.FromID, constants.Value}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.FromID.GetName(), fromID.String()) + viper.Set(constants.OwnableID.GetName(), ownableID.String()) + viper.Set(constants.Value.GetName(), testRate.String()) + type fields struct { + BaseReq rest.BaseReq + FromID string + OwnableID string + Value string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), ownableID.String(), testRate.String()}, args{cliCommand, cliContext}, transactionRequest{testBaseRequest, fromID.String(), ownableID.String(), testRate.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), base.NewID("ownableID"), sdkTypes.NewInt(2)), msg) - require.Nil(t, Error) +func Test_transactionRequest_FromJSON(t *testing.T) { + jsonMessage, err := json.Marshal(newTransactionRequest(testBaseRequest, fromID.String(), ownableID.String(), testRate.String())) + require.NoError(t, err) + type fields struct { + BaseReq rest.BaseReq + FromID string + OwnableID string + Value string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), ownableID.String(), testRate.String()}, args{jsonMessage}, newTransactionRequest(testBaseRequest, fromID.String(), ownableID.String(), big.NewInt(1).String()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error := newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", "ownableID", "2").MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + OwnableID string + Value string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, fromID.String(), ownableID.String(), testRate.String()}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error = newTransactionRequest(rest.BaseReq{From: fromAddress, ChainID: "test"}, "fromID", "ownableID", "2.5").MakeMsg() - require.Equal(t, xprtErrors.InvalidRequest, Error) - require.Nil(t, msg2) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + OwnableID string + Value string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), ownableID.String(), testRate.String()}, newMessage(fromAccAddress, fromID, ownableID, testRate), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error = newTransactionRequest(testBaseReq, "fromID", "ownableID", "randomString").MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + OwnableID string + Value string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, fromID.String(), ownableID.String(), testRate.String()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + OwnableID string + Value string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), ownableID.String(), testRate.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + OwnableID: tt.fields.OwnableID, + Value: tt.fields.Value, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/splits/internal/transactions/unwrap/response.go b/modules/splits/internal/transactions/unwrap/response.go new file mode 100644 index 000000000..769ddc779 --- /dev/null +++ b/modules/splits/internal/transactions/unwrap/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package unwrap + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/splits/internal/transactions/unwrap/response_test.go b/modules/splits/internal/transactions/unwrap/response_test.go new file mode 100644 index 000000000..9cf63666d --- /dev/null +++ b/modules/splits/internal/transactions/unwrap/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package unwrap + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Unwrap_Response(t *testing.T) { + testTransactionResponse := newTransactionResponse(constants.IncorrectFormat) + testTransactionResponse2 := newTransactionResponse(nil) + + require.Equal(t, transactionResponse{Success: false, Error: constants.IncorrectFormat}, testTransactionResponse) + require.Equal(t, false, testTransactionResponse.IsSuccessful()) + require.Equal(t, true, testTransactionResponse2.IsSuccessful()) + + require.Equal(t, constants.IncorrectFormat, testTransactionResponse.GetError()) + require.Equal(t, nil, testTransactionResponse2.GetError()) +} diff --git a/modules/splits/internal/transactions/unwrap/transaction.go b/modules/splits/internal/transactions/unwrap/transaction.go new file mode 100644 index 000000000..07a1e499a --- /dev/null +++ b/modules/splits/internal/transactions/unwrap/transaction.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package unwrap + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "unwrap", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + constants.FromID, + constants.OwnableID, + constants.Value, +) diff --git a/modules/splits/internal/transactions/wrap/keeper.go b/modules/splits/internal/transactions/wrap/keeper.go new file mode 100644 index 000000000..1b4a2fef0 --- /dev/null +++ b/modules/splits/internal/transactions/wrap/keeper.go @@ -0,0 +1,67 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package wrap + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/supply" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/splits/internal/module" + "github.com/AssetMantle/modules/modules/splits/internal/utilities" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +type transactionKeeper struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplyKeeper supply.Keeper + authenticateAuxiliary helpers.Auxiliary +} + +var _ helpers.TransactionKeeper = (*transactionKeeper)(nil) + +func (transactionKeeper transactionKeeper) Transact(context sdkTypes.Context, msg sdkTypes.Msg) helpers.TransactionResponse { + message := messageFromInterface(msg) + if auxiliaryResponse := transactionKeeper.authenticateAuxiliary.GetKeeper().Help(context, authenticate.NewAuxiliaryRequest(message.From, message.FromID)); !auxiliaryResponse.IsSuccessful() { + return newTransactionResponse(auxiliaryResponse.GetError()) + } + + if err := transactionKeeper.supplyKeeper.SendCoinsFromAccountToModule(context, message.From, module.Name, message.Coins); err != nil { + return newTransactionResponse(err) + } + + for _, coin := range message.Coins { + if _, err := utilities.AddSplits(transactionKeeper.mapper.NewCollection(context), message.FromID, baseIDs.NewOwnableID(baseIDs.NewStringID(coin.Denom)), sdkTypes.NewDecFromInt(coin.Amount)); err != nil { + return newTransactionResponse(err) + } + } + + return newTransactionResponse(nil) +} + +func (transactionKeeper transactionKeeper) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, auxiliaries []interface{}) helpers.Keeper { + transactionKeeper.mapper, transactionKeeper.parameters = mapper, parameters + + for _, auxiliary := range auxiliaries { + switch value := auxiliary.(type) { + case supply.Keeper: + transactionKeeper.supplyKeeper = value + case helpers.Auxiliary: + switch value.GetName() { + case authenticate.Auxiliary.GetName(): + transactionKeeper.authenticateAuxiliary = value + default: + break + } + } + } + + return transactionKeeper +} + +func keeperPrototype() helpers.TransactionKeeper { + return transactionKeeper{} +} diff --git a/modules/splits/internal/transactions/wrap/keeper_test.go b/modules/splits/internal/transactions/wrap/keeper_test.go index 5b932d512..a4f9a30d7 100644 --- a/modules/splits/internal/transactions/wrap/keeper_test.go +++ b/modules/splits/internal/transactions/wrap/keeper_test.go @@ -1,61 +1,78 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package wrap import ( + "fmt" + "reflect" + "testing" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/constants/test" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/supply" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/libs/log" tendermintDB "github.com/tendermint/tm-db" - "reflect" - "testing" + + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/modules/splits/internal/module" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +var ( + authenticateAuxiliary helpers.Auxiliary + delPk1 = ed25519.GenPrivKey().PubKey() + delAddr1 = sdkTypes.AccAddress(delPk1.Address()) + + // test addresses + TestAddrs = []sdkTypes.AccAddress{ + delAddr1, + } ) type TestKeepers struct { - SplitsKeeper helpers.TransactionKeeper - AccountKeeper auth.AccountKeeper - BankKeeper bank.Keeper + WrapKeeper helpers.TransactionKeeper } -func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { +func createTestInput(t *testing.T) (sdkTypes.Context, TestKeepers, helpers.Mapper, helpers.Parameters, supply.Keeper) { + var Codec = codec.New() + bank.RegisterCodec(Codec) + staking.RegisterCodec(Codec) + auth.RegisterCodec(Codec) + supply.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + types.RegisterCodec(Codec) // distr + schema.RegisterCodec(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) - params.RegisterCodec(Codec) - auth.RegisterCodec(Codec) Codec.Seal() storeKey := sdkTypes.NewKVStoreKey("test") paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + keyAcc := sdkTypes.NewKVStoreKey(auth.StoreKey) + keyDistr := sdkTypes.NewKVStoreKey(types.StoreKey) + keyStaking := sdkTypes.NewKVStoreKey(staking.StoreKey) paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") - authStoreKey := sdkTypes.NewKVStoreKey("testAuth") - supplyStoreKey := sdkTypes.NewKVStoreKey("testSupply") - mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) + Mapper := baseHelpers.NewMapper(key.Prototype, mappable.Prototype).Initialize(storeKey) paramsKeeper := params.NewKeeper( Codec, paramsStoreKey, @@ -65,75 +82,190 @@ func CreateTestInput(t *testing.T) (sdkTypes.Context, TestKeepers) { memDB := tendermintDB.NewMemDB() commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(keyDistr, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(keyStaking, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(keyAcc, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - commitMultiStore.MountStoreWithDB(authStoreKey, sdkTypes.StoreTypeIAVL, memDB) - commitMultiStore.MountStoreWithDB(supplyStoreKey, sdkTypes.StoreTypeIAVL, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + authenticateAuxiliary = authenticate.AuxiliaryMock.Initialize(Mapper, Parameters) context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) - accountKeeper := auth.NewAccountKeeper(Codec, authStoreKey, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) + feeCollectorAcc := supply.NewEmptyModuleAccount(auth.FeeCollectorName) + notBondedPool := supply.NewEmptyModuleAccount(staking.NotBondedPoolName, supply.Burner, supply.Staking) + bondPool := supply.NewEmptyModuleAccount(staking.BondedPoolName, supply.Burner, supply.Staking) + distrAcc := supply.NewEmptyModuleAccount(types.ModuleName) + splitAcc := supply.NewEmptyModuleAccount(module.Name) - bankKeeper := bank.NewBaseKeeper(accountKeeper, paramsKeeper.Subspace(bank.DefaultParamspace), make(map[string]bool)) - supplyKeeper := supply.NewKeeper(Codec, supplyStoreKey, accountKeeper, bankKeeper, map[string][]string{module.Name: nil}) - verifyAuxiliary := verify.AuxiliaryMock.Initialize(mapper, Parameters) - keepers := TestKeepers{ - SplitsKeeper: keeperPrototype().Initialize(mapper, Parameters, - []interface{}{verifyAuxiliary, supplyKeeper}).(helpers.TransactionKeeper), - AccountKeeper: accountKeeper, - BankKeeper: bankKeeper, + blacklistedAddrs := make(map[string]bool) + blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true + blacklistedAddrs[notBondedPool.GetAddress().String()] = true + blacklistedAddrs[bondPool.GetAddress().String()] = true + blacklistedAddrs[distrAcc.GetAddress().String()] = true + blacklistedAddrs[splitAcc.GetAddress().String()] = true + + accountKeeper := auth.NewAccountKeeper(Codec, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) + bankKeeper := bank.NewBaseKeeper(accountKeeper, paramsKeeper.Subspace(bank.DefaultParamspace), blacklistedAddrs) + + maccPerms := map[string][]string{ + auth.FeeCollectorName: nil, + types.ModuleName: nil, + module.Name: nil, + staking.NotBondedPoolName: {supply.Burner, supply.Staking}, + staking.BondedPoolName: {supply.Burner, supply.Staking}, } - return context, keepers -} + supplyKeeper := supply.NewKeeper(Codec, storeKey, accountKeeper, bankKeeper, maccPerms) -func Test_transactionKeeper_Transact(t *testing.T) { + sk := staking.NewKeeper(Codec, keyStaking, supplyKeeper, paramsKeeper.Subspace(staking.DefaultParamspace)) + sk.SetParams(context, staking.DefaultParams()) + intToken := sdkTypes.TokensFromConsensusPower(100000000) + initCoins := sdkTypes.NewCoins(sdkTypes.NewCoin(sk.BondDenom(context), intToken)) + totalSupply := sdkTypes.NewCoins(sdkTypes.NewCoin(sk.BondDenom(context), intToken.MulRaw(int64(len(TestAddrs))))) + supplyKeeper.SetSupply(context, supply.NewSupply(totalSupply)) - ctx, keepers := CreateTestInput(t) - defaultAddr := sdkTypes.AccAddress("addr") - verifyMockErrorAddress := sdkTypes.AccAddress("verifyError") + for _, addr := range TestAddrs { + _, err := bankKeeper.AddCoins(context, addr, initCoins) + require.Nil(t, err) + } + + // set module accounts + supplyKeeper.SetModuleAccount(context, feeCollectorAcc) + supplyKeeper.SetModuleAccount(context, notBondedPool) + supplyKeeper.SetModuleAccount(context, bondPool) + supplyKeeper.SetModuleAccount(context, distrAcc) + supplyKeeper.SetModuleAccount(context, splitAcc) - fromID := base.NewID("fromID") - coins := func(amount int64) sdkTypes.Coins { - return sdkTypes.NewCoins(sdkTypes.NewCoin("stake", sdkTypes.NewInt(amount))) + keepers := TestKeepers{ + WrapKeeper: keeperPrototype().Initialize(Mapper, Parameters, []interface{}{}).(helpers.TransactionKeeper), } - Error := keepers.BankKeeper.SetCoins(ctx, defaultAddr, coins(1000)) - require.Equal(t, nil, Error) - t.Run("PositiveCase", func(t *testing.T) { - want := newTransactionResponse(nil) - if got := keepers.SplitsKeeper.Transact(ctx, newMessage(defaultAddr, fromID, coins(100))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("PositiveCase- reAdd", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(nil) - if got := keepers.SplitsKeeper.Transact(ctx, newMessage(defaultAddr, fromID, coins(100))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase-Verify Identity Failure", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(test.MockError) - if got := keepers.SplitsKeeper.Transact(ctx, newMessage(verifyMockErrorAddress, fromID, coins(100))); !reflect.DeepEqual(got, want) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) - - t.Run("NegativeCase-Wrap Negative coins", func(t *testing.T) { - t.Parallel() - want := newTransactionResponse(errors.InsufficientBalance) - if got := keepers.SplitsKeeper.Transact(ctx, newMessage(defaultAddr, fromID, coins(10000))); !reflect.DeepEqual(got.IsSuccessful(), want.IsSuccessful()) { - t.Errorf("Transact() = %v, want %v", got, want) - } - }) + return context, keepers, Mapper, Parameters, supplyKeeper +} +func Test_keeperPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionKeeper + }{ + {"+ve", transactionKeeper{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := keeperPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("keeperPrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Initialize(t *testing.T) { + _, _, Mapper, Parameters, _ := createTestInput(t) + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + paramsKeeper := params.NewKeeper( + codec.New(), + paramsStoreKey, + paramsTransientStoreKeys, + ) + accountKeeper := auth.NewAccountKeeper( + codec.New(), // amino codec + paramsStoreKey, // target store + paramsKeeper.Subspace(auth.DefaultParamspace), + auth.ProtoBaseAccount, // prototype + ) + feeCollectorAcc := supply.NewEmptyModuleAccount(auth.FeeCollectorName) + notBondedPool := supply.NewEmptyModuleAccount(staking.NotBondedPoolName, supply.Burner, supply.Staking) + bondPool := supply.NewEmptyModuleAccount(staking.BondedPoolName, supply.Burner, supply.Staking) + distrAcc := supply.NewEmptyModuleAccount(types.ModuleName) + blacklistedAddrs := make(map[string]bool) + blacklistedAddrs[feeCollectorAcc.GetAddress().String()] = true + blacklistedAddrs[notBondedPool.GetAddress().String()] = true + blacklistedAddrs[bondPool.GetAddress().String()] = true + blacklistedAddrs[distrAcc.GetAddress().String()] = true + bankKeeper := bank.NewBaseKeeper(accountKeeper, paramsKeeper.Subspace(bank.DefaultParamspace), blacklistedAddrs) + maccPerms := map[string][]string{ + auth.FeeCollectorName: nil, + types.ModuleName: nil, + staking.NotBondedPoolName: {supply.Burner, supply.Staking}, + staking.BondedPoolName: {supply.Burner, supply.Staking}, + } + supplyKeeper := supply.NewKeeper(codec.Cdc, sdkTypes.NewKVStoreKey(supply.StoreKey), accountKeeper, bankKeeper, maccPerms) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplyKeeper supply.Keeper + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaries []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Keeper + }{ + {"+ve", fields{Mapper, Parameters, supplyKeeper, authenticateAuxiliary}, args{Mapper, Parameters, []interface{}{}}, transactionKeeper{Mapper, Parameters, supplyKeeper, authenticateAuxiliary}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + supplyKeeper: tt.fields.supplyKeeper, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaries); !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_transactionKeeper_Transact(t *testing.T) { + context, keepers, Mapper, Parameters, supplyKeeper := createTestInput(t) + testRate1 := sdkTypes.NewCoins(sdkTypes.NewInt64Coin("stake", 1)) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("stake")) + split := baseTypes.NewSplit(fromID, testOwnableID, sdkTypes.NewDec(1)) + keepers.WrapKeeper.(transactionKeeper).mapper.NewCollection(context).Add(mappable.NewMappable(split)) + type fields struct { + mapper helpers.Mapper + parameters helpers.Parameters + supplyKeeper supply.Keeper + authenticateAuxiliary helpers.Auxiliary + } + type args struct { + context sdkTypes.Context + msg sdkTypes.Msg + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionResponse + }{ + {"+ve", fields{Mapper, Parameters, supplyKeeper, authenticateAuxiliary}, args{context, newMessage(delAddr1, fromID, testRate1)}, newTransactionResponse(nil)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionKeeper := transactionKeeper{ + mapper: tt.fields.mapper, + parameters: tt.fields.parameters, + supplyKeeper: tt.fields.supplyKeeper, + authenticateAuxiliary: tt.fields.authenticateAuxiliary, + } + if got := transactionKeeper.Transact(tt.args.context, tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Transact() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/internal/transactions/wrap/message.go b/modules/splits/internal/transactions/wrap/message.go index a2be0e908..19092ca10 100644 --- a/modules/splits/internal/transactions/wrap/message.go +++ b/modules/splits/internal/transactions/wrap/message.go @@ -1,69 +1,64 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package wrap import ( "github.com/asaskevich/govalidator" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" - sdkTypesMsgService "github.com/cosmos/cosmos-sdk/types/msgservice" - xprtErrors "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/AssetMantle/modules/modules/splits/internal/module" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/transaction" ) -var _ helpers.Message = &Message{} +type message struct { + From sdkTypes.AccAddress `json:"from" valid:"required~required field from missing"` + FromID ids.IdentityID `json:"fromID" valid:"required~required field fromID missing"` + Coins sdkTypes.Coins `json:"coins" valid:"required~required field coins missing"` +} + +var _ sdkTypes.Msg = message{} -func (message Message) Route() string { return module.Name } -func (message Message) Type() string { return Transaction.GetName() } -func (message Message) ValidateBasic() error { - var _, Error = govalidator.ValidateStruct(message) - if Error != nil { - return errors.Wrap(xprtErrors.IncorrectMessage, Error.Error()) +func (message message) Route() string { return module.Name } +func (message message) Type() string { return Transaction.GetName() } +func (message message) ValidateBasic() error { + if _, err := govalidator.ValidateStruct(message); err != nil { + return sdkErrors.Wrap(errorConstants.IncorrectMessage, err.Error()) } return nil } -func (message Message) GetSignBytes() []byte { - return sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(message)) -} -func (message Message) GetSigners() []sdkTypes.AccAddress { - return []sdkTypes.AccAddress{message.From.AsSDKTypesAccAddress()} +func (message message) GetSignBytes() []byte { + return sdkTypes.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message)) } -func (Message) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, Message{}) +func (message message) GetSigners() []sdkTypes.AccAddress { + return []sdkTypes.AccAddress{message.From} } -func (Message) RegisterInterface(registry codecTypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdkTypes.Msg)(nil), - &Message{}, - ) - sdkTypesMsgService.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +func (message) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, message{}) } -func messageFromInterface(msg sdkTypes.Msg) Message { +func messageFromInterface(msg sdkTypes.Msg) message { switch value := msg.(type) { - case *Message: - return *value + case message: + return value default: - return Message{} + return message{} } } func messagePrototype() helpers.Message { - return &Message{} + return message{} } -func newMessage(from sdkTypes.AccAddress, fromID types.ID, coins sdkTypes.Coins) sdkTypes.Msg { - return &Message{ - From: base.NewAccAddressFromSDKTypesAccAddress(from), - FromID: *base.NewID(fromID.String()), +func newMessage(from sdkTypes.AccAddress, fromID ids.IdentityID, coins sdkTypes.Coins) sdkTypes.Msg { + return message{ + From: from, + FromID: fromID, Coins: coins, } } diff --git a/modules/splits/internal/transactions/wrap/message.pb.go b/modules/splits/internal/transactions/wrap/message.pb.go deleted file mode 100644 index d7513cfe5..000000000 --- a/modules/splits/internal/transactions/wrap/message.pb.go +++ /dev/null @@ -1,643 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/modules/splits/internal/transactions/wrap/message.proto - -package wrap - -import ( - context "context" - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - github_com_persistenceOne_persistenceSDK_schema_types_base "github.com/persistenceOne/persistenceSDK/schema/types/base" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Message struct { - From github_com_persistenceOne_persistenceSDK_schema_types_base.AccAddress `protobuf:"bytes,1,opt,name=from,proto3,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress" json:"from" valid:"required~required field From missing"` - FromID base.ID `protobuf:"bytes,2,opt,name=from_i_d,json=fromID,proto3" json:"from_i_d" valid:"required~required field FromID missing"` - Coins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,3,rep,name=coins,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Coin,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"coins" valid:"required~required field Coins missing"` -} - -func (m *Message) Reset() { *m = Message{} } -func (m *Message) String() string { return proto.CompactTextString(m) } -func (*Message) ProtoMessage() {} -func (*Message) Descriptor() ([]byte, []int) { - return fileDescriptor_1310275d9b86728f, []int{0} -} -func (m *Message) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Message) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Message.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Message) XXX_Merge(src proto.Message) { - xxx_messageInfo_Message.Merge(m, src) -} -func (m *Message) XXX_Size() int { - return m.Size() -} -func (m *Message) XXX_DiscardUnknown() { - xxx_messageInfo_Message.DiscardUnknown(m) -} - -var xxx_messageInfo_Message proto.InternalMessageInfo - -type TransactionResponse struct { -} - -func (m *TransactionResponse) Reset() { *m = TransactionResponse{} } -func (m *TransactionResponse) String() string { return proto.CompactTextString(m) } -func (*TransactionResponse) ProtoMessage() {} -func (*TransactionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_1310275d9b86728f, []int{1} -} -func (m *TransactionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *TransactionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_TransactionResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *TransactionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TransactionResponse.Merge(m, src) -} -func (m *TransactionResponse) XXX_Size() int { - return m.Size() -} -func (m *TransactionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TransactionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TransactionResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Message)(nil), "persistence_sdk.modules.splits.internal.transactions.wrap.Message") - proto.RegisterType((*TransactionResponse)(nil), "persistence_sdk.modules.splits.internal.transactions.wrap.TransactionResponse") -} - -func init() { - proto.RegisterFile("persistence_sdk/modules/splits/internal/transactions/wrap/message.proto", fileDescriptor_1310275d9b86728f) -} - -var fileDescriptor_1310275d9b86728f = []byte{ - // 472 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0x31, 0x8b, 0xd4, 0x40, - 0x14, 0xc7, 0x33, 0xee, 0x79, 0xde, 0xc5, 0x2e, 0x2a, 0x2c, 0x5b, 0x24, 0x21, 0x20, 0x2e, 0xe2, - 0xcd, 0xc0, 0x09, 0x82, 0xd7, 0x5d, 0x5c, 0x95, 0x43, 0x4e, 0x61, 0x15, 0x04, 0x9b, 0x65, 0x36, - 0xf3, 0x36, 0x37, 0x98, 0xcc, 0xc4, 0x79, 0x59, 0x0f, 0x0b, 0xad, 0x2d, 0x2c, 0xb4, 0xb7, 0x38, - 0xd0, 0xca, 0x0f, 0x22, 0x57, 0x5e, 0x29, 0x16, 0x51, 0x76, 0x1b, 0xeb, 0xfd, 0x04, 0x92, 0x64, - 0xcf, 0x5d, 0x56, 0xc1, 0xa0, 0xd5, 0x4c, 0xc2, 0xe3, 0xf7, 0xfb, 0xf3, 0xf8, 0x8f, 0x7d, 0x37, - 0x03, 0x83, 0x12, 0x73, 0x50, 0x11, 0x0c, 0x50, 0x3c, 0x65, 0xa9, 0x16, 0xe3, 0x04, 0x90, 0x61, - 0x96, 0xc8, 0x1c, 0x99, 0x54, 0x39, 0x18, 0xc5, 0x13, 0x96, 0x1b, 0xae, 0x90, 0x47, 0xb9, 0xd4, - 0x0a, 0xd9, 0xa1, 0xe1, 0x19, 0x4b, 0x01, 0x91, 0xc7, 0x40, 0x33, 0xa3, 0x73, 0xed, 0xdc, 0x5c, - 0x01, 0xd1, 0x39, 0x88, 0xd6, 0x20, 0x7a, 0x0a, 0xa2, 0xcb, 0x20, 0x5a, 0x82, 0x3a, 0x17, 0x63, - 0x1d, 0xeb, 0x8a, 0xc2, 0xca, 0x5b, 0x0d, 0xec, 0x5c, 0x5d, 0x4d, 0x86, 0xd1, 0x01, 0xa4, 0x9c, - 0xe5, 0x2f, 0x32, 0x40, 0x36, 0xe4, 0x08, 0x4c, 0x8a, 0x7a, 0x36, 0xf8, 0xdc, 0xb2, 0xcf, 0xed, - 0xd7, 0x71, 0x9c, 0x77, 0xc4, 0x5e, 0x1b, 0x19, 0x9d, 0xb6, 0x89, 0x4f, 0xba, 0x9b, 0xe1, 0xcb, - 0xe3, 0xc2, 0xb3, 0xbe, 0x16, 0xde, 0xed, 0x58, 0xe6, 0x07, 0xe3, 0x21, 0x8d, 0x74, 0xca, 0x96, - 0xc8, 0x0f, 0x14, 0x2c, 0x7f, 0x3e, 0xec, 0xdd, 0xfb, 0xdd, 0x43, 0x77, 0xa3, 0x68, 0x57, 0x08, - 0x03, 0x88, 0xb3, 0xc2, 0xbb, 0xf6, 0x9c, 0x27, 0x52, 0xec, 0x04, 0x06, 0x9e, 0x8d, 0xa5, 0x01, - 0xf1, 0xea, 0xf4, 0xe2, 0x8f, 0x24, 0x24, 0xc2, 0xbf, 0x63, 0x74, 0xea, 0xa7, 0x12, 0x51, 0xaa, - 0x38, 0xe8, 0x57, 0x51, 0x9c, 0x43, 0x7b, 0xa3, 0x3c, 0x07, 0x72, 0x20, 0xda, 0x67, 0x7c, 0xd2, - 0x3d, 0xbf, 0x7d, 0x99, 0xae, 0xee, 0xab, 0xd6, 0xd2, 0x4a, 0x4b, 0x2b, 0xed, 0x5e, 0x2f, 0xbc, - 0x51, 0xa6, 0x9f, 0x15, 0x1e, 0x6d, 0x20, 0xdd, 0xeb, 0x2d, 0xb4, 0xeb, 0xa3, 0xea, 0x87, 0xf3, - 0x81, 0xd8, 0x67, 0x23, 0x2d, 0x15, 0xb6, 0x5b, 0x7e, 0xab, 0xbb, 0x19, 0xbe, 0x21, 0xf3, 0x75, - 0x5c, 0x59, 0x5a, 0x47, 0xa4, 0x31, 0xd5, 0x38, 0x3f, 0xb6, 0xca, 0x55, 0xd7, 0x21, 0x6e, 0x69, - 0xa9, 0x66, 0x85, 0xb7, 0xf5, 0x17, 0x77, 0x39, 0x86, 0xbf, 0xd4, 0x9f, 0xbe, 0x79, 0xdd, 0x86, - 0x6c, 0xec, 0xd7, 0xd9, 0x76, 0x36, 0x5e, 0x1f, 0x79, 0xd6, 0x8f, 0x23, 0xcf, 0x0a, 0x2e, 0xd9, - 0x17, 0x1e, 0x2d, 0xfa, 0xd1, 0x07, 0xcc, 0xb4, 0x42, 0xd8, 0xfe, 0x48, 0xec, 0xd6, 0x3e, 0xc6, - 0xce, 0x7b, 0x62, 0xaf, 0x3d, 0x36, 0x3c, 0x73, 0x42, 0xfa, 0xcf, 0x75, 0xa3, 0xf3, 0xa2, 0x74, - 0xee, 0xff, 0x07, 0xe3, 0x0f, 0x21, 0x03, 0x2b, 0x4c, 0x8e, 0x27, 0x2e, 0x39, 0x99, 0xb8, 0xe4, - 0xfb, 0xc4, 0x25, 0x6f, 0xa7, 0xae, 0x75, 0x32, 0x75, 0xad, 0x2f, 0x53, 0xd7, 0x7a, 0xd2, 0x6f, - 0xdc, 0xbe, 0xc6, 0xef, 0x6f, 0xb8, 0x5e, 0x75, 0xff, 0xfa, 0xcf, 0x00, 0x00, 0x00, 0xff, 0xff, - 0xc1, 0x11, 0x4d, 0xb3, 0xc3, 0x03, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// MsgClient is the client API for Msg service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type MsgClient interface { - Wrap(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) Wrap(ctx context.Context, in *Message, opts ...grpc.CallOption) (*TransactionResponse, error) { - out := new(TransactionResponse) - err := c.cc.Invoke(ctx, "/persistence_sdk.modules.splits.internal.transactions.wrap.Msg/Wrap", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - Wrap(context.Context, *Message) (*TransactionResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { -} - -func (*UnimplementedMsgServer) Wrap(ctx context.Context, req *Message) (*TransactionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Wrap not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_Wrap_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).Wrap(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/persistence_sdk.modules.splits.internal.transactions.wrap.Msg/Wrap", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).Wrap(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "persistence_sdk.modules.splits.internal.transactions.wrap.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Wrap", - Handler: _Msg_Wrap_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "persistence_sdk/modules/splits/internal/transactions/wrap/message.proto", -} - -func (m *Message) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Message) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Message) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Coins) > 0 { - for iNdEx := len(m.Coins) - 1; iNdEx >= 0; iNdEx-- { - { - size := m.Coins[iNdEx].Size() - i -= size - if _, err := m.Coins[iNdEx].MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - { - size, err := m.FromID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size := m.From.Size() - i -= size - if _, err := m.From.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintMessage(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *TransactionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *TransactionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *TransactionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func encodeVarintMessage(dAtA []byte, offset int, v uint64) int { - offset -= sovMessage(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Message) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.From.Size() - n += 1 + l + sovMessage(uint64(l)) - l = m.FromID.Size() - n += 1 + l + sovMessage(uint64(l)) - if len(m.Coins) > 0 { - for _, e := range m.Coins { - l = e.Size() - n += 1 + l + sovMessage(uint64(l)) - } - } - return n -} - -func (m *TransactionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func sovMessage(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMessage(x uint64) (n int) { - return sovMessage(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Message) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Message: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Message: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field From", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.From.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field FromID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.FromID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Coins", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMessage - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMessage - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var v github_com_cosmos_cosmos_sdk_types.Coin - m.Coins = append(m.Coins, v) - if err := m.Coins[len(m.Coins)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *TransactionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMessage - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: TransactionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: TransactionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipMessage(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMessage - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMessage(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMessage - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMessage - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMessage - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMessage - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMessage = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMessage = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMessage = fmt.Errorf("proto: unexpected end of group") -) diff --git a/modules/splits/internal/transactions/wrap/message_test.go b/modules/splits/internal/transactions/wrap/message_test.go index cc7104581..b44e7c2f8 100644 --- a/modules/splits/internal/transactions/wrap/message_test.go +++ b/modules/splits/internal/transactions/wrap/message_test.go @@ -1,38 +1,238 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package wrap import ( + "reflect" "testing" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - "github.com/persistenceOne/persistenceSDK/utilities/transaction" + "github.com/AssetMantle/modules/modules/splits/internal/module" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/utilities/transaction" ) -func Test_Wrap_Message(t *testing.T) { - testFromID := base.NewID("fromID") - testCoins := sdkTypes.NewCoins(sdkTypes.NewCoin("stake", sdkTypes.NewInt(2))) - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, err) - - testMessage := newMessage(fromAccAddress, testFromID, testCoins) - require.Equal(t, Message{From: fromAccAddress, FromID: testFromID, Coins: testCoins}, testMessage) - require.Equal(t, module.Name, testMessage.Route()) - require.Equal(t, Transaction.GetName(), testMessage.Type()) - require.Equal(t, nil, testMessage.ValidateBasic()) - require.NotNil(t, Message{}.ValidateBasic()) - require.Equal(t, sdkTypes.MustSortJSON(transaction.RegisterLegacyAminoCodec(messagePrototype).MustMarshalJSON(testMessage)), testMessage.GetSignBytes()) - require.Equal(t, []sdkTypes.AccAddress{fromAccAddress}, testMessage.GetSigners()) - require.Equal(t, testMessage, messageFromInterface(testMessage)) - require.Equal(t, Message{}, messageFromInterface(nil)) - require.Equal(t, Message{}, messagePrototype()) +func Test_messageFromInterface(t *testing.T) { + type args struct { + msg types.Msg + } + tests := []struct { + name string + args args + want message + }{ + {"+ve", args{newMessage(fromAccAddress, fromID, testRate)}, message{fromAccAddress, fromID, testRate}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messageFromInterface(tt.args.msg); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messageFromInterface() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_messagePrototype(t *testing.T) { + tests := []struct { + name string + want helpers.Message + }{ + {"+ve", message{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := messagePrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("messagePrototype() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSignBytes(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + Coins types.Coins + } + tests := []struct { + name string + fields fields + want []byte + }{ + {"+ve", fields{fromAccAddress, fromID, testRate}, types.MustSortJSON(transaction.RegisterCodec(messagePrototype).MustMarshalJSON(message{fromAccAddress, fromID, testRate}))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + Coins: tt.fields.Coins, + } + if got := message.GetSignBytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSignBytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_GetSigners(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + Coins types.Coins + } + tests := []struct { + name string + fields fields + want []types.AccAddress + }{ + {"+ve", fields{fromAccAddress, fromID, testRate}, []types.AccAddress{fromAccAddress}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + Coins: tt.fields.Coins, + } + if got := message.GetSigners(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetSigners() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_RegisterCodec(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + Coins types.Coins + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{fromAccAddress, fromID, testRate}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + me := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + Coins: tt.fields.Coins, + } + me.RegisterCodec(tt.args.codec) + }) + } +} + +func Test_message_Route(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + Coins types.Coins + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, testRate}, module.Name}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + Coins: tt.fields.Coins, + } + if got := message.Route(); got != tt.want { + t.Errorf("Route() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_Type(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + Coins types.Coins + } + tests := []struct { + name string + fields fields + want string + }{ + {"+ve", fields{fromAccAddress, fromID, testRate}, Transaction.GetName()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + Coins: tt.fields.Coins, + } + if got := message.Type(); got != tt.want { + t.Errorf("Type() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_message_ValidateBasic(t *testing.T) { + type fields struct { + From types.AccAddress + FromID ids.IdentityID + Coins types.Coins + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{fromAccAddress, fromID, testRate}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + message := message{ + From: tt.fields.From, + FromID: tt.fields.FromID, + Coins: tt.fields.Coins, + } + if err := message.ValidateBasic(); (err != nil) != tt.wantErr { + t.Errorf("ValidateBasic() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} +func Test_newMessage(t *testing.T) { + type args struct { + from types.AccAddress + fromID ids.IdentityID + coins types.Coins + } + tests := []struct { + name string + args args + want types.Msg + }{ + {"+ve", args{fromAccAddress, fromID, testRate}, message{fromAccAddress, fromID, testRate}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newMessage(tt.args.from, tt.args.fromID, tt.args.coins); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newMessage() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/modules/splits/internal/transactions/wrap/msg_server.go b/modules/splits/internal/transactions/wrap/msg_server.go deleted file mode 100644 index 375707067..000000000 --- a/modules/splits/internal/transactions/wrap/msg_server.go +++ /dev/null @@ -1,39 +0,0 @@ -package wrap - -import ( - "context" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/identities/auxiliaries/verify" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/utilities" - "github.com/persistenceOne/persistenceSDK/schema/types/base" -) - -type msgServer struct { - transactionKeeper -} - -func (msgServer msgServer) Wrap(goCtx context.Context, message *Message) (*TransactionResponse, error) { - ctx := sdkTypes.UnwrapSDKContext(goCtx) - if auxiliaryResponse := msgServer.transactionKeeper.verifyAuxiliary.GetKeeper().Help(ctx, verify.NewAuxiliaryRequest(message.From.AsSDKTypesAccAddress(), &message.FromID)); !auxiliaryResponse.IsSuccessful() { - return nil, auxiliaryResponse.GetError() - } - - if Error := msgServer.transactionKeeper.bankKeeper.SendCoinsFromAccountToModule(ctx, message.From.AsSDKTypesAccAddress(), module.Name, message.Coins); Error != nil { - return nil, Error - } - - for _, coin := range message.Coins { - if _, Error := utilities.AddSplits(msgServer.transactionKeeper.mapper.NewCollection(ctx), &message.FromID, base.NewID(coin.Denom), sdkTypes.NewDecFromInt(coin.Amount)); Error != nil { - return nil, Error - } - } - - return &TransactionResponse{}, nil -} - -func NewMsgServerImpl(keeper transactionKeeper) MsgServer { - return &msgServer{keeper} -} - -var _ MsgServer = msgServer{} diff --git a/modules/splits/internal/transactions/wrap/request.go b/modules/splits/internal/transactions/wrap/request.go index 28b32ea3d..85a10a7e9 100644 --- a/modules/splits/internal/transactions/wrap/request.go +++ b/modules/splits/internal/transactions/wrap/request.go @@ -1,22 +1,21 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package wrap import ( "encoding/json" + "github.com/asaskevich/govalidator" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/module" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type transactionRequest struct { @@ -27,30 +26,30 @@ type transactionRequest struct { var _ helpers.TransactionRequest = (*transactionRequest)(nil) -// Transaction Request godoc -// @Summary wrap split transaction -// @Descrption wrap split transaction +// Validate godoc +// @Summary Wrap split transaction +// @Description Wrap split transaction // @Accept text/plain // @Produce json // @Tags Splits -// @Param body body transactionRequest true "request body" -// @Success 200 {object} transactionResponse "A successful response." -// @Failure default {object} transactionResponse "An unexpected error response." +// @Param body body transactionRequest true "Request body to wrap split" +// @Success 200 {object} transactionResponse "Message for a successful response." +// @Failure default {object} transactionResponse "Message for an unexpected error response." // @Router /splits/wrap [post] func (transactionRequest transactionRequest) Validate() error { - _, Error := govalidator.ValidateStruct(transactionRequest) - return Error + _, err := govalidator.ValidateStruct(transactionRequest) + return err } -func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest transactionRequest) FromCLI(cliCommand helpers.CLICommand, cliContext context.CLIContext) (helpers.TransactionRequest, error) { return newTransactionRequest( cliCommand.ReadBaseReq(cliContext), - cliCommand.ReadString(flags.FromID), - cliCommand.ReadString(flags.Coins), + cliCommand.ReadString(constants.FromID), + cliCommand.ReadString(constants.Coins), ), nil } func (transactionRequest transactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { - if Error := json.Unmarshal(rawMessage, &transactionRequest); Error != nil { - return nil, Error + if err := json.Unmarshal(rawMessage, &transactionRequest); err != nil { + return nil, err } return transactionRequest, nil @@ -59,24 +58,29 @@ func (transactionRequest transactionRequest) GetBaseReq() rest.BaseReq { return transactionRequest.BaseReq } func (transactionRequest transactionRequest) MakeMsg() (sdkTypes.Msg, error) { - from, Error := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) - if Error != nil { - return nil, Error + from, err := sdkTypes.AccAddressFromBech32(transactionRequest.GetBaseReq().From) + if err != nil { + return nil, err + } + + coins, err := sdkTypes.ParseCoins(transactionRequest.Coins) + if err != nil { + return nil, err } - coins, Error := sdkTypes.ParseCoinsNormalized(transactionRequest.Coins) - if Error != nil { - return nil, Error + fromID, err := baseIDs.ReadIdentityID(transactionRequest.FromID) + if err != nil { + return nil, err } return newMessage( from, - base.NewID(transactionRequest.FromID), + fromID, coins, ), nil } -func (transactionRequest) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, module.Name, transactionRequest{}) +func (transactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, transactionRequest{}) } func requestPrototype() helpers.TransactionRequest { return transactionRequest{} diff --git a/modules/splits/internal/transactions/wrap/request_test.go b/modules/splits/internal/transactions/wrap/request_test.go index 40286b5df..9ffc2c0ce 100644 --- a/modules/splits/internal/transactions/wrap/request_test.go +++ b/modules/splits/internal/transactions/wrap/request_test.go @@ -1,75 +1,273 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package wrap import ( "encoding/json" + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/persistenceOne/persistenceSDK/constants/flags" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - baseHelpers "github.com/persistenceOne/persistenceSDK/schema/helpers/base" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/spf13/viper" "github.com/stretchr/testify/require" - "testing" -) -func Test_Unwrap_Request(t *testing.T) { - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) - codec.RegisterEvidences(Codec) - vesting.RegisterCodec(Codec) - Codec.Seal() - cliCommand := baseHelpers.NewCLICommand("", "", "", []helpers.CLIFlag{flags.FromID, flags.Coins}) - cliContext := context.NewCLIContext().WithCodec(Codec) - - fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" - fromAccAddress, Error := sdkTypes.AccAddressFromBech32(fromAddress) - require.Nil(t, Error) - - testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} - testTransactionRequest := newTransactionRequest(testBaseReq, "fromID", "2 stake") + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) - require.Equal(t, transactionRequest{BaseReq: testBaseReq, FromID: "fromID", Coins: "2 stake"}, testTransactionRequest) - require.Equal(t, nil, testTransactionRequest.Validate()) +var ( + fromAddress = "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ = types.AccAddressFromBech32(fromAddress) + testBaseRequest = rest.BaseReq{From: fromAddress, ChainID: "test", Fees: types.NewCoins()} + immutables = baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables = baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())))) + classificationID = baseIDs.NewClassificationID(immutables, mutables) + fromID = baseIDs.NewIdentityID(classificationID, immutables) + ownableID = baseIDs.NewOwnableID(baseIDs.NewStringID("ownableid")) + testRate = types.NewCoins(types.NewCoin("mntl", types.NewInt(1))) +) - requestFromCLI, Error := transactionRequest{}.FromCLI(cliCommand, cliContext) - require.Equal(t, nil, Error) - require.Equal(t, transactionRequest{BaseReq: rest.BaseReq{From: cliContext.GetFromAddress().String(), ChainID: cliContext.ChainID, Simulate: cliContext.Simulate}, FromID: "", Coins: ""}, requestFromCLI) +func Test_newTransactionRequest(t *testing.T) { + type args struct { + baseReq rest.BaseReq + fromID string + coins string + } + tests := []struct { + name string + args args + want helpers.TransactionRequest + }{ + {"+ve", args{testBaseRequest, fromID.String(), testRate.String()}, transactionRequest{testBaseRequest, fromID.String(), testRate.String()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := newTransactionRequest(tt.args.baseReq, tt.args.fromID, tt.args.coins); !reflect.DeepEqual(got, tt.want) { + t.Errorf("newTransactionRequest() = %v, want %v", got, tt.want) + } + }) + } +} - jsonMessage, _ := json.Marshal(testTransactionRequest) - transactionRequestUnmarshalled, Error := transactionRequest{}.FromJSON(jsonMessage) - require.Equal(t, nil, Error) - require.Equal(t, testTransactionRequest, transactionRequestUnmarshalled) +func Test_requestPrototype(t *testing.T) { + tests := []struct { + name string + want helpers.TransactionRequest + }{ + {"+ve", transactionRequest{}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := requestPrototype(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("requestPrototype() = %v, want %v", got, tt.want) + } + }) + } +} - randomUnmarshall, Error := transactionRequest{}.FromJSON([]byte{}) - require.Equal(t, nil, randomUnmarshall) - require.NotNil(t, Error) +func Test_transactionRequest_FromCLI(t *testing.T) { + cliCommand := base.NewCLICommand("", "", "", []helpers.CLIFlag{constants.Coins, constants.FromID}) + cliContext := context.NewCLIContext().WithCodec(codec.New()).WithFromAddress(fromAccAddress).WithChainID("test") + viper.Set(constants.FromID.GetName(), fromID.String()) + viper.Set(constants.Coins.GetName(), testRate.String()) + type fields struct { + BaseReq rest.BaseReq + FromID string + Coins string + } + type args struct { + cliCommand helpers.CLICommand + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testRate.String()}, args{cliCommand, cliContext}, transactionRequest{testBaseRequest, fromID.String(), testRate.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + Coins: tt.fields.Coins, + } + got, err := transactionRequest.FromCLI(tt.args.cliCommand, tt.args.cliContext) + if (err != nil) != tt.wantErr { + t.Errorf("FromCLI() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("FromCLI() got = %v, want %v", got, tt.want) + } + }) + } +} - require.Equal(t, testBaseReq, testTransactionRequest.GetBaseReq()) +func Test_transactionRequest_FromJSON(t *testing.T) { + jsonMessage, err := json.Marshal(newTransactionRequest(testBaseRequest, fromID.String(), testRate.String())) + require.NoError(t, err) + type fields struct { + BaseReq rest.BaseReq + FromID string + Coins string + } + type args struct { + rawMessage json.RawMessage + } + tests := []struct { + name string + fields fields + args args + want helpers.TransactionRequest + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testRate.String()}, args{jsonMessage}, newTransactionRequest(testBaseRequest, fromID.String(), testRate.String()), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + Coins: tt.fields.Coins, + } + got, err := transactionRequest.FromJSON(tt.args.rawMessage) + if (err != nil) != tt.wantErr { + t.Errorf("FromJSON() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("FromJSON() got = %v, want %v", got, tt.want) + } + }) + } +} - msg, Error := testTransactionRequest.MakeMsg() - require.Equal(t, newMessage(fromAccAddress, base.NewID("fromID"), sdkTypes.NewCoins(sdkTypes.NewCoin("stake", sdkTypes.NewInt(2)))), msg) - require.Nil(t, Error) +func Test_transactionRequest_GetBaseReq(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + Coins string + } + tests := []struct { + name string + fields fields + want rest.BaseReq + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testRate.String()}, testBaseRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + Coins: tt.fields.Coins, + } + if got := transactionRequest.GetBaseReq(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error := newTransactionRequest(rest.BaseReq{From: "randomFromAddress", ChainID: "test"}, "fromID", "2 stake").MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_MakeMsg(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + Coins string + } + tests := []struct { + name string + fields fields + want types.Msg + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testRate.String()}, newMessage(fromAccAddress, fromID, testRate), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + Coins: tt.fields.Coins, + } + got, err := transactionRequest.MakeMsg() + if (err != nil) != tt.wantErr { + t.Errorf("MakeMsg() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("MakeMsg() got = %v, want %v", got, tt.want) + } + }) + } +} - msg2, Error = newTransactionRequest(testBaseReq, "fromID", "randomString").MakeMsg() - require.NotNil(t, Error) - require.Nil(t, msg2) +func Test_transactionRequest_RegisterCodec(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + Coins string + } + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + fields fields + args args + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testRate.String()}, args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tr := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + Coins: tt.fields.Coins, + } + tr.RegisterCodec(tt.args.codec) + }) + } +} - require.Equal(t, transactionRequest{}, requestPrototype()) - require.NotPanics(t, func() { - requestPrototype().RegisterLegacyAminoCodec(codec.New()) - }) +func Test_transactionRequest_Validate(t *testing.T) { + type fields struct { + BaseReq rest.BaseReq + FromID string + Coins string + } + tests := []struct { + name string + fields fields + wantErr bool + }{ + {"+ve", fields{testBaseRequest, fromID.String(), testRate.String()}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + transactionRequest := transactionRequest{ + BaseReq: tt.fields.BaseReq, + FromID: tt.fields.FromID, + Coins: tt.fields.Coins, + } + if err := transactionRequest.Validate(); (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } } diff --git a/modules/splits/internal/transactions/wrap/response.go b/modules/splits/internal/transactions/wrap/response.go new file mode 100644 index 000000000..0b426faf1 --- /dev/null +++ b/modules/splits/internal/transactions/wrap/response.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package wrap + +import ( + "github.com/AssetMantle/modules/schema/helpers" +) + +type transactionResponse struct { + Success bool `json:"success"` + Error error `json:"error" swaggertype:"string"` +} + +var _ helpers.TransactionResponse = (*transactionResponse)(nil) + +func (transactionResponse transactionResponse) IsSuccessful() bool { + return transactionResponse.Success +} +func (transactionResponse transactionResponse) GetError() error { + return transactionResponse.Error +} +func newTransactionResponse(error error) helpers.TransactionResponse { + success := true + if error != nil { + success = false + } + + return transactionResponse{ + Success: success, + Error: error, + } +} diff --git a/modules/splits/internal/transactions/wrap/response_test.go b/modules/splits/internal/transactions/wrap/response_test.go new file mode 100644 index 000000000..cfe68302e --- /dev/null +++ b/modules/splits/internal/transactions/wrap/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package wrap + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_Wrap_Response(t *testing.T) { + testTransactionResponse := newTransactionResponse(constants.IncorrectFormat) + testTransactionResponse2 := newTransactionResponse(nil) + + require.Equal(t, transactionResponse{Success: false, Error: constants.IncorrectFormat}, testTransactionResponse) + require.Equal(t, false, testTransactionResponse.IsSuccessful()) + require.Equal(t, true, testTransactionResponse2.IsSuccessful()) + + require.Equal(t, constants.IncorrectFormat, testTransactionResponse.GetError()) + require.Equal(t, nil, testTransactionResponse2.GetError()) +} diff --git a/modules/splits/internal/transactions/wrap/transaction.go b/modules/splits/internal/transactions/wrap/transaction.go new file mode 100644 index 000000000..a35d340be --- /dev/null +++ b/modules/splits/internal/transactions/wrap/transaction.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package wrap + +import ( + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" + "github.com/AssetMantle/modules/schema/helpers/constants" +) + +var Transaction = baseHelpers.NewTransaction( + "wrap", + "", + "", + + requestPrototype, + messagePrototype, + keeperPrototype, + + constants.FromID, + constants.Coins, +) diff --git a/modules/splits/internal/utilities/ownable.go b/modules/splits/internal/utilities/ownable.go index 2ac6e52b3..f14046d0b 100644 --- a/modules/splits/internal/utilities/ownable.go +++ b/modules/splits/internal/utilities/ownable.go @@ -1,30 +1,28 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package utilities import ( sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/types" ) -func GetOwnableTotalSplitsValue(collection helpers.Collection, ownableID types.ID) sdkTypes.Dec { +func GetOwnableTotalSplitsValue(collection helpers.Collection, ownableID ids.ID) sdkTypes.Dec { value := sdkTypes.ZeroDec() accumulator := func(mappable helpers.Mappable) bool { - if key.ReadOwnableID(key.ToID(mappable.GetKey())).Compare(ownableID) == 0 { - value = value.Add(mappable.(mappables.Split).GetValue()) + if mappable.(types.Split).GetOwnableID().Compare(ownableID) == 0 { + value = value.Add(mappable.(types.Split).GetValue()) } return false } - collection.Iterate(key.FromID(base.NewID("")), accumulator) + collection.Iterate(key.NewKey(baseIDs.PrototypeSplitID()), accumulator) return value } diff --git a/modules/splits/internal/utilities/ownable_test.go b/modules/splits/internal/utilities/ownable_test.go new file mode 100644 index 000000000..d51173fa8 --- /dev/null +++ b/modules/splits/internal/utilities/ownable_test.go @@ -0,0 +1,51 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package utilities + +import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +func TestGetOwnableTotalSplitsValue(t *testing.T) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testOwnerIdentityID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + testRate := types.NewDec(10) + split := baseTypes.NewSplit(testOwnerIdentityID, testOwnableID, testRate) + context, testMapper := createTestInput1(t) + testSplits := testMapper.NewCollection(context).Add(mappable.NewMappable(split)) + type args struct { + collection helpers.Collection + ownableID ids.ID + } + tests := []struct { + name string + args args + want types.Dec + }{ + {"+ve", args{testSplits, testOwnableID}, testRate}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := GetOwnableTotalSplitsValue(tt.args.collection, tt.args.ownableID); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetOwnableTotalSplitsValue() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/splits/internal/utilities/split.go b/modules/splits/internal/utilities/split.go index d2926bd17..25dfbcf54 100644 --- a/modules/splits/internal/utilities/split.go +++ b/modules/splits/internal/utilities/split.go @@ -1,59 +1,59 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package utilities import ( sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key" - "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/mappables" //nolint:typecheck - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" + + "github.com/AssetMantle/modules/modules/splits/internal/key" + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/types" + "github.com/AssetMantle/modules/schema/types/base" + + "github.com/AssetMantle/modules/schema/helpers" ) -func AddSplits(splits helpers.Collection, ownerID types.ID, ownableID types.ID, value sdkTypes.Dec) (helpers.Collection, error) { +func AddSplits(splits helpers.Collection, ownerID ids.IdentityID, ownableID ids.OwnableID, value sdkTypes.Dec) (helpers.Collection, error) { if value.LTE(sdkTypes.ZeroDec()) { - return nil, errors.NotAuthorized + return nil, constants.NotAuthorized } - splitID := key.NewSplitID(ownerID, ownableID) + splitID := baseIDs.NewSplitID(ownerID, ownableID) - split := splits.Fetch(key.FromID(splitID)).Get(key.FromID(splitID)) + split := splits.Fetch(key.NewKey(splitID)).Get(key.NewKey(splitID)) if split == nil { - splits.Add(mappable.NewSplit(splitID, value)) + splits.Add(mappable.NewMappable(base.NewSplit(ownerID, ownableID, value))) } else { - newSplit := split.(mappables.Split).Receive(value) - splits.Mutate(mappable.NewSplit(base.NewID(key.NewSplitID(ownerID, ownableID).String()), newSplit.GetValue())) + splits.Mutate(mappable.NewMappable(split.(types.Split).Receive(value))) } return splits, nil } -func SubtractSplits(splits helpers.Collection, ownerID types.ID, ownableID types.ID, value sdkTypes.Dec) (helpers.Collection, error) { +func SubtractSplits(splits helpers.Collection, ownerID ids.IdentityID, ownableID ids.OwnableID, value sdkTypes.Dec) (helpers.Collection, error) { if value.LTE(sdkTypes.ZeroDec()) { - return nil, errors.NotAuthorized + return nil, constants.NotAuthorized } - splitsKey := key.FromID(key.NewSplitID(ownerID, ownableID)) + splitsKey := key.NewKey(baseIDs.NewSplitID(ownerID, ownableID)) - split := splits.Fetch(splitsKey).Get(splitsKey) - if split == nil { - return nil, errors.EntityNotFound + Mappable := splits.Fetch(splitsKey).Get(splitsKey) + if Mappable == nil { + return nil, constants.EntityNotFound } + split := Mappable.(types.Split) - newSplit := split.(mappables.Split).Send(value) - switch split = mappable.NewSplit(base.NewID(key.NewSplitID(ownerID, ownableID).String()), newSplit.GetValue()); { - case split.(mappables.Split).GetValue().LT(sdkTypes.ZeroDec()): - return nil, errors.NotAuthorized - case split.(mappables.Split).GetValue().Equal(sdkTypes.ZeroDec()): - splits.Remove(split) + switch split = split.Send(value); { + case split.GetValue().LT(sdkTypes.ZeroDec()): + return nil, constants.NotAuthorized + case split.GetValue().Equal(sdkTypes.ZeroDec()): + splits.Remove(mappable.NewMappable(split)) default: - splits.Mutate(split) + splits.Mutate(mappable.NewMappable(split)) } return splits, nil diff --git a/modules/splits/internal/utilities/split_test.go b/modules/splits/internal/utilities/split_test.go new file mode 100644 index 000000000..63617abc5 --- /dev/null +++ b/modules/splits/internal/utilities/split_test.go @@ -0,0 +1,141 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package utilities + +import ( + "fmt" + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/libs/log" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/splits/internal/mappable" + "github.com/AssetMantle/modules/modules/splits/internal/mapper" + "github.com/AssetMantle/modules/schema" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIds "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +func createTestInput1(t *testing.T) (sdkTypes.Context, helpers.Mapper) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + storeKey := sdkTypes.NewKVStoreKey("test") + paramsStoreKey := sdkTypes.NewKVStoreKey("testParams") + paramsTransientStoreKeys := sdkTypes.NewTransientStoreKey("testParamsTransient") + + memDB := tendermintDB.NewMemDB() + commitMultiStore := store.NewCommitMultiStore(memDB) + commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) + commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) + + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ + ChainID: "test", + }, false, log.NewNopLogger()) + + testMapper := mapper.Prototype().Initialize(storeKey) + + return context, testMapper +} + +func TestAddSplits(t *testing.T) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testOwnerIdentityID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + testRate := sdkTypes.NewDec(1) + split := baseTypes.NewSplit(testOwnerIdentityID, testOwnableID, testRate) + context, testMapper := createTestInput1(t) + testSplits := testMapper.NewCollection(context).Add(mappable.NewMappable(split)) + type args struct { + splits helpers.Collection + ownerID ids.IdentityID + ownableID ids.OwnableID + value sdkTypes.Dec + } + tests := []struct { + name string + args args + want helpers.Collection + wantErr bool + }{ + {"+ve", args{testSplits, testOwnerIdentityID, testOwnableID, sdkTypes.NewDec(100)}, testSplits.Mutate(mappable.NewMappable(split.Receive(sdkTypes.NewDec(100)))), false}, + {"+ve Not authorized", args{testSplits, testOwnerIdentityID, testOwnableID, sdkTypes.ZeroDec()}, nil, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := AddSplits(tt.args.splits, tt.args.ownerID, tt.args.ownableID, tt.args.value) + if (err != nil) != tt.wantErr { + t.Errorf("AddSplits() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("AddSplits() got = %v, want %v", got, tt.want) + } + }) + } +} + +func TestSubtractSplits(t *testing.T) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMetaProperty(baseIds.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + classificationID := baseIds.NewClassificationID(immutables, mutables) + testOwnerIdentityID := baseIds.NewIdentityID(classificationID, immutables) + testOwnableID := baseIds.NewOwnableID(baseIds.NewStringID("OwnerID")) + testRate := sdkTypes.NewDec(10) + split := baseTypes.NewSplit(testOwnerIdentityID, testOwnableID, testRate) + context, testMapper := createTestInput1(t) + testSplits := testMapper.NewCollection(context).Add(mappable.NewMappable(split)) + type args struct { + splits helpers.Collection + ownerID ids.IdentityID + ownableID ids.OwnableID + value sdkTypes.Dec + } + tests := []struct { + name string + args args + want helpers.Collection + wantErr bool + }{ + {"+ve", args{testSplits, testOwnerIdentityID, testOwnableID, sdkTypes.NewDec(9)}, testSplits.Mutate(mappable.NewMappable(split)), false}, + {"+ve Not Authorized", args{testSplits, testOwnerIdentityID, testOwnableID, sdkTypes.NewDec(100)}, nil, true}, + {"+ve Not Authorized", args{testSplits, testOwnerIdentityID, testOwnableID, sdkTypes.ZeroDec()}, nil, true}, + {"+ve Entity Not found", args{testSplits, baseIds.PrototypeIdentityID(), testOwnableID, testRate}, nil, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := SubtractSplits(tt.args.splits, tt.args.ownerID, tt.args.ownableID, tt.args.value) + if (err != nil) != tt.wantErr { + t.Errorf("SubtractSplits() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(fmt.Sprint(got), fmt.Sprint(tt.want)) { + t.Errorf("SubtractSplits() got = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/modules/splits/prototype.go b/modules/splits/prototype.go new file mode 100644 index 000000000..b9072dfcc --- /dev/null +++ b/modules/splits/prototype.go @@ -0,0 +1,32 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package splits + +import ( + "github.com/AssetMantle/modules/modules/splits/auxiliaries" + "github.com/AssetMantle/modules/modules/splits/internal/block" + "github.com/AssetMantle/modules/modules/splits/internal/genesis" + "github.com/AssetMantle/modules/modules/splits/internal/mapper" + "github.com/AssetMantle/modules/modules/splits/internal/module" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/modules/splits/internal/queries" + "github.com/AssetMantle/modules/modules/splits/internal/simulator" + "github.com/AssetMantle/modules/modules/splits/internal/transactions" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func Prototype() helpers.Module { + return baseHelpers.NewModule( + module.Name, + auxiliaries.Prototype, + genesis.Prototype, + mapper.Prototype, + parameters.Prototype, + queries.Prototype, + simulator.Prototype, + transactions.Prototype, + block.Prototype, + ) +} diff --git a/modules/splits/prototype_test.go b/modules/splits/prototype_test.go new file mode 100644 index 000000000..2a0bf2d06 --- /dev/null +++ b/modules/splits/prototype_test.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package splits + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/modules/classifications/auxiliaries" + "github.com/AssetMantle/modules/modules/splits/internal/block" + "github.com/AssetMantle/modules/modules/splits/internal/genesis" + "github.com/AssetMantle/modules/modules/splits/internal/mapper" + "github.com/AssetMantle/modules/modules/splits/internal/module" + "github.com/AssetMantle/modules/modules/splits/internal/parameters" + "github.com/AssetMantle/modules/modules/splits/internal/queries" + "github.com/AssetMantle/modules/modules/splits/internal/simulator" + "github.com/AssetMantle/modules/modules/splits/internal/transactions" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func TestPrototype(t *testing.T) { + require.Equal(t, Prototype().Name(), baseHelpers.NewModule( + module.Name, + auxiliaries.Prototype, + genesis.Prototype, + mapper.Prototype, + parameters.Prototype, + queries.Prototype, + simulator.Prototype, + transactions.Prototype, + block.Prototype, + ).Name()) +} diff --git a/proto/persistence_sdk/modules/assets/internal/genesis/genesis.proto b/proto/persistence_sdk/modules/assets/internal/genesis/genesis.proto deleted file mode 100644 index 5ca80b2f1..000000000 --- a/proto/persistence_sdk/modules/assets/internal/genesis/genesis.proto +++ /dev/null @@ -1,19 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.assets.internal.genesis; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/modules/assets/internal/mappable/asset.proto"; -import "persistence_sdk/modules/assets/internal/parameters/dummy/parameter.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/assets/internal/genesis"; - -message Genesis { - option (gogoproto.goproto_getters) = false; - repeated persistence_sdk.modules.assets.internal.mappable.Asset defaultMappableList = 1 [(gogoproto.nullable) = false]; - repeated persistence_sdk.modules.assets.internal.parameters.dummy.DummyParameter defaultParameterList = 2 [(gogoproto.nullable) = false]; - - repeated persistence_sdk.modules.assets.internal.mappable.Asset MappableList = 3 [(gogoproto.nullable) = false]; - repeated persistence_sdk.modules.assets.internal.parameters.dummy.DummyParameter ParameterList = 4 [(gogoproto.nullable) = false]; - -} diff --git a/proto/persistence_sdk/modules/assets/internal/key/assetID.proto b/proto/persistence_sdk/modules/assets/internal/key/assetID.proto deleted file mode 100644 index b5b676416..000000000 --- a/proto/persistence_sdk/modules/assets/internal/key/assetID.proto +++ /dev/null @@ -1,14 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.assets.internal.key; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/assets/internal/key"; - -message AssetID { - option (gogoproto.goproto_stringer) = false; - - string classification_i_d = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; - string hash_i_d = 2 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/assets/internal/mappable/asset.proto b/proto/persistence_sdk/modules/assets/internal/mappable/asset.proto deleted file mode 100644 index e42ae0566..000000000 --- a/proto/persistence_sdk/modules/assets/internal/mappable/asset.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.assets.internal.mappable; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/traits/base/hasImmutables.proto"; -import "persistence_sdk/schema/traits/base/hasMutables.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/assets/internal/mappable"; - -message Asset { - option (gogoproto.goproto_getters) = false; - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.traits.base.HasImmutables has_immutables = 2 [(gogoproto.nullable) = false]; - persistence_sdk.schema.traits.base.HasMutables has_mutables = 3 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/assets/internal/parameters/dummy/parameter.proto b/proto/persistence_sdk/modules/assets/internal/parameters/dummy/parameter.proto deleted file mode 100644 index 17a784a4a..000000000 --- a/proto/persistence_sdk/modules/assets/internal/parameters/dummy/parameter.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.assets.internal.parameters.dummy; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/decData.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/assets/internal/parameters/dummy"; - -message DummyParameter { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.DecData data = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/assets/internal/queries/asset/query.proto b/proto/persistence_sdk/modules/assets/internal/queries/asset/query.proto deleted file mode 100644 index 33b2cca71..000000000 --- a/proto/persistence_sdk/modules/assets/internal/queries/asset/query.proto +++ /dev/null @@ -1,32 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.assets.internal.queries.asset; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/assets/internal/queries/asset"; - -message QueryRequest { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - persistence_sdk.schema.types.base.ID asset_i_d = 1 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required AssetID missing\""]; -} - -message QueryResponse { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - bool success = 1; - string error = 2 ; - repeated string list = 3 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable", (gogoproto.nullable) = false] ; - -} - -service Query { - rpc Enquire(QueryRequest) returns (QueryResponse) { - option (google.api.http).get = "/persistence/assets/asset"; - } -} \ No newline at end of file diff --git a/proto/persistence_sdk/modules/assets/internal/transactions/burn/message.proto b/proto/persistence_sdk/modules/assets/internal/transactions/burn/message.proto deleted file mode 100644 index f21f47a23..000000000 --- a/proto/persistence_sdk/modules/assets/internal/transactions/burn/message.proto +++ /dev/null @@ -1,23 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.assets.internal.transactions.burn; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/assets/internal/transactions/burn"; - -message Message { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\" required~required field From missing\""]; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.ID asset_i_d = 3 [(gogoproto.nullable) = false]; -} - -message TransactionResponse{} - -service Msg{ - rpc Burn(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/assets/internal/transactions/define/message.proto b/proto/persistence_sdk/modules/assets/internal/transactions/define/message.proto deleted file mode 100644 index 79c436a8c..000000000 --- a/proto/persistence_sdk/modules/assets/internal/transactions/define/message.proto +++ /dev/null @@ -1,28 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.assets.internal.transactions.define; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/metaProperties.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/assets/internal/transactions/define"; - -message Message { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\" required~required field From missing\""]; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\" required~required field FromID missing\""]; - persistence_sdk.schema.types.base.MetaProperties immutable_meta_properties = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\" required~required field ImmutableMetaProperties missing\""]; - persistence_sdk.schema.types.base.Properties immutable_properties = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\" required~required field ImmutableProperties missing\""]; - persistence_sdk.schema.types.base.MetaProperties mutable_meta_properties = 5 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\" required~required field MutableMetaProperties missing\""]; - persistence_sdk.schema.types.base.Properties mutable_properties = 6 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\" required~required field MutableProperties missing\""]; -} - -message TransactionResponse{} - -service Msg{ - rpc Define(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/assets/internal/transactions/deputize/message.proto b/proto/persistence_sdk/modules/assets/internal/transactions/deputize/message.proto deleted file mode 100644 index 15017b372..000000000 --- a/proto/persistence_sdk/modules/assets/internal/transactions/deputize/message.proto +++ /dev/null @@ -1,29 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.assets.internal.transactions.deputize; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/assets/internal/transactions/deputize"; - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field From missing\""] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field FromID missing\""] ; - persistence_sdk.schema.types.base.ID to_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field ToID missing\""] ; - persistence_sdk.schema.types.base.ID classification_i_d = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field ClassificationID missing\""] ; - persistence_sdk.schema.types.base.Properties maintained_properties = 5 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field MaintainedProperties missing\""] ; - bool add_maintainer = 6; - bool remove_maintainer = 7; - bool mutate_maintainer = 8; -} - -message TransactionResponse{} - -service Msg{ - rpc Deputize(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/assets/internal/transactions/mint/message.proto b/proto/persistence_sdk/modules/assets/internal/transactions/mint/message.proto deleted file mode 100644 index ef3d126d2..000000000 --- a/proto/persistence_sdk/modules/assets/internal/transactions/mint/message.proto +++ /dev/null @@ -1,30 +0,0 @@ -syntax = "proto3"; - -package modules.assets.internal.transactions.mint; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; -import "persistence_sdk/schema/types/base/metaProperties.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/assets/internal/transactions/mint"; - -message Message { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field From missing\""] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field FromID missing\""] ; - persistence_sdk.schema.types.base.ID to_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field ToID missing\""] ; - persistence_sdk.schema.types.base.ID classification_i_d = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field ClassificationID missing\""] ; - persistence_sdk.schema.types.base.MetaProperties immutable_meta_properties = 5 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field ImmutableMetaProperties missing\""]; - persistence_sdk.schema.types.base.Properties immutable_properties = 6 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field ImmutableProperties missing\""]; - persistence_sdk.schema.types.base.MetaProperties mutable_meta_properties = 7 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field MutableMetaProperties missing\""]; - persistence_sdk.schema.types.base.Properties mutable_properties = 8 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field MutableProperties missing\""]; -} - -message TransactionResponse{} - -service Msg{ - rpc Mint(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/assets/internal/transactions/mutate/message.proto b/proto/persistence_sdk/modules/assets/internal/transactions/mutate/message.proto deleted file mode 100644 index d43db2d16..000000000 --- a/proto/persistence_sdk/modules/assets/internal/transactions/mutate/message.proto +++ /dev/null @@ -1,27 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.assets.internal.transactions.mutate; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; -import "persistence_sdk/schema/types/base/metaProperties.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/assets/internal/transactions/mutate"; - -message Message { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field From missing\""] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field FromID missing\""] ; - persistence_sdk.schema.types.base.ID asset_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field AssetID missing\""] ; - persistence_sdk.schema.types.base.MetaProperties mutable_meta_properties = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field MutableMetaProperties missing\""] ; - persistence_sdk.schema.types.base.Properties mutable_properties = 5 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field MutableProperties missing\""] ; -} - -message TransactionResponse{} - -service Msg{ - rpc Mutate(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/assets/internal/transactions/renumerate/message.proto b/proto/persistence_sdk/modules/assets/internal/transactions/renumerate/message.proto deleted file mode 100644 index 7b47d2616..000000000 --- a/proto/persistence_sdk/modules/assets/internal/transactions/renumerate/message.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; - -package modules.assets.internal.transactions.renumerate; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/assets/internal/transactions/renumerate"; - -message Message { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field From missing\""] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field FromID missing\""] ; - persistence_sdk.schema.types.base.ID asset_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field AssetID missing\""]; -} - -message TransactionResponse{} - -service Msg{ - rpc Renumerate(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/assets/internal/transactions/revoke/message.proto b/proto/persistence_sdk/modules/assets/internal/transactions/revoke/message.proto deleted file mode 100644 index da168a9f7..000000000 --- a/proto/persistence_sdk/modules/assets/internal/transactions/revoke/message.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.assets.internal.transactions.revoke; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/assets/internal/transactions/revoke"; - -message Message { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field From missing\""] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field FromID missing\""] ; - persistence_sdk.schema.types.base.ID to_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field AssetID missing\""]; - persistence_sdk.schema.types.base.ID classification_i_d = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field ClassificationID missing\""]; -} - -message TransactionResponse{} - -service Msg{ - rpc Revoke(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/classifications/internal/genesis/genesis.proto b/proto/persistence_sdk/modules/classifications/internal/genesis/genesis.proto deleted file mode 100644 index 7c8833222..000000000 --- a/proto/persistence_sdk/modules/classifications/internal/genesis/genesis.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.classifications.internal.genesis; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/modules/classifications/internal/mappable/classification.proto"; -import "persistence_sdk/modules/classifications/internal/parameters/dummy/parameter.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/genesis"; - -message Genesis { - option (gogoproto.goproto_getters) = false; - repeated persistence_sdk.modules.classifications.internal.mappable.Classification defaultMappableList = 1 [(gogoproto.nullable) = false]; - repeated persistence_sdk.modules.classifications.internal.parameters.dummy.DummyParameter defaultParameterList = 2 [(gogoproto.nullable) = false]; - - repeated persistence_sdk.modules.classifications.internal.mappable.Classification MappableList = 3 [(gogoproto.nullable) = false]; - repeated persistence_sdk.modules.classifications.internal.parameters.dummy.DummyParameter ParameterList = 4 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/classifications/internal/key/classifictionID.proto b/proto/persistence_sdk/modules/classifications/internal/key/classifictionID.proto deleted file mode 100644 index 7382822ce..000000000 --- a/proto/persistence_sdk/modules/classifications/internal/key/classifictionID.proto +++ /dev/null @@ -1,14 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.classifications.internal.key; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/key"; - -message ClassificationID { - option (gogoproto.goproto_stringer) = false; - - string chain_i_d = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; - string hash_i_d = 2 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/classifications/internal/mappable/classification.proto b/proto/persistence_sdk/modules/classifications/internal/mappable/classification.proto deleted file mode 100644 index b3d7eebd7..000000000 --- a/proto/persistence_sdk/modules/classifications/internal/mappable/classification.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.classifications.internal.mappable; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/traits/base/hasImmutables.proto"; -import "persistence_sdk/schema/traits/base/hasMutables.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/mappable"; - -message Classification { - option (gogoproto.goproto_getters) = false; - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.traits.base.HasImmutables has_immutables = 2 [(gogoproto.nullable) = false]; - persistence_sdk.schema.traits.base.HasMutables has_mutables = 3 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/classifications/internal/parameters/dummy/parameter.proto b/proto/persistence_sdk/modules/classifications/internal/parameters/dummy/parameter.proto deleted file mode 100644 index 94db056da..000000000 --- a/proto/persistence_sdk/modules/classifications/internal/parameters/dummy/parameter.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.classifications.internal.parameters.dummy; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/decData.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/parameters/dummy"; - -message DummyParameter { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.DecData data = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/classifications/internal/queries/classification/query.proto b/proto/persistence_sdk/modules/classifications/internal/queries/classification/query.proto deleted file mode 100644 index 7897325fc..000000000 --- a/proto/persistence_sdk/modules/classifications/internal/queries/classification/query.proto +++ /dev/null @@ -1,32 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.classifications.internal.queries.classification; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/classifications/internal/queries/classification"; - -message QueryRequest { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - persistence_sdk.schema.types.base.ID classification_i_d = 1 [ (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required ClassificationID missing\""]; -} - -message QueryResponse { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - bool success = 1; - string error = 2 ; - repeated string list = 3 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable", (gogoproto.nullable) = false] ; - -} - -service Query { - rpc Enquire(QueryRequest) returns (QueryResponse) { - option (google.api.http).get = "/persistence/classifications/classification"; - } -} diff --git a/proto/persistence_sdk/modules/identities/internal/genesis/genesis.proto b/proto/persistence_sdk/modules/identities/internal/genesis/genesis.proto deleted file mode 100644 index 3eb0085f4..000000000 --- a/proto/persistence_sdk/modules/identities/internal/genesis/genesis.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.identities.internal.genesis; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/modules/identities/internal/parameters/dummy/parameter.proto"; -import "persistence_sdk/modules/identities/internal/mappable/identity.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/genesis"; - -message Genesis { - option (gogoproto.goproto_getters) = false; - repeated persistence_sdk.modules.identities.internal.mappable.Identity defaultMappableList = 1 [(gogoproto.nullable) = false ]; - repeated persistence_sdk.modules.identities.parameters.dummy.DummyParameter defaultParameterList = 2 [(gogoproto.nullable) = false ]; - - repeated persistence_sdk.modules.identities.internal.mappable.Identity MappableList = 3 [(gogoproto.nullable) = false ]; - repeated persistence_sdk.modules.identities.parameters.dummy.DummyParameter ParameterList = 4 [(gogoproto.nullable) = false ]; -} diff --git a/proto/persistence_sdk/modules/identities/internal/key/identityID.proto b/proto/persistence_sdk/modules/identities/internal/key/identityID.proto deleted file mode 100644 index 25470169d..000000000 --- a/proto/persistence_sdk/modules/identities/internal/key/identityID.proto +++ /dev/null @@ -1,14 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.identities.internal.key; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/key"; - -message IdentityID { - option (gogoproto.goproto_stringer) = false; - - string classification_i_d = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; - string hash_i_d = 2 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/identities/internal/mappable/identity.proto b/proto/persistence_sdk/modules/identities/internal/mappable/identity.proto deleted file mode 100644 index 44684da3f..000000000 --- a/proto/persistence_sdk/modules/identities/internal/mappable/identity.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.identities.internal.mappable; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/traits/base/hasImmutables.proto"; -import "persistence_sdk/schema/traits/base/hasMutables.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/mappable"; - -message Identity { - option (gogoproto.goproto_getters) = false; - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.traits.base.HasImmutables has_immutables = 2 [(gogoproto.nullable) = false]; - persistence_sdk.schema.traits.base.HasMutables has_mutables = 3 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/identities/internal/parameters/dummy/parameter.proto b/proto/persistence_sdk/modules/identities/internal/parameters/dummy/parameter.proto deleted file mode 100644 index 6f813fd6e..000000000 --- a/proto/persistence_sdk/modules/identities/internal/parameters/dummy/parameter.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.identities.parameters.dummy; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/decData.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/parameters/dummy"; - -message DummyParameter { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.DecData data = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/identities/internal/queries/identity/query.proto b/proto/persistence_sdk/modules/identities/internal/queries/identity/query.proto deleted file mode 100644 index d992ab099..000000000 --- a/proto/persistence_sdk/modules/identities/internal/queries/identity/query.proto +++ /dev/null @@ -1,32 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.identities.internal.queries.identity; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/queries/identity"; - -message QueryRequest { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - persistence_sdk.schema.types.base.ID identity_i_d = 1 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required IdentityID missing\""]; -} - -message QueryResponse { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - bool success = 1; - string error = 2 ; - repeated string list = 3 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable", (gogoproto.nullable) = false] ; - -} - -service Query { - rpc Enquire(QueryRequest) returns (QueryResponse) { - option (google.api.http).get = "/persistence/identities/identity"; - } -} diff --git a/proto/persistence_sdk/modules/identities/internal/transactions/define/message.proto b/proto/persistence_sdk/modules/identities/internal/transactions/define/message.proto deleted file mode 100644 index c80a1144d..000000000 --- a/proto/persistence_sdk/modules/identities/internal/transactions/define/message.proto +++ /dev/null @@ -1,28 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.identities.internal.transactions.define; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; -import "persistence_sdk/schema/types/base/metaProperties.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/transactions/define"; - -message Message { - option (gogoproto.equal) = false; - option (gogoproto.goproto_getters) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field From missing\""] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field FromID missing\""] ; - persistence_sdk.schema.types.base.MetaProperties immutable_meta_properties = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field ImmutableMetaProperties missing\""]; - persistence_sdk.schema.types.base.Properties immutable_properties = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field ImmutableProperties missing\""]; - persistence_sdk.schema.types.base.MetaProperties mutable_meta_properties = 5 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field MutableMetaProperties missing\""]; - persistence_sdk.schema.types.base.Properties mutable_properties = 6 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field MutableProperties missing\""]; -} - -message TransactionResponse{} - -service Msg{ - rpc Define(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/identities/internal/transactions/deputize/message.proto b/proto/persistence_sdk/modules/identities/internal/transactions/deputize/message.proto deleted file mode 100644 index 7d1bfc643..000000000 --- a/proto/persistence_sdk/modules/identities/internal/transactions/deputize/message.proto +++ /dev/null @@ -1,29 +0,0 @@ -syntax = "proto3"; - -package modules.identities.internal.transactions.deputize; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/transactions/deputize"; - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field from missing\""] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field fromID missing\""] ; - persistence_sdk.schema.types.base.ID to_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field toID missing\""] ; - persistence_sdk.schema.types.base.ID classification_i_d = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field classificationID missing\""] ; - persistence_sdk.schema.types.base.Properties maintained_properties = 5 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field maintainedProperties missing\""] ; - bool add_maintainer = 6; - bool remove_maintainer = 7; - bool mutate_maintainer = 8; -} - -message TransactionResponse{} - -service Msg{ - rpc Deputize(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/identities/internal/transactions/issue/message.proto b/proto/persistence_sdk/modules/identities/internal/transactions/issue/message.proto deleted file mode 100644 index 689b95750..000000000 --- a/proto/persistence_sdk/modules/identities/internal/transactions/issue/message.proto +++ /dev/null @@ -1,30 +0,0 @@ -syntax = "proto3"; - -package modules.identities.internal.transactions.issue; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; -import "persistence_sdk/schema/types/base/metaProperties.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/transactions/issue"; - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false,(gogoproto.moretags) = "valid:\"required~required field From missing\""] ; - string to = 2 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false,(gogoproto.moretags) = "valid:\"required~required field To missing\""] ; - persistence_sdk.schema.types.base.ID from_i_d = 3 [(gogoproto.nullable) = false,(gogoproto.moretags) = "valid:\"required~required field FromID missing\""] ; - persistence_sdk.schema.types.base.ID classification_i_d = 4 [(gogoproto.nullable) = false,(gogoproto.moretags) = "valid:\"required~required field ClassificationID missing\""] ; - persistence_sdk.schema.types.base.MetaProperties immutable_meta_properties = 5 [(gogoproto.nullable) = false,(gogoproto.moretags) = "valid:\"required~required field ImmutableMetaProperties missing\""]; - persistence_sdk.schema.types.base.Properties immutable_properties = 6 [(gogoproto.nullable) = false,(gogoproto.moretags) = "valid:\"required~required field ImmutableProperties missing\""]; - persistence_sdk.schema.types.base.MetaProperties mutable_meta_properties = 7 [(gogoproto.nullable) = false,(gogoproto.moretags) = "valid:\"required~required field MutableMetaProperties missing\""]; - persistence_sdk.schema.types.base.Properties mutable_properties = 8 [(gogoproto.nullable) = false,(gogoproto.moretags) = "valid:\"required~required field MutableProperties missing\""]; -} - -message TransactionResponse{} - -service Msg{ - rpc Issue(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/identities/internal/transactions/mutate/message.proto b/proto/persistence_sdk/modules/identities/internal/transactions/mutate/message.proto deleted file mode 100644 index ecd038938..000000000 --- a/proto/persistence_sdk/modules/identities/internal/transactions/mutate/message.proto +++ /dev/null @@ -1,27 +0,0 @@ -syntax = "proto3"; - -package modules.identities.internal.transactions.mutate; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; -import "persistence_sdk/schema/types/base/metaProperties.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/transactions/mutate"; - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field From missing\""] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field FromID missing\""] ; - persistence_sdk.schema.types.base.ID identity_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field IdentityID missing\""] ; - persistence_sdk.schema.types.base.MetaProperties mutable_meta_properties = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field MutableMetaProperties missing\""]; - persistence_sdk.schema.types.base.Properties mutable_properties = 5 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field MutableProperties missing\""]; -} - -message TransactionResponse{} - -service Msg{ - rpc Mutate(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/identities/internal/transactions/nub/message.proto b/proto/persistence_sdk/modules/identities/internal/transactions/nub/message.proto deleted file mode 100644 index f20b23e7a..000000000 --- a/proto/persistence_sdk/modules/identities/internal/transactions/nub/message.proto +++ /dev/null @@ -1,22 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.identities.internal.transactions.nub; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/transactions/nub"; - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field From missing\""] ; - persistence_sdk.schema.types.base.ID nub_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field NubID missing\""] ; -} - -message TransactionResponse{} - -service Msg{ - rpc Nub(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/identities/internal/transactions/provision/message.proto b/proto/persistence_sdk/modules/identities/internal/transactions/provision/message.proto deleted file mode 100644 index 6bdbe00a4..000000000 --- a/proto/persistence_sdk/modules/identities/internal/transactions/provision/message.proto +++ /dev/null @@ -1,23 +0,0 @@ -syntax = "proto3"; - -package modules.identities.internal.transactions.provision; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/transactions/provision"; - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field From missing\""]; - string to = 2 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field To missing\""] ; - persistence_sdk.schema.types.base.ID identity_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required IdentityID missing\""]; -} - -message TransactionResponse{} - -service Msg{ - rpc Provision(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/identities/internal/transactions/quash/message.proto b/proto/persistence_sdk/modules/identities/internal/transactions/quash/message.proto deleted file mode 100644 index 1456750b2..000000000 --- a/proto/persistence_sdk/modules/identities/internal/transactions/quash/message.proto +++ /dev/null @@ -1,23 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.identities.internal.transactions.quash; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/transactions/quash"; - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required From missing\""] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required FromID missing\""] ; - persistence_sdk.schema.types.base.ID identity_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required IdentityID missing\""]; -} - -message TransactionResponse{} - -service Msg{ - rpc Quash(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/identities/internal/transactions/revoke/message.proto b/proto/persistence_sdk/modules/identities/internal/transactions/revoke/message.proto deleted file mode 100644 index 8bb76d5df..000000000 --- a/proto/persistence_sdk/modules/identities/internal/transactions/revoke/message.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.identities.internal.transactions.revoke; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/transactions/revoke"; - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required From missing\""] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required FromID missing\""] ; - persistence_sdk.schema.types.base.ID to_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required ToID missing\""]; - persistence_sdk.schema.types.base.ID classification_i_d = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required ClassificationID missing\""]; -} - -message TransactionResponse{} - -service Msg{ - rpc Revoke(Message) returns (TransactionResponse); -} diff --git a/proto/persistence_sdk/modules/identities/internal/transactions/unprovision/message.proto b/proto/persistence_sdk/modules/identities/internal/transactions/unprovision/message.proto deleted file mode 100644 index 590be1241..000000000 --- a/proto/persistence_sdk/modules/identities/internal/transactions/unprovision/message.proto +++ /dev/null @@ -1,23 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.identities.internal.transactions.unprovision; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/identities/internal/transactions/unprovision"; - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required From missing\""] ; - string to = 2 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required field To missing\""] ; - persistence_sdk.schema.types.base.ID identity_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required IdentityID missing\""]; -} - -message TransactionResponse{} - -service Msg{ - rpc Unprovision(Message) returns (TransactionResponse){}; -} diff --git a/proto/persistence_sdk/modules/maintainers/internal/genesis/genesis.proto b/proto/persistence_sdk/modules/maintainers/internal/genesis/genesis.proto deleted file mode 100644 index a29dc6590..000000000 --- a/proto/persistence_sdk/modules/maintainers/internal/genesis/genesis.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.maintainers.internal.genesis; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/modules/maintainers/internal/parameters/dummy/parameter.proto"; -import "persistence_sdk/modules/maintainers/internal/mappable/maintainer.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/genesis"; - -message Genesis { - option (gogoproto.goproto_getters) = false; - repeated persistence_sdk.modules.maintainers.internal.mappable.Maintainer defaultMappableList = 1 [(gogoproto.nullable) = false ]; - repeated persistence_sdk.modules.maintainers.internal.parameters.dummy.DummyParameter defaultParameterList = 2 [(gogoproto.nullable) = false ]; - - repeated persistence_sdk.modules.maintainers.internal.mappable.Maintainer MappableList = 3 [(gogoproto.nullable) = false ]; - repeated persistence_sdk.modules.maintainers.internal.parameters.dummy.DummyParameter ParameterList = 4 [(gogoproto.nullable) = false ]; -} diff --git a/proto/persistence_sdk/modules/maintainers/internal/key/maintainerID.proto b/proto/persistence_sdk/modules/maintainers/internal/key/maintainerID.proto deleted file mode 100644 index bb9ce9977..000000000 --- a/proto/persistence_sdk/modules/maintainers/internal/key/maintainerID.proto +++ /dev/null @@ -1,14 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.maintainers.internal.key; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/key"; - -message MaintainerID { - option (gogoproto.goproto_stringer) = false; - - string classification_i_d = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; - string identity_i_d = 2 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/maintainers/internal/mappable/maintainer.proto b/proto/persistence_sdk/modules/maintainers/internal/mappable/maintainer.proto deleted file mode 100644 index f6f0e5483..000000000 --- a/proto/persistence_sdk/modules/maintainers/internal/mappable/maintainer.proto +++ /dev/null @@ -1,20 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.maintainers.internal.mappable; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/traits/base/hasImmutables.proto"; -import "persistence_sdk/schema/traits/base/hasMutables.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/mappable"; - -message Maintainer { - option (gogoproto.goproto_getters) = false; - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.Properties maintained_properties = 2 [(gogoproto.nullable) = false]; - bool add_maintainer = 3; - bool remove_maintainer = 4; - bool mutate_maintainer = 5; -} diff --git a/proto/persistence_sdk/modules/maintainers/internal/parameters/dummy/parameter.proto b/proto/persistence_sdk/modules/maintainers/internal/parameters/dummy/parameter.proto deleted file mode 100644 index fee2e55d0..000000000 --- a/proto/persistence_sdk/modules/maintainers/internal/parameters/dummy/parameter.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.maintainers.internal.parameters.dummy; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/decData.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/parameters/dummy"; - -message DummyParameter { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.DecData data = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/maintainers/internal/queries/maintainer/query.proto b/proto/persistence_sdk/modules/maintainers/internal/queries/maintainer/query.proto deleted file mode 100644 index 8cea845a2..000000000 --- a/proto/persistence_sdk/modules/maintainers/internal/queries/maintainer/query.proto +++ /dev/null @@ -1,32 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.maintainers.internal.queries.maintainer; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/maintainers/internal/queries/maintainer"; - -message QueryRequest { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - persistence_sdk.schema.types.base.ID maintainer_i_d = 1 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required MaintainerID missing\""]; -} - -message QueryResponse { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - bool success = 1; - string error = 2 ; - repeated string list = 3 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable", (gogoproto.nullable) = false] ; - -} - -service Query { - rpc Enquire(QueryRequest) returns (QueryResponse) { - option (google.api.http).get = "/persistence/maintainers/maintainer"; - } -} diff --git a/proto/persistence_sdk/modules/metas/internal/genesis/genesis.proto b/proto/persistence_sdk/modules/metas/internal/genesis/genesis.proto deleted file mode 100644 index 786f25616..000000000 --- a/proto/persistence_sdk/modules/metas/internal/genesis/genesis.proto +++ /dev/null @@ -1,19 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.metas.internal.genesis; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/modules/metas/internal/parameters/dummy/parameter.proto"; -import "persistence_sdk/modules/metas/internal/mappable/meta.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/metas/internal/genesis"; - -message Genesis { - option (gogoproto.goproto_getters) = false; - repeated persistence_sdk.modules.metas.internal.mappable.Meta defaultMappableList = 1 [(gogoproto.nullable) = false]; - repeated persistence_sdk.modules.metas.internal.parameters.dummy.DummyParameter defaultParameterList = 2 [(gogoproto.nullable) = false]; - - repeated persistence_sdk.modules.metas.internal.mappable.Meta MappableList = 3 [(gogoproto.nullable) = false]; - repeated persistence_sdk.modules.metas.internal.parameters.dummy.DummyParameter ParameterList = 4 [(gogoproto.nullable) = false]; - -} diff --git a/proto/persistence_sdk/modules/metas/internal/key/metaID.proto b/proto/persistence_sdk/modules/metas/internal/key/metaID.proto deleted file mode 100644 index a15af1497..000000000 --- a/proto/persistence_sdk/modules/metas/internal/key/metaID.proto +++ /dev/null @@ -1,15 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.metas.internal.key; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/metas/internal/key"; - -message MetaID { - option (gogoproto.goproto_stringer) = false; - - persistence_sdk.schema.types.base.ID type_i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.ID hash_i_d = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/metas/internal/mappable/meta.proto b/proto/persistence_sdk/modules/metas/internal/mappable/meta.proto deleted file mode 100644 index 055b4ac46..000000000 --- a/proto/persistence_sdk/modules/metas/internal/mappable/meta.proto +++ /dev/null @@ -1,15 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.metas.internal.mappable; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/data.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/metas/internal/mappable"; - -message Meta { - option (gogoproto.goproto_getters) = false; - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.Data data = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/metas/internal/parameters/dummy/parameter.proto b/proto/persistence_sdk/modules/metas/internal/parameters/dummy/parameter.proto deleted file mode 100644 index d7590698c..000000000 --- a/proto/persistence_sdk/modules/metas/internal/parameters/dummy/parameter.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.metas.internal.parameters.dummy; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/decData.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/metas/internal/parameters/dummy"; - -message DummyParameter { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.DecData data = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/metas/internal/queries/meta/query.proto b/proto/persistence_sdk/modules/metas/internal/queries/meta/query.proto deleted file mode 100644 index 5e7c18227..000000000 --- a/proto/persistence_sdk/modules/metas/internal/queries/meta/query.proto +++ /dev/null @@ -1,32 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.metas.internal.queries.meta; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/metas/internal/queries/meta"; - -message QueryRequest { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - persistence_sdk.schema.types.base.ID meta_i_d = 1 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required MetaID missing\""]; -} - -message QueryResponse { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - bool success = 1; - string error = 2 ; - repeated string list = 3 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable", (gogoproto.nullable) = false] ; - -} - -service Query { - rpc Get(QueryRequest) returns (QueryResponse) { - option (google.api.http).get = "/persistence/metas/meta"; - } -} diff --git a/proto/persistence_sdk/modules/metas/internal/transactions/reveal/message.proto b/proto/persistence_sdk/modules/metas/internal/transactions/reveal/message.proto deleted file mode 100644 index 8d0650c0d..000000000 --- a/proto/persistence_sdk/modules/metas/internal/transactions/reveal/message.proto +++ /dev/null @@ -1,22 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.metas.internal.transactions.reveal; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/metaFact.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/metas/internal/transactions/reveal"; - -service Msg { - rpc Reveal(Message) returns (TransactionResponse) {}; -} - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field From missing"'] ; - persistence_sdk.schema.types.base.MetaFact meta_fact = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MetaFact missing"'] ; -} - -message TransactionResponse {} diff --git a/proto/persistence_sdk/modules/orders/internal/genesis/genesis.proto b/proto/persistence_sdk/modules/orders/internal/genesis/genesis.proto deleted file mode 100644 index f415fa2be..000000000 --- a/proto/persistence_sdk/modules/orders/internal/genesis/genesis.proto +++ /dev/null @@ -1,19 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.orders.internal.genesis; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/modules/orders/internal/parameters/dummy/parameter.proto"; -import "persistence_sdk/modules/orders/internal/mappable/order.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/orders/internal/genesis"; - -message Genesis { - option (gogoproto.goproto_getters) = false; - repeated persistence_sdk.modules.orders.internal.mappable.Order defaultMappableList = 1 [(gogoproto.nullable) = false]; - repeated persistence_sdk.modules.orders.internal.parameters.dummy.DummyParameter defaultParameterList = 2 [(gogoproto.nullable) = false]; - - repeated persistence_sdk.modules.orders.internal.mappable.Order MappableList = 3 [(gogoproto.nullable) = false]; - repeated persistence_sdk.modules.orders.internal.parameters.dummy.DummyParameter ParameterList = 4 [(gogoproto.nullable) = false]; - -} diff --git a/proto/persistence_sdk/modules/orders/internal/key/orderID.proto b/proto/persistence_sdk/modules/orders/internal/key/orderID.proto deleted file mode 100644 index a3ae8a026..000000000 --- a/proto/persistence_sdk/modules/orders/internal/key/orderID.proto +++ /dev/null @@ -1,19 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.orders.internal.key; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/orders/internal/key"; - -message OrderID { - option (gogoproto.goproto_stringer) = false; - - string classification_i_d = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; - string maker_ownable_i_d = 2 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; - string taker_ownable_i_d = 3 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; - string rate_i_d = 4 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; - string creation_i_d = 5 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; - string maker_i_d = 6 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; - string hash_i_d = 7 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/orders/internal/mappable/order.proto b/proto/persistence_sdk/modules/orders/internal/mappable/order.proto deleted file mode 100644 index e89cbda5f..000000000 --- a/proto/persistence_sdk/modules/orders/internal/mappable/order.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.orders.internal.mappable; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/traits/base/hasImmutables.proto"; -import "persistence_sdk/schema/traits/base/hasMutables.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/orders/internal/mappable"; - -message Order { - option (gogoproto.goproto_getters) = false; - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - schema.traits.base.HasImmutables has_immutables = 2 [(gogoproto.nullable) = false]; - schema.traits.base.HasMutables has_mutables = 3 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/orders/internal/parameters/dummy/parameter.proto b/proto/persistence_sdk/modules/orders/internal/parameters/dummy/parameter.proto deleted file mode 100644 index 090fa2e02..000000000 --- a/proto/persistence_sdk/modules/orders/internal/parameters/dummy/parameter.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.orders.internal.parameters.dummy; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/decData.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/orders/internal/parameters/dummy"; - -message DummyParameter { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.DecData data = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/orders/internal/queries/order/query.proto b/proto/persistence_sdk/modules/orders/internal/queries/order/query.proto deleted file mode 100644 index 7a07bb50a..000000000 --- a/proto/persistence_sdk/modules/orders/internal/queries/order/query.proto +++ /dev/null @@ -1,32 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.orders.internal.queries.order; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/orders/internal/queries/order"; - -message QueryRequest { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - persistence_sdk.schema.types.base.ID order_i_d = 1 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required OrderID missing\""]; -} - -message QueryResponse { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - bool success = 1; - string error = 2 ; - repeated string list = 3 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable", (gogoproto.nullable) = false] ; - -} - -service Query { - rpc Enquire(QueryRequest) returns (QueryResponse) { - option (google.api.http).get = "/persistence/orders/order"; - } -} diff --git a/proto/persistence_sdk/modules/orders/internal/transactions/cancel/message.proto b/proto/persistence_sdk/modules/orders/internal/transactions/cancel/message.proto deleted file mode 100644 index a2f8563bb..000000000 --- a/proto/persistence_sdk/modules/orders/internal/transactions/cancel/message.proto +++ /dev/null @@ -1,23 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.orders.internal.transactions.cancel; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/orders/internal/transactions/cancel"; - -service Msg { - rpc Cancel(Message) returns (TransactionResponse) {}; -} - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field From missing"'] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field FromID missing"'] ; - persistence_sdk.schema.types.base.ID order_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field OrderID missing"'] ; -} - -message TransactionResponse {} diff --git a/proto/persistence_sdk/modules/orders/internal/transactions/define/message.proto b/proto/persistence_sdk/modules/orders/internal/transactions/define/message.proto deleted file mode 100644 index 1228d6a18..000000000 --- a/proto/persistence_sdk/modules/orders/internal/transactions/define/message.proto +++ /dev/null @@ -1,28 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.orders.internal.transactions.define; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; -import "persistence_sdk/schema/types/base/metaProperties.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/orders/internal/transactions/define"; - -service Msg { - rpc Define(Message) returns (TransactionResponse) {}; -} - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field From missing"'] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field FromID missing"'] ; - persistence_sdk.schema.types.base.MetaProperties immutable_meta_properties = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ImmutableMetaProperties missing"']; - persistence_sdk.schema.types.base.Properties immutable_properties = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ImmutableProperties missing"']; - persistence_sdk.schema.types.base.MetaProperties mutable_meta_properties = 5 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MutableMetaProperties missing"']; - persistence_sdk.schema.types.base.Properties mutable_properties = 6 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MutableProperties missing"']; -} - -message TransactionResponse {} diff --git a/proto/persistence_sdk/modules/orders/internal/transactions/deputize/message.proto b/proto/persistence_sdk/modules/orders/internal/transactions/deputize/message.proto deleted file mode 100644 index df242edde..000000000 --- a/proto/persistence_sdk/modules/orders/internal/transactions/deputize/message.proto +++ /dev/null @@ -1,29 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.orders.internal.transactions.deputize; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/orders/internal/transactions/deputize"; - -service Msg { - rpc Deputize(Message) returns (TransactionResponse) {}; -} - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field From missing"'] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field FromID missing"'] ; - persistence_sdk.schema.types.base.ID to_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ToID missing"']; - persistence_sdk.schema.types.base.ID classification_i_d = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ClassificationID missing"']; - persistence_sdk.schema.types.base.Properties maintained_properties = 5 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MaintainedProperties missing"']; - bool add_maintainer = 6 ; - bool remove_maintainer = 7 ; - bool mutate_maintainer = 8; -} - -message TransactionResponse {} diff --git a/proto/persistence_sdk/modules/orders/internal/transactions/immediate/message.proto b/proto/persistence_sdk/modules/orders/internal/transactions/immediate/message.proto deleted file mode 100644 index 891d50080..000000000 --- a/proto/persistence_sdk/modules/orders/internal/transactions/immediate/message.proto +++ /dev/null @@ -1,35 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.orders.internal.transactions.immediate; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/height.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; -import "persistence_sdk/schema/types/base/metaProperties.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/orders/internal/transactions/immediate"; - -service Msg { - rpc Immediate(Message) returns (TransactionResponse) {}; -} - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field From missing"'] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field FromID missing"'] ; - persistence_sdk.schema.types.base.ID classification_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ClassificationID missing"']; - persistence_sdk.schema.types.base.ID maker_ownable_i_d = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MakerOwnableID missing"']; - persistence_sdk.schema.types.base.ID taker_ownable_i_d = 5 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field TakerOwnableID missing"']; - persistence_sdk.schema.types.base.Height expires_in = 6 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ExpiresIn missing"']; - string maker_ownable_split = 7 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MakerOwnableSplit missing"']; - string taker_ownable_split = 8 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field TakerOwnableSplit missing"']; - persistence_sdk.schema.types.base.MetaProperties immutable_meta_properties = 9 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ImmutableMetaProperties missing"']; - persistence_sdk.schema.types.base.Properties immutable_properties = 10 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ImmutableProperties missing"']; - persistence_sdk.schema.types.base.MetaProperties mutable_meta_properties = 11 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MutableMetaProperties missing"']; - persistence_sdk.schema.types.base.Properties mutable_properties = 12 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MutableProperties missing"']; -} - -message TransactionResponse {} diff --git a/proto/persistence_sdk/modules/orders/internal/transactions/make/message.proto b/proto/persistence_sdk/modules/orders/internal/transactions/make/message.proto deleted file mode 100644 index 499275041..000000000 --- a/proto/persistence_sdk/modules/orders/internal/transactions/make/message.proto +++ /dev/null @@ -1,35 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.orders.internal.transactions.make; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; -import "persistence_sdk/schema/types/base/metaProperties.proto"; -import "persistence_sdk/schema/types/base/height.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/orders/internal/transactions/make"; - -service Msg { - rpc Make(Message) returns (TransactionResponse) {}; -} - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field From missing"'] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field FromID missing"'] ; - persistence_sdk.schema.types.base.ID classification_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ClassificationID missing"']; - persistence_sdk.schema.types.base.ID maker_ownable_i_d = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MakerOwnableID missing"']; - persistence_sdk.schema.types.base.ID taker_ownable_i_d = 5 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field TakerOwnableID missing"']; - persistence_sdk.schema.types.base.Height expires_in = 6 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ExpiresIn missing"']; - string maker_ownable_split = 7 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MakerOwnableSplit missing"']; - string taker_ownable_split = 8 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field TakerOwnableSplit missing"']; - persistence_sdk.schema.types.base.MetaProperties immutable_meta_properties = 9 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ImmutableMetaProperties missing"']; - persistence_sdk.schema.types.base.Properties immutable_properties = 10 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ImmutableProperties missing"']; - persistence_sdk.schema.types.base.MetaProperties mutable_meta_properties = 11 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MutableMetaProperties missing"']; - persistence_sdk.schema.types.base.Properties mutable_properties = 12 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MutableProperties missing"']; -} - -message TransactionResponse {} diff --git a/proto/persistence_sdk/modules/orders/internal/transactions/modify/message.proto b/proto/persistence_sdk/modules/orders/internal/transactions/modify/message.proto deleted file mode 100644 index 3419d169f..000000000 --- a/proto/persistence_sdk/modules/orders/internal/transactions/modify/message.proto +++ /dev/null @@ -1,31 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.orders.internal.transactions.modify; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; -import "persistence_sdk/schema/types/base/metaProperties.proto"; -import "persistence_sdk/schema/types/base/height.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/orders/internal/transactions/modify"; - -service Msg { - rpc Modify(Message) returns (TransactionResponse) {}; -} - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field From missing"'] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field FromID missing"'] ; - persistence_sdk.schema.types.base.ID order_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field OrderID missing"']; - string maker_ownable_split = 4 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MakerOwnableSplit missing"']; - string taker_ownable_split = 5 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field TakerOwnableSplit missing"']; - persistence_sdk.schema.types.base.Height expires_in = 6 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ExpiresIn missing"']; - persistence_sdk.schema.types.base.MetaProperties mutable_meta_properties = 7 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MutableMetaProperties missing"']; - persistence_sdk.schema.types.base.Properties mutable_properties = 8 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field MutableProperties missing"']; -} - -message TransactionResponse {} diff --git a/proto/persistence_sdk/modules/orders/internal/transactions/revoke/message.proto b/proto/persistence_sdk/modules/orders/internal/transactions/revoke/message.proto deleted file mode 100644 index f6e3dbdee..000000000 --- a/proto/persistence_sdk/modules/orders/internal/transactions/revoke/message.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.orders.internal.transactions.revoke; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/orders/internal/transactions/revoke"; - -service Msg { - rpc Revoke(Message) returns (TransactionResponse) {}; -} - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field From missing"'] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field FromID missing"'] ; - persistence_sdk.schema.types.base.ID to_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ToID missing"']; - persistence_sdk.schema.types.base.ID classification_i_d = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ClassificationID missing"']; -} - -message TransactionResponse {} diff --git a/proto/persistence_sdk/modules/orders/internal/transactions/take/message.proto b/proto/persistence_sdk/modules/orders/internal/transactions/take/message.proto deleted file mode 100644 index 14872af1e..000000000 --- a/proto/persistence_sdk/modules/orders/internal/transactions/take/message.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.orders.internal.transactions.take; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/orders/internal/transactions/take"; - -service Msg { - rpc Take(Message) returns (TransactionResponse) {}; -} - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field From missing"'] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field FromID missing"'] ; - string taker_ownable_split = 3 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field TakerOwnableSplit missing"']; - persistence_sdk.schema.types.base.ID order_i_d = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field OrderID missing"']; -} - -message TransactionResponse {} diff --git a/proto/persistence_sdk/modules/splits/internal/genesis/genesis.proto b/proto/persistence_sdk/modules/splits/internal/genesis/genesis.proto deleted file mode 100644 index 93887246c..000000000 --- a/proto/persistence_sdk/modules/splits/internal/genesis/genesis.proto +++ /dev/null @@ -1,19 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.splits.internal.genesis; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/modules/splits/internal/parameters/dummy/parameter.proto"; -import "persistence_sdk/modules/splits/internal/mappable/split.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/splits/internal/genesis"; - -message Genesis { - option (gogoproto.goproto_getters) = false; - repeated persistence_sdk.modules.splits.internal.mappable.Split defaultMappableList = 1 [(gogoproto.nullable) = false]; - repeated persistence_sdk.modules.splits.internal.parameters.dummy.DummyParameter defaultParameterList = 2 [(gogoproto.nullable) = false]; - - repeated persistence_sdk.modules.splits.internal.mappable.Split MappableList = 3 [(gogoproto.nullable) = false]; - repeated persistence_sdk.modules.splits.internal.parameters.dummy.DummyParameter ParameterList = 4 [(gogoproto.nullable) = false]; - -} diff --git a/proto/persistence_sdk/modules/splits/internal/key/splitID.proto b/proto/persistence_sdk/modules/splits/internal/key/splitID.proto deleted file mode 100644 index 296f4a059..000000000 --- a/proto/persistence_sdk/modules/splits/internal/key/splitID.proto +++ /dev/null @@ -1,14 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.splits.internal.key; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/splits/internal/key"; - -message SplitID { - option (gogoproto.goproto_stringer) = false; - - string owner_i_d = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; - string ownable_i_d = 2 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types.ID", (gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/splits/internal/mappable/split.proto b/proto/persistence_sdk/modules/splits/internal/mappable/split.proto deleted file mode 100644 index 4caa7d451..000000000 --- a/proto/persistence_sdk/modules/splits/internal/mappable/split.proto +++ /dev/null @@ -1,14 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.splits.internal.mappable; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/splits/internal/mappable"; - -message Split { - option (gogoproto.goproto_getters) = false; - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - string value = 2 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/splits/internal/parameters/dummy/parameter.proto b/proto/persistence_sdk/modules/splits/internal/parameters/dummy/parameter.proto deleted file mode 100644 index 6858d68d9..000000000 --- a/proto/persistence_sdk/modules/splits/internal/parameters/dummy/parameter.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.splits.internal.parameters.dummy; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/decData.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/splits/internal/parameters/dummy"; - -message DummyParameter { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.DecData data = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/modules/splits/internal/queries/ownable/query.proto b/proto/persistence_sdk/modules/splits/internal/queries/ownable/query.proto deleted file mode 100644 index 0cc0268be..000000000 --- a/proto/persistence_sdk/modules/splits/internal/queries/ownable/query.proto +++ /dev/null @@ -1,32 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.splits.internal.queries.ownable; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/splits/internal/queries/ownable"; - -message QueryRequest { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - persistence_sdk.schema.types.base.ID ownable_i_d = 1 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required OwnableID missing\""]; -} - -message QueryResponse { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - bool success = 1; - string error = 2 ; - string value = 3 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false] ; - -} - -service Query { - rpc Enquire(QueryRequest) returns (QueryResponse) { - option (google.api.http).get = "/persistence/splits/ownable"; - } -} diff --git a/proto/persistence_sdk/modules/splits/internal/queries/split/query.proto b/proto/persistence_sdk/modules/splits/internal/queries/split/query.proto deleted file mode 100644 index 887a18a66..000000000 --- a/proto/persistence_sdk/modules/splits/internal/queries/split/query.proto +++ /dev/null @@ -1,32 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.splits.internal.queries.split; - -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/splits/internal/queries/split"; - -message QueryRequest { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - persistence_sdk.schema.types.base.ID split_i_d = 1 [(gogoproto.nullable) = false, (gogoproto.moretags) = "valid:\"required~required splitID missing\""]; -} - -message QueryResponse { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - bool success = 1; - string error = 2 ; - repeated string list = 3 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/helpers.Mappable", (gogoproto.nullable) = false] ; - -} - -service Query { - rpc Enquire(QueryRequest) returns (QueryResponse) { - option (google.api.http).get = "/persistence/splits/split"; - } -} diff --git a/proto/persistence_sdk/modules/splits/internal/transactions/send/message.proto b/proto/persistence_sdk/modules/splits/internal/transactions/send/message.proto deleted file mode 100644 index e6746f1eb..000000000 --- a/proto/persistence_sdk/modules/splits/internal/transactions/send/message.proto +++ /dev/null @@ -1,25 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.splits.internal.transactions.send; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/splits/internal/transactions/send"; - -service Msg { - rpc Send(Message) returns (TransactionResponse) {}; -} - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field From missing"']; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field FromID missing"'] ; - persistence_sdk.schema.types.base.ID to_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field ToID missing"']; - persistence_sdk.schema.types.base.ID ownable_i_d = 4 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field OwnableID missing"']; - string value = 5 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field Value missing"']; -} - -message TransactionResponse {} diff --git a/proto/persistence_sdk/modules/splits/internal/transactions/unwrap/message.proto b/proto/persistence_sdk/modules/splits/internal/transactions/unwrap/message.proto deleted file mode 100644 index d308854d3..000000000 --- a/proto/persistence_sdk/modules/splits/internal/transactions/unwrap/message.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.splits.internal.transactions.unwrap; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/splits/internal/transactions/unwrap"; - -service Msg { - rpc Unwrap(Message) returns (TransactionResponse) {}; -} - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field From missing"'] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field FromID missing"'] ; - persistence_sdk.schema.types.base.ID ownable_i_d = 3 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field OwnableID missing"']; - string value = 4 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field Value missing"']; -} - -message TransactionResponse {} diff --git a/proto/persistence_sdk/modules/splits/internal/transactions/wrap/message.proto b/proto/persistence_sdk/modules/splits/internal/transactions/wrap/message.proto deleted file mode 100644 index 257c27e44..000000000 --- a/proto/persistence_sdk/modules/splits/internal/transactions/wrap/message.proto +++ /dev/null @@ -1,23 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.modules.splits.internal.transactions.wrap; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/modules/splits/internal/transactions/wrap"; - -service Msg { - rpc Wrap(Message) returns (TransactionResponse) {}; -} - -message Message { - option (gogoproto.goproto_getters) = false; - option (gogoproto.equal) = false; - - string from = 1 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.AccAddress", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field From missing"'] ; - persistence_sdk.schema.types.base.ID from_i_d = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field FromID missing"'] ; - repeated string coins = 3 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Coin", (gogoproto.nullable) = false, (gogoproto.moretags) = 'valid:"required~required field Coins missing"', (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; -} - -message TransactionResponse {} diff --git a/proto/persistence_sdk/schema/traits/base/hasImmutables.proto b/proto/persistence_sdk/schema/traits/base/hasImmutables.proto deleted file mode 100644 index d912a22e7..000000000 --- a/proto/persistence_sdk/schema/traits/base/hasImmutables.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.traits.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/traits/base"; - -message HasImmutables { - persistence_sdk.schema.types.base.Properties properties = 1 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/traits/base/hasMutables.proto b/proto/persistence_sdk/schema/traits/base/hasMutables.proto deleted file mode 100644 index 309ad8c5f..000000000 --- a/proto/persistence_sdk/schema/traits/base/hasMutables.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.traits.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/properties.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/traits/base"; - -message HasMutables { - persistence_sdk.schema.types.base.Properties properties = 1 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/accAddress.proto b/proto/persistence_sdk/schema/types/base/accAddress.proto deleted file mode 100644 index d6f0c4bc0..000000000 --- a/proto/persistence_sdk/schema/types/base/accAddress.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message AccAddress { - option (gogoproto.goproto_stringer) = false; - - bytes value = 1; -} diff --git a/proto/persistence_sdk/schema/types/base/accAddressData.proto b/proto/persistence_sdk/schema/types/base/accAddressData.proto deleted file mode 100644 index 853c10685..000000000 --- a/proto/persistence_sdk/schema/types/base/accAddressData.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/accAddress.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message AccAddressData { - option (gogoproto.goproto_stringer) = false; - schema.types.base.AccAddress value = 1 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/customError.proto b/proto/persistence_sdk/schema/types/base/customError.proto deleted file mode 100644 index a9ff7bc3e..000000000 --- a/proto/persistence_sdk/schema/types/base/customError.proto +++ /dev/null @@ -1,9 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message CustomError { - string proto_error = 1; -} diff --git a/proto/persistence_sdk/schema/types/base/data.proto b/proto/persistence_sdk/schema/types/base/data.proto deleted file mode 100644 index 0756ab2b9..000000000 --- a/proto/persistence_sdk/schema/types/base/data.proto +++ /dev/null @@ -1,23 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/decData.proto"; -import "persistence_sdk/schema/types/base/heightData.proto"; -import "persistence_sdk/schema/types/base/idData.proto"; -import "persistence_sdk/schema/types/base/stringData.proto"; -import "persistence_sdk/schema/types/base/accAddressData.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message Data { - oneof data { - persistence_sdk.schema.types.base.DecData dec_data = 1; - persistence_sdk.schema.types.base.HeightData height_data = 2; - persistence_sdk.schema.types.base.IDData id_data = 3; - persistence_sdk.schema.types.base.StringData string_data = 4; - persistence_sdk.schema.types.base.AccAddressData acc_address_data = 5; - string list_data = 6 [(gogoproto.customtype) = "github.com/persistenceOne/persistenceSDK/schema/types/base.ListData"]; - } -} diff --git a/proto/persistence_sdk/schema/types/base/decData.proto b/proto/persistence_sdk/schema/types/base/decData.proto deleted file mode 100644 index 6f46b82b1..000000000 --- a/proto/persistence_sdk/schema/types/base/decData.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message DecData { - option (gogoproto.goproto_stringer) = false; - bytes value = 1 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/fact.proto b/proto/persistence_sdk/schema/types/base/fact.proto deleted file mode 100644 index 3b72b18f0..000000000 --- a/proto/persistence_sdk/schema/types/base/fact.proto +++ /dev/null @@ -1,16 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/signatures.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message Fact { - option (gogoproto.goproto_getters) = false; - persistence_sdk.schema.types.base.ID hash_id = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.ID type_id = 2 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.Signatures signatures = 3 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/height.proto b/proto/persistence_sdk/schema/types/base/height.proto deleted file mode 100644 index ed497ba5d..000000000 --- a/proto/persistence_sdk/schema/types/base/height.proto +++ /dev/null @@ -1,11 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message Height { - int64 value = 1; -} diff --git a/proto/persistence_sdk/schema/types/base/heightData.proto b/proto/persistence_sdk/schema/types/base/heightData.proto deleted file mode 100644 index a05097e30..000000000 --- a/proto/persistence_sdk/schema/types/base/heightData.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/height.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message HeightData { - option (gogoproto.goproto_stringer) = false; - persistence_sdk.schema.types.base.Height value = 1 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/id.proto b/proto/persistence_sdk/schema/types/base/id.proto deleted file mode 100644 index 7b6f2f13d..000000000 --- a/proto/persistence_sdk/schema/types/base/id.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message ID { - option (gogoproto.goproto_stringer) = false; - - string id_string = 1; -} diff --git a/proto/persistence_sdk/schema/types/base/idData.proto b/proto/persistence_sdk/schema/types/base/idData.proto deleted file mode 100644 index e5135eb10..000000000 --- a/proto/persistence_sdk/schema/types/base/idData.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message IDData { - option (gogoproto.goproto_stringer) = false; - persistence_sdk.schema.types.base.ID value = 1 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/listData.proto b/proto/persistence_sdk/schema/types/base/listData.proto deleted file mode 100644 index 85b209071..000000000 --- a/proto/persistence_sdk/schema/types/base/listData.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/data.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message ListData { - option (gogoproto.goproto_stringer) = false; - repeated persistence_sdk.schema.types.base.Data value = 1 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/metaFact.proto b/proto/persistence_sdk/schema/types/base/metaFact.proto deleted file mode 100644 index 802eae177..000000000 --- a/proto/persistence_sdk/schema/types/base/metaFact.proto +++ /dev/null @@ -1,15 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/signatures.proto"; -import "persistence_sdk/schema/types/base/data.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message MetaFact { - option (gogoproto.goproto_getters) = false; - persistence_sdk.schema.types.base.Signatures signatures = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.Data data = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/metaProperties.proto b/proto/persistence_sdk/schema/types/base/metaProperties.proto deleted file mode 100644 index be4827f9d..000000000 --- a/proto/persistence_sdk/schema/types/base/metaProperties.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/metaProperty.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message MetaProperties { - repeated persistence_sdk.schema.types.base.MetaProperty metaPropertyList = 1 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/metaProperty.proto b/proto/persistence_sdk/schema/types/base/metaProperty.proto deleted file mode 100644 index 48a4e9733..000000000 --- a/proto/persistence_sdk/schema/types/base/metaProperty.proto +++ /dev/null @@ -1,15 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/metaFact.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message MetaProperty { - option (gogoproto.goproto_getters) = false; - persistence_sdk.schema.types.base.ID id = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.MetaFact metaFact = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/parameter.proto b/proto/persistence_sdk/schema/types/base/parameter.proto deleted file mode 100644 index 6d7ee4541..000000000 --- a/proto/persistence_sdk/schema/types/base/parameter.proto +++ /dev/null @@ -1,15 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "cosmos_proto/cosmos.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/data.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message Parameter { - persistence_sdk.schema.types.base.ID i_d = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.Data data = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/properties.proto b/proto/persistence_sdk/schema/types/base/properties.proto deleted file mode 100644 index a9edb0b4c..000000000 --- a/proto/persistence_sdk/schema/types/base/properties.proto +++ /dev/null @@ -1,14 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/property.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message Properties { - - repeated persistence_sdk.schema.types.base.Property propertyList = 1 [(gogoproto.nullable) = false]; - -} diff --git a/proto/persistence_sdk/schema/types/base/property.proto b/proto/persistence_sdk/schema/types/base/property.proto deleted file mode 100644 index 2115707fb..000000000 --- a/proto/persistence_sdk/schema/types/base/property.proto +++ /dev/null @@ -1,14 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/fact.proto"; -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message Property { - option (gogoproto.goproto_getters) = false; - persistence_sdk.schema.types.base.ID id = 1 [(gogoproto.nullable) = false]; - persistence_sdk.schema.types.base.Fact fact = 2 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/signature.proto b/proto/persistence_sdk/schema/types/base/signature.proto deleted file mode 100644 index c7cc60041..000000000 --- a/proto/persistence_sdk/schema/types/base/signature.proto +++ /dev/null @@ -1,18 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/id.proto"; -import "persistence_sdk/schema/types/base/height.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message Signature { - option (gogoproto.goproto_stringer) = false; - option (gogoproto.goproto_getters) = false; - - persistence_sdk.schema.types.base.ID id = 1 [(gogoproto.nullable) = false]; - bytes signature_bytes = 2; - persistence_sdk.schema.types.base.Height validity_height = 3 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/signatures.proto b/proto/persistence_sdk/schema/types/base/signatures.proto deleted file mode 100644 index 7291493bc..000000000 --- a/proto/persistence_sdk/schema/types/base/signatures.proto +++ /dev/null @@ -1,14 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; -import "persistence_sdk/schema/types/base/signature.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message Signatures { - option (gogoproto.stringer) = false; - - repeated persistence_sdk.schema.types.base.Signature signature_list = 1 [(gogoproto.nullable) = false]; -} diff --git a/proto/persistence_sdk/schema/types/base/stringData.proto b/proto/persistence_sdk/schema/types/base/stringData.proto deleted file mode 100644 index 553dd66e5..000000000 --- a/proto/persistence_sdk/schema/types/base/stringData.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; - -package persistence_sdk.schema.types.base; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/persistenceOne/persistenceSDK/schema/types/base"; - -message StringData { - option (gogoproto.goproto_stringer) = false; - string value = 1; -} diff --git a/schema/applications/application.go b/schema/applications/application.go index 8cc128546..bb2625622 100644 --- a/schema/applications/application.go +++ b/schema/applications/application.go @@ -4,37 +4,46 @@ package applications import ( + "encoding/json" + "io" + + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" - serverTypes "github.com/cosmos/cosmos-sdk/server/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + tendermintABCITypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" + tendermintTypes "github.com/tendermint/tendermint/types" + tendermintDB "github.com/tendermint/tm-db" ) type Application interface { - serverTypes.Application + tendermintABCITypes.Application GetDefaultNodeHome() string GetDefaultClientHome() string GetModuleBasicManager() module.BasicManager - GetCodec() codec.Codec + GetCodec() *codec.Codec LoadHeight(int64) error - ExportApplicationStateAndValidators(bool, []string) (serverTypes.ExportedApp, error) + ExportApplicationStateAndValidators(bool, []string) (json.RawMessage, []tendermintTypes.GenesisValidator, error) Name() string + AppVersion() string Logger() log.Logger MountStores(keys ...sdkTypes.StoreKey) MountKVStores(keys map[string]*sdkTypes.KVStoreKey) MountTransientStores(keys map[string]*sdkTypes.TransientStoreKey) + MountStoreWithDB(key sdkTypes.StoreKey, typ sdkTypes.StoreType, db tendermintDB.DB) MountStore(key sdkTypes.StoreKey, typ sdkTypes.StoreType) + LoadLatestVersion(baseKey *sdkTypes.KVStoreKey) error + LoadVersion(version int64, baseKey *sdkTypes.KVStoreKey) error LastCommitID() sdkTypes.CommitID LastBlockHeight() int64 Router() sdkTypes.Router QueryRouter() sdkTypes.QueryRouter Seal() IsSealed() bool -} -// Initialize(logger log.Logger, db tendermintDB.DB, traceStore io.Writer, loadLatest bool, invCheckPeriod uint, skipUpgradeHeights map[int64]bool, home string, baseAppOptions ...func(*baseapp.BaseApp)) Application -// } + Initialize(logger log.Logger, db tendermintDB.DB, traceStore io.Writer, loadLatest bool, invCheckPeriod uint, skipUpgradeHeights map[int64]bool, home string, baseAppOptions ...func(*baseapp.BaseApp)) Application +} diff --git a/schema/applications/base/application.go b/schema/applications/base/application.go index bbd96f25c..17a78150a 100644 --- a/schema/applications/base/application.go +++ b/schema/applications/base/application.go @@ -5,99 +5,61 @@ package base import ( "encoding/json" + "io" + "os" + "path/filepath" + + "github.com/CosmWasm/wasmd/x/wasm" "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/grpc/tmservice" - "github.com/cosmos/cosmos-sdk/client/rpc" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/server/api" - "github.com/cosmos/cosmos-sdk/server/config" - serverTypes "github.com/cosmos/cosmos-sdk/server/types" - storeTypes "github.com/cosmos/cosmos-sdk/store/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/ante" - authRest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" - authKeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authSimulation "github.com/cosmos/cosmos-sdk/x/auth/simulation" - authTx "github.com/cosmos/cosmos-sdk/x/auth/tx" - authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/cosmos/cosmos-sdk/x/auth/vesting" - vestingTypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - "github.com/cosmos/cosmos-sdk/x/authz" - authzKeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" - authzModule "github.com/cosmos/cosmos-sdk/x/authz/module" "github.com/cosmos/cosmos-sdk/x/bank" - bankKeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - bankTypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/capability" - capabilityKeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" - capabilityTypes "github.com/cosmos/cosmos-sdk/x/capability/types" "github.com/cosmos/cosmos-sdk/x/crisis" - crisisKeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" - crisisTypes "github.com/cosmos/cosmos-sdk/x/crisis/types" "github.com/cosmos/cosmos-sdk/x/distribution" - distributionKeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - distributionTypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/evidence" - evidenceKeeper "github.com/cosmos/cosmos-sdk/x/evidence/keeper" - evidenceTypes "github.com/cosmos/cosmos-sdk/x/evidence/types" - "github.com/cosmos/cosmos-sdk/x/feegrant" - feeGrantKeeper "github.com/cosmos/cosmos-sdk/x/feegrant/keeper" - feeGrantModule "github.com/cosmos/cosmos-sdk/x/feegrant/module" "github.com/cosmos/cosmos-sdk/x/genutil" - genutilTypes "github.com/cosmos/cosmos-sdk/x/genutil/types" "github.com/cosmos/cosmos-sdk/x/gov" - govKeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" - govTypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/cosmos/cosmos-sdk/x/mint" - mintKeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" - mintTypes "github.com/cosmos/cosmos-sdk/x/mint/types" "github.com/cosmos/cosmos-sdk/x/params" - paramsKeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" - paramsTypes "github.com/cosmos/cosmos-sdk/x/params/types" - paramsProposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" "github.com/cosmos/cosmos-sdk/x/slashing" - slashingKeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" - slashingTypes "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking" - stakingKeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/cosmos/cosmos-sdk/x/supply" "github.com/cosmos/cosmos-sdk/x/upgrade" - upgradeKeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" - upgradeTypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - ica "github.com/cosmos/ibc-go/v3/modules/apps/27-interchain-accounts" - icaControllerTypes "github.com/cosmos/ibc-go/v3/modules/apps/27-interchain-accounts/controller/types" - icaHostKeeper "github.com/cosmos/ibc-go/v3/modules/apps/27-interchain-accounts/host/keeper" - icaHostTypes "github.com/cosmos/ibc-go/v3/modules/apps/27-interchain-accounts/host/types" - icaTypes "github.com/cosmos/ibc-go/v3/modules/apps/27-interchain-accounts/types" - ibcTransfer "github.com/cosmos/ibc-go/v3/modules/apps/transfer" - ibcTransferKeeper "github.com/cosmos/ibc-go/v3/modules/apps/transfer/keeper" - ibcTransferTypes "github.com/cosmos/ibc-go/v3/modules/apps/transfer/types" - ibc "github.com/cosmos/ibc-go/v3/modules/core" - ibcClient "github.com/cosmos/ibc-go/v3/modules/core/02-client" - ibcClientTypes "github.com/cosmos/ibc-go/v3/modules/core/02-client/types" - ibcHost "github.com/cosmos/ibc-go/v3/modules/core/24-host" - ibcAnte "github.com/cosmos/ibc-go/v3/modules/core/ante" - ibcKeeper "github.com/cosmos/ibc-go/v3/modules/core/keeper" - "github.com/rakyll/statik/fs" - "github.com/spf13/cast" + "github.com/spf13/viper" abciTypes "github.com/tendermint/tendermint/abci/types" - tendermintJSON "github.com/tendermint/tendermint/libs/json" - tendermintLog "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/libs/log" tendermintOS "github.com/tendermint/tendermint/libs/os" - protoTendermintTypes "github.com/tendermint/tendermint/proto/tendermint/types" + tendermintTypes "github.com/tendermint/tendermint/types" tendermintDB "github.com/tendermint/tm-db" - "io" - "log" - "net/http" - "os" - + "honnef.co/go/tools/version" + + "github.com/AssetMantle/modules/modules/assets" + "github.com/AssetMantle/modules/modules/classifications" + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/conform" + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/define" + "github.com/AssetMantle/modules/modules/classifications/auxiliaries/member" + "github.com/AssetMantle/modules/modules/identities" + "github.com/AssetMantle/modules/modules/identities/auxiliaries/authenticate" + "github.com/AssetMantle/modules/modules/maintainers" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/deputize" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/maintain" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/revoke" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/super" + "github.com/AssetMantle/modules/modules/maintainers/auxiliaries/verify" "github.com/AssetMantle/modules/modules/metas" + "github.com/AssetMantle/modules/modules/metas/auxiliaries/supplement" + "github.com/AssetMantle/modules/modules/orders" + "github.com/AssetMantle/modules/modules/splits" + splitsMint "github.com/AssetMantle/modules/modules/splits/auxiliaries/mint" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/renumerate" + "github.com/AssetMantle/modules/modules/splits/auxiliaries/transfer" + "github.com/AssetMantle/modules/schema" "github.com/AssetMantle/modules/schema/applications" + wasmUtilities "github.com/AssetMantle/modules/utilities/wasm" ) type application struct { @@ -105,21 +67,22 @@ type application struct { moduleBasicManager module.BasicManager - codec codec.Codec + codec *codec.Codec - moduleAccountPermissions map[string][]string - tokenReceiveAllowedModules map[string]bool + enabledWasmProposalTypeList []wasm.ProposalType + moduleAccountPermissions map[string][]string + tokenReceiveAllowedModules map[string]bool keys map[string]*sdkTypes.KVStoreKey - stakingKeeper stakingKeeper.Keeper - slashingKeeper slashingKeeper.Keeper - distributionKeeper distributionKeeper.Keeper - crisisKeeper crisisKeeper.Keeper + stakingKeeper staking.Keeper + slashingKeeper slashing.Keeper + distributionKeeper distribution.Keeper + crisisKeeper crisis.Keeper moduleManager *module.Manager - *baseapp.BaseApp + baseapp.BaseApp } var _ applications.Application = (*application)(nil) @@ -133,18 +96,16 @@ func (application application) GetDefaultClientHome() string { func (application application) GetModuleBasicManager() module.BasicManager { return application.moduleBasicManager } -func (application application) GetCodec() codec.Codec { +func (application application) GetCodec() *codec.Codec { return application.codec } func (application application) LoadHeight(height int64) error { - return application.BaseApp.LoadVersion(height) + return application.BaseApp.LoadVersion(height, application.keys[baseapp.MainStoreKey]) } -func (application application) ExportApplicationStateAndValidators(forZeroHeight bool, jailWhiteList []string) (serverTypes.ExportedApp, error) { - context := application.BaseApp.NewContext(true, protoTendermintTypes.Header{Height: application.BaseApp.LastBlockHeight()}) +func (application application) ExportApplicationStateAndValidators(forZeroHeight bool, jailWhiteList []string) (json.RawMessage, []tendermintTypes.GenesisValidator, error) { + context := application.BaseApp.NewContext(true, abciTypes.Header{Height: application.BaseApp.LastBlockHeight()}) - height := application.LastBlockHeight() + 1 if forZeroHeight { - height = 0 applyWhiteList := false if len(jailWhiteList) > 0 { @@ -163,23 +124,14 @@ func (application application) ExportApplicationStateAndValidators(forZeroHeight application.crisisKeeper.AssertInvariants(context) - application.stakingKeeper.IterateValidators(context, func(_ int64, val stakingTypes.ValidatorI) (stop bool) { + application.stakingKeeper.IterateValidators(context, func(_ int64, val staking.ValidatorI) (stop bool) { _, _ = application.distributionKeeper.WithdrawValidatorCommission(context, val.GetOperator()) return false }) delegations := application.stakingKeeper.GetAllDelegations(context) for _, delegation := range delegations { - validatorAddress, err := sdkTypes.ValAddressFromBech32(delegation.ValidatorAddress) - if err != nil { - panic(err) - } - - delegatorAddress, err := sdkTypes.AccAddressFromBech32(delegation.DelegatorAddress) - if err != nil { - panic(err) - } - _, _ = application.distributionKeeper.WithdrawDelegationRewards(context, delegatorAddress, validatorAddress) + _, _ = application.distributionKeeper.WithdrawDelegationRewards(context, delegation.DelegatorAddress, delegation.ValidatorAddress) } application.distributionKeeper.DeleteAllValidatorSlashEvents(context) @@ -189,8 +141,8 @@ func (application application) ExportApplicationStateAndValidators(forZeroHeight height := context.BlockHeight() context = context.WithBlockHeight(0) - application.stakingKeeper.IterateValidators(context, func(_ int64, val stakingTypes.ValidatorI) (stop bool) { - scraps := application.distributionKeeper.GetValidatorOutstandingRewardsCoins(context, val.GetOperator()) + application.stakingKeeper.IterateValidators(context, func(_ int64, val staking.ValidatorI) (stop bool) { + scraps := application.distributionKeeper.GetValidatorOutstandingRewards(context, val.GetOperator()) feePool := application.distributionKeeper.GetFeePool(context) feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) application.distributionKeeper.SetFeePool(context, feePool) @@ -200,22 +152,13 @@ func (application application) ExportApplicationStateAndValidators(forZeroHeight }) for _, delegation := range delegations { - validatorAddress, err := sdkTypes.ValAddressFromBech32(delegation.ValidatorAddress) - if err != nil { - panic(err) - } - - delegatorAddress, err := sdkTypes.AccAddressFromBech32(delegation.DelegatorAddress) - if err != nil { - panic(err) - } - application.distributionKeeper.Hooks().BeforeDelegationCreated(context, delegatorAddress, validatorAddress) - application.distributionKeeper.Hooks().AfterDelegationModified(context, delegatorAddress, validatorAddress) + application.distributionKeeper.Hooks().BeforeDelegationCreated(context, delegation.DelegatorAddress, delegation.ValidatorAddress) + application.distributionKeeper.Hooks().AfterDelegationModified(context, delegation.DelegatorAddress, delegation.ValidatorAddress) } context = context.WithBlockHeight(height) - application.stakingKeeper.IterateRedelegations(context, func(_ int64, redelegation stakingTypes.Redelegation) (stop bool) { + application.stakingKeeper.IterateRedelegations(context, func(_ int64, redelegation staking.Redelegation) (stop bool) { for i := range redelegation.Entries { redelegation.Entries[i].CreationHeight = 0 } @@ -223,7 +166,7 @@ func (application application) ExportApplicationStateAndValidators(forZeroHeight return false }) - application.stakingKeeper.IterateUnbondingDelegations(context, func(_ int64, unbondingDelegation stakingTypes.UnbondingDelegation) (stop bool) { + application.stakingKeeper.IterateUnbondingDelegations(context, func(_ int64, unbondingDelegation staking.UnbondingDelegation) (stop bool) { for i := range unbondingDelegation.Entries { unbondingDelegation.Entries[i].CreationHeight = 0 } @@ -231,18 +174,20 @@ func (application application) ExportApplicationStateAndValidators(forZeroHeight return false }) - store := context.KVStore(application.keys[stakingTypes.StoreKey]) - kvStoreReversePrefixIterator := sdkTypes.KVStoreReversePrefixIterator(store, stakingTypes.ValidatorsKey) + store := context.KVStore(application.keys[staking.StoreKey]) + kvStoreReversePrefixIterator := sdkTypes.KVStoreReversePrefixIterator(store, staking.ValidatorsKey) counter := int16(0) for ; kvStoreReversePrefixIterator.Valid(); kvStoreReversePrefixIterator.Next() { - addr := sdkTypes.ValAddress(stakingTypes.AddressFromValidatorsKey(kvStoreReversePrefixIterator.Key())) + addr := sdkTypes.ValAddress(kvStoreReversePrefixIterator.Key()[1:]) validator, found := application.stakingKeeper.GetValidator(context, addr) + if !found { - panic("expected validator, not found") + panic("Validator not found!") } validator.UnbondingHeight = 0 + if applyWhiteList && !whiteListMap[addr.String()] { validator.Jailed = true } @@ -251,456 +196,370 @@ func (application application) ExportApplicationStateAndValidators(forZeroHeight counter++ } - if err := kvStoreReversePrefixIterator.Close(); err != nil { - log.Fatal(err) - } + kvStoreReversePrefixIterator.Close() - if _, err := application.stakingKeeper.ApplyAndReturnValidatorSetUpdates(context); err != nil { - log.Fatal(err) - } + _ = application.stakingKeeper.ApplyAndReturnValidatorSetUpdates(context) application.slashingKeeper.IterateValidatorSigningInfos( context, - func(consAddress sdkTypes.ConsAddress, validatorSigningInfo slashingTypes.ValidatorSigningInfo) (stop bool) { + func(validatorConsAddress sdkTypes.ConsAddress, validatorSigningInfo slashing.ValidatorSigningInfo) (stop bool) { validatorSigningInfo.StartHeight = 0 - application.slashingKeeper.SetValidatorSigningInfo(context, consAddress, validatorSigningInfo) + application.slashingKeeper.SetValidatorSigningInfo(context, validatorConsAddress, validatorSigningInfo) return false }, ) } - genesisState := application.moduleManager.ExportGenesis(context, application.codec) - applicationState, err := json.MarshalIndent(genesisState, "", " ") + genesisState := application.moduleManager.ExportGenesis(context) + applicationState, err := codec.MarshalJSONIndent(application.codec, genesisState) + if err != nil { - return serverTypes.ExportedApp{}, err + return nil, nil, err } - validators, err := staking.WriteValidators(context, application.stakingKeeper) - return serverTypes.ExportedApp{ - AppState: applicationState, - Validators: validators, - Height: height, - ConsensusParams: application.BaseApp.GetConsensusParams(context), - }, err -} -func (application application) RegisterAPIRoutes(server *api.Server, apiConfig config.APIConfig) { - clientCtx := server.ClientCtx - rpc.RegisterRoutes(clientCtx, server.Router) - authRest.RegisterTxRoutes(clientCtx, server.Router) - authTx.RegisterGRPCGatewayRoutes(clientCtx, server.GRPCGatewayRouter) - tmservice.RegisterGRPCGatewayRoutes(clientCtx, server.GRPCGatewayRouter) - application.moduleBasicManager.RegisterRESTRoutes(clientCtx, server.Router) - application.moduleBasicManager.RegisterGRPCGatewayRoutes(clientCtx, server.GRPCGatewayRouter) - if apiConfig.Swagger { - Fs, err := fs.New() - if err != nil { - panic(err) - } - - server.Router.PathPrefix("/swagger/").Handler(http.StripPrefix("/swagger/", http.FileServer(Fs))) - } -} -func (application application) RegisterTxService(context client.Context) { - authTx.RegisterTxService(application.BaseApp.GRPCQueryRouter(), context, application.BaseApp.Simulate, context.InterfaceRegistry) -} -func (application application) RegisterTendermintService(context client.Context) { - tmservice.RegisterTendermintService(application.BaseApp.GRPCQueryRouter(), context, context.InterfaceRegistry) + return applicationState, staking.WriteValidators(context, application.stakingKeeper), nil } -func (application application) Initialize(logger tendermintLog.Logger, db tendermintDB.DB, traceStore io.Writer, loadLatest bool, invCheckPeriod uint, skipUpgradeHeights map[int64]bool, home string, txConfig client.TxConfig, interfaceRegistry types.InterfaceRegistry, legacyAmino *codec.LegacyAmino, appOptions serverTypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp)) applications.Application { - application.BaseApp = baseapp.NewBaseApp(application.name, logger, db, txConfig.TxDecoder(), baseAppOptions...) +func (application application) Initialize(logger log.Logger, db tendermintDB.DB, traceStore io.Writer, loadLatest bool, invCheckPeriod uint, skipUpgradeHeights map[int64]bool, home string, baseAppOptions ...func(*baseapp.BaseApp)) applications.Application { + application.BaseApp = *baseapp.NewBaseApp( + application.name, + logger, + db, + auth.DefaultTxDecoder(application.codec), + baseAppOptions..., + ) application.BaseApp.SetCommitMultiStoreTracer(traceStore) - application.BaseApp.SetVersion(version.Version) - application.BaseApp.SetInterfaceRegistry(interfaceRegistry) + application.BaseApp.SetAppVersion(version.Version) application.keys = sdkTypes.NewKVStoreKeys( - authTypes.StoreKey, - bankTypes.StoreKey, - stakingTypes.StoreKey, - mintTypes.StoreKey, - distributionTypes.StoreKey, - slashingTypes.StoreKey, - govTypes.StoreKey, - paramsTypes.StoreKey, - ibcHost.StoreKey, - upgradeTypes.StoreKey, - evidenceTypes.StoreKey, - ibcTransferTypes.StoreKey, - capabilityTypes.StoreKey, - feegrant.StoreKey, - authzKeeper.StoreKey, - icaHostTypes.StoreKey, - + baseapp.MainStoreKey, + auth.StoreKey, + supply.StoreKey, + staking.StoreKey, + mint.StoreKey, + distribution.StoreKey, + slashing.StoreKey, + gov.StoreKey, + params.StoreKey, + upgrade.StoreKey, + evidence.StoreKey, + wasm.StoreKey, + assets.Prototype().Name(), + classifications.Prototype().Name(), + identities.Prototype().Name(), + maintainers.Prototype().Name(), metas.Prototype().Name(), + orders.Prototype().Name(), + splits.Prototype().Name(), ) - transientStoreKeys := sdkTypes.NewTransientStoreKeys(paramsTypes.TStoreKey) - memoryStoreKeys := sdkTypes.NewMemoryStoreKeys(capabilityTypes.MemStoreKey) + transientStoreKeys := sdkTypes.NewTransientStoreKeys(params.TStoreKey) - ParamsKeeper := paramsKeeper.NewKeeper( + paramsKeeper := params.NewKeeper( application.codec, - legacyAmino, - application.keys[paramsTypes.StoreKey], - transientStoreKeys[paramsTypes.TStoreKey], + application.keys[params.StoreKey], + transientStoreKeys[params.TStoreKey], ) - application.BaseApp.SetParamStore(ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramsKeeper.ConsensusParamsKeyTable())) - - CapabilityKeeper := capabilityKeeper.NewKeeper(application.codec, application.keys[capabilityTypes.StoreKey], memoryStoreKeys[capabilityTypes.MemStoreKey]) - scopedIBCKeeper := CapabilityKeeper.ScopeToModule(ibcHost.ModuleName) - scopedTransferKeeper := CapabilityKeeper.ScopeToModule(ibcTransferTypes.ModuleName) - scopedICAHostKeeper := CapabilityKeeper.ScopeToModule(icaHostTypes.SubModuleName) - CapabilityKeeper.Seal() - - AccountKeeper := authKeeper.NewAccountKeeper( + accountKeeper := auth.NewAccountKeeper( application.codec, - application.keys[authTypes.StoreKey], - ParamsKeeper.Subspace(authTypes.ModuleName), - authTypes.ProtoBaseAccount, - application.moduleAccountPermissions, + application.keys[auth.StoreKey], + paramsKeeper.Subspace(auth.DefaultParamspace), + auth.ProtoBaseAccount, ) blacklistedAddresses := make(map[string]bool) for account := range application.moduleAccountPermissions { - blacklistedAddresses[authTypes.NewModuleAddress(account).String()] = !application.tokenReceiveAllowedModules[account] + blacklistedAddresses[supply.NewModuleAddress(account).String()] = !application.tokenReceiveAllowedModules[account] } - BankKeeper := bankKeeper.NewBaseKeeper( - application.codec, - application.keys[bankTypes.StoreKey], - AccountKeeper, - ParamsKeeper.Subspace(bankTypes.ModuleName), + bankKeeper := bank.NewBaseKeeper( + accountKeeper, + paramsKeeper.Subspace(bank.DefaultParamspace), blacklistedAddresses, ) - AuthzKeeper := authzKeeper.NewKeeper( - application.keys[authzKeeper.StoreKey], + supplyKeeper := supply.NewKeeper( application.codec, - application.BaseApp.MsgServiceRouter(), + application.keys[supply.StoreKey], + accountKeeper, + bankKeeper, + application.moduleAccountPermissions, ) - FeeGrantKeeper := feeGrantKeeper.NewKeeper( + stakingKeeper := staking.NewKeeper( application.codec, - application.keys[feegrant.StoreKey], - AccountKeeper, + application.keys[staking.StoreKey], + supplyKeeper, + paramsKeeper.Subspace(staking.DefaultParamspace), ) - application.stakingKeeper = stakingKeeper.NewKeeper( + mintKeeper := mint.NewKeeper( application.codec, - application.keys[stakingTypes.StoreKey], - AccountKeeper, - BankKeeper, - ParamsKeeper.Subspace(stakingTypes.StoreKey), + application.keys[mint.StoreKey], + paramsKeeper.Subspace(mint.DefaultParamspace), + &stakingKeeper, + supplyKeeper, + auth.FeeCollectorName, ) - MintKeeper := mintKeeper.NewKeeper( - application.codec, - application.keys[mintTypes.StoreKey], - ParamsKeeper.Subspace(mintTypes.ModuleName), - &application.stakingKeeper, - AccountKeeper, - BankKeeper, - authTypes.FeeCollectorName, - ) + blackListedModuleAddresses := make(map[string]bool) + for moduleAccount := range application.moduleAccountPermissions { + blackListedModuleAddresses[supply.NewModuleAddress(moduleAccount).String()] = true + } - application.distributionKeeper = distributionKeeper.NewKeeper( + application.distributionKeeper = distribution.NewKeeper( application.codec, - application.keys[distributionTypes.StoreKey], - ParamsKeeper.Subspace(distributionTypes.ModuleName), - AccountKeeper, - BankKeeper, - &application.stakingKeeper, - authTypes.FeeCollectorName, - blacklistedAddresses, + application.keys[distribution.StoreKey], + paramsKeeper.Subspace(distribution.DefaultParamspace), + &stakingKeeper, + supplyKeeper, + auth.FeeCollectorName, + blackListedModuleAddresses, ) - - application.slashingKeeper = slashingKeeper.NewKeeper( + application.slashingKeeper = slashing.NewKeeper( application.codec, - application.keys[slashingTypes.StoreKey], - &application.stakingKeeper, - ParamsKeeper.Subspace(slashingTypes.ModuleName), + application.keys[slashing.StoreKey], + &stakingKeeper, + paramsKeeper.Subspace(slashing.DefaultParamspace), ) - - application.crisisKeeper = crisisKeeper.NewKeeper( - ParamsKeeper.Subspace(crisisTypes.ModuleName), + application.crisisKeeper = crisis.NewKeeper( + paramsKeeper.Subspace(crisis.DefaultParamspace), invCheckPeriod, - BankKeeper, - authTypes.FeeCollectorName, + supplyKeeper, + auth.FeeCollectorName, ) - - UpgradeKeeper := upgradeKeeper.NewKeeper( + upgradeKeeper := upgrade.NewKeeper( skipUpgradeHeights, - application.keys[upgradeTypes.StoreKey], + application.keys[upgrade.StoreKey], application.codec, - home, - application.BaseApp, ) - application.stakingKeeper = *application.stakingKeeper.SetHooks(stakingTypes.NewMultiStakingHooks(application.distributionKeeper.Hooks(), application.slashingKeeper.Hooks())) - - IBCKeeper := ibcKeeper.NewKeeper( + evidenceKeeper := evidence.NewKeeper( application.codec, - application.keys[ibcHost.StoreKey], - ParamsKeeper.Subspace(ibcHost.ModuleName), - application.stakingKeeper, - UpgradeKeeper, - scopedIBCKeeper, + application.keys[evidence.StoreKey], + paramsKeeper.Subspace(evidence.DefaultParamspace), + &stakingKeeper, + application.slashingKeeper, ) + evidenceRouter := evidence.NewRouter() + evidenceKeeper.SetRouter(evidenceRouter) - govRouter := govTypes.NewRouter(). - AddRoute(govTypes.RouterKey, govTypes.ProposalHandler). - AddRoute(paramsProposal.RouterKey, params.NewParamChangeProposalHandler(ParamsKeeper)). - AddRoute(distributionTypes.RouterKey, distribution.NewCommunityPoolSpendProposalHandler(application.distributionKeeper)). - AddRoute(upgradeTypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(UpgradeKeeper)). - AddRoute(ibcClientTypes.RouterKey, ibcClient.NewClientProposalHandler(IBCKeeper.ClientKeeper)) - - GovKeeper := govKeeper.NewKeeper( - application.codec, - application.keys[govTypes.StoreKey], - ParamsKeeper.Subspace(govTypes.ModuleName), - AccountKeeper, - BankKeeper, - &application.stakingKeeper, - govRouter, + application.stakingKeeper = *stakingKeeper.SetHooks( + staking.NewMultiStakingHooks(application.distributionKeeper.Hooks(), application.slashingKeeper.Hooks()), ) - IBCTransferKeeper := ibcTransferKeeper.NewKeeper( - application.codec, - application.keys[ibcTransferTypes.StoreKey], - ParamsKeeper.Subspace(ibcTransferTypes.ModuleName), - IBCKeeper.ChannelKeeper, - IBCKeeper.ChannelKeeper, - &IBCKeeper.PortKeeper, - AccountKeeper, - BankKeeper, - scopedTransferKeeper, + metasModule := metas.Prototype().Initialize( + application.keys[metas.Prototype().Name()], + paramsKeeper.Subspace(metas.Prototype().Name()), + ) + classificationsModule := classifications.Prototype().Initialize( + application.keys[classifications.Prototype().Name()], + paramsKeeper.Subspace(classifications.Prototype().Name()), + ) + maintainersModule := maintainers.Prototype().Initialize( + application.keys[metas.Prototype().Name()], + paramsKeeper.Subspace(maintainers.Prototype().Name()), + classificationsModule.GetAuxiliary(member.Auxiliary.GetName()), ) + identitiesModule := identities.Prototype().Initialize( + application.keys[identities.Prototype().Name()], + paramsKeeper.Subspace(identities.Prototype().Name()), + classificationsModule.GetAuxiliary(conform.Auxiliary.GetName()), + classificationsModule.GetAuxiliary(define.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(deputize.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(maintain.Auxiliary.GetName()), + classificationsModule.GetAuxiliary(member.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(super.Auxiliary.GetName()), + metasModule.GetAuxiliary(supplement.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(revoke.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(verify.Auxiliary.GetName()), + ) + splitsModule := splits.Prototype().Initialize( + application.keys[splits.Prototype().Name()], + paramsKeeper.Subspace(splits.Prototype().Name()), + supplyKeeper, + identitiesModule.GetAuxiliary(authenticate.Auxiliary.GetName()), + ) + assetsModule := assets.Prototype().Initialize( + application.keys[assets.Prototype().Name()], + paramsKeeper.Subspace(assets.Prototype().Name()), + identitiesModule.GetAuxiliary(authenticate.Auxiliary.GetName()), + classificationsModule.GetAuxiliary(conform.Auxiliary.GetName()), + classificationsModule.GetAuxiliary(define.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(deputize.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(maintain.Auxiliary.GetName()), + splitsModule.GetAuxiliary(renumerate.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(revoke.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(super.Auxiliary.GetName()), + metasModule.GetAuxiliary(supplement.Auxiliary.GetName()), + splitsModule.GetAuxiliary(splitsMint.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(verify.Auxiliary.GetName()), + ) + ordersModule := orders.Prototype().Initialize( + application.keys[orders.Prototype().Name()], + paramsKeeper.Subspace(orders.Prototype().Name()), + identitiesModule.GetAuxiliary(authenticate.Auxiliary.GetName()), + classificationsModule.GetAuxiliary(conform.Auxiliary.GetName()), + classificationsModule.GetAuxiliary(define.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(deputize.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(maintain.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(revoke.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(super.Auxiliary.GetName()), + metasModule.GetAuxiliary(supplement.Auxiliary.GetName()), + splitsModule.GetAuxiliary(transfer.Auxiliary.GetName()), + maintainersModule.GetAuxiliary(verify.Auxiliary.GetName()), + ) + var wasmRouter = application.BaseApp.Router() + + wasmDir := filepath.Join(home, wasm.ModuleName) + + wasmWrap := struct { + Wasm wasm.WasmConfig `mapstructure:"wasm"` + }{ + Wasm: wasm.DefaultWasmConfig(), + } + + err := viper.Unmarshal(&wasmWrap) + if err != nil { + panic("error while reading wasm config: " + err.Error()) + } + + wasmConfig := wasmWrap.Wasm - ICAHostKeeper := icaHostKeeper.NewKeeper( + wasmKeeper := wasm.NewKeeper( application.codec, - application.keys[icaHostTypes.StoreKey], - ParamsKeeper.Subspace(icaHostTypes.SubModuleName), - IBCKeeper.ChannelKeeper, - &IBCKeeper.PortKeeper, - AccountKeeper, - scopedICAHostKeeper, - application.MsgServiceRouter(), + application.keys[wasm.StoreKey], + paramsKeeper.Subspace(wasm.DefaultParamspace), + accountKeeper, + bankKeeper, + application.stakingKeeper, + wasmRouter, + wasmDir, + wasmConfig, + staking.ModuleName, + &wasm.MessageEncoders{Custom: wasmUtilities.CustomEncoder(assets.Prototype(), classifications.Prototype(), identities.Prototype(), maintainers.Prototype(), metas.Prototype(), orders.Prototype(), splits.Prototype())}, + nil) + + govRouter := gov.NewRouter().AddRoute( + gov.RouterKey, + gov.ProposalHandler, + ).AddRoute( + params.RouterKey, + params.NewParamChangeProposalHandler(paramsKeeper), + ).AddRoute( + distribution.RouterKey, + distribution.NewCommunityPoolSpendProposalHandler(application.distributionKeeper), + ).AddRoute( + upgrade.RouterKey, + upgrade.NewSoftwareUpgradeProposalHandler(upgradeKeeper), ) - EvidenceKeeper := *evidenceKeeper.NewKeeper( + if len(application.enabledWasmProposalTypeList) != 0 { + govRouter.AddRoute(wasm.RouterKey, wasm.NewWasmProposalHandler(wasmKeeper, application.enabledWasmProposalTypeList)) + } + + govKeeper := gov.NewKeeper( application.codec, - application.keys[evidenceTypes.StoreKey], - &application.stakingKeeper, - application.slashingKeeper, + application.keys[gov.StoreKey], + paramsKeeper.Subspace(gov.DefaultParamspace).WithKeyTable(gov.ParamKeyTable()), + supplyKeeper, + &stakingKeeper, + govRouter, ) - metasModule := metas.Prototype().Initialize( - application.keys[metas.Prototype().Name()], - ParamsKeeper.Subspace(metas.Prototype().Name()), - ) application.moduleManager = module.NewManager( - genutil.NewAppModule(AccountKeeper, application.stakingKeeper, application.BaseApp.DeliverTx, txConfig), - auth.NewAppModule(application.codec, AccountKeeper, nil), - vesting.NewAppModule(AccountKeeper, BankKeeper), - bank.NewAppModule(application.codec, BankKeeper, AccountKeeper), - capability.NewAppModule(application.codec, *CapabilityKeeper), - crisis.NewAppModule(&application.crisisKeeper, cast.ToBool(appOptions.Get(crisis.FlagSkipGenesisInvariants))), - gov.NewAppModule(application.codec, GovKeeper, AccountKeeper, BankKeeper), - mint.NewAppModule(application.codec, MintKeeper, AccountKeeper), - slashing.NewAppModule(application.codec, application.slashingKeeper, AccountKeeper, BankKeeper, application.stakingKeeper), - distribution.NewAppModule(application.codec, application.distributionKeeper, AccountKeeper, BankKeeper, application.stakingKeeper), - staking.NewAppModule(application.codec, application.stakingKeeper, AccountKeeper, BankKeeper), - upgrade.NewAppModule(UpgradeKeeper), - evidence.NewAppModule(EvidenceKeeper), - feeGrantModule.NewAppModule(application.codec, AccountKeeper, BankKeeper, FeeGrantKeeper, interfaceRegistry), - authzModule.NewAppModule(application.codec, AuthzKeeper, AccountKeeper, BankKeeper, interfaceRegistry), - ibc.NewAppModule(IBCKeeper), - params.NewAppModule(ParamsKeeper), - ibcTransfer.NewAppModule(IBCTransferKeeper), - ica.NewAppModule(nil, &ICAHostKeeper), - + genutil.NewAppModule(accountKeeper, application.stakingKeeper, application.BaseApp.DeliverTx), + auth.NewAppModule(accountKeeper), + bank.NewAppModule(bankKeeper, accountKeeper), + crisis.NewAppModule(&application.crisisKeeper), + supply.NewAppModule(supplyKeeper, accountKeeper), + gov.NewAppModule(govKeeper, accountKeeper, supplyKeeper), + mint.NewAppModule(mintKeeper), + slashing.NewAppModule(application.slashingKeeper, accountKeeper, application.stakingKeeper), + distribution.NewAppModule(application.distributionKeeper, accountKeeper, supplyKeeper, application.stakingKeeper), + staking.NewAppModule(application.stakingKeeper, accountKeeper, supplyKeeper), + upgrade.NewAppModule(upgradeKeeper), + wasm.NewAppModule(wasmKeeper), + evidence.NewAppModule(*evidenceKeeper), + + assetsModule, + classificationsModule, + identitiesModule, + maintainersModule, metasModule, + ordersModule, + splitsModule, ) application.moduleManager.SetOrderBeginBlockers( - upgradeTypes.ModuleName, - capabilityTypes.ModuleName, - crisisTypes.ModuleName, - govTypes.ModuleName, - stakingTypes.ModuleName, - ibcTransferTypes.ModuleName, - ibcHost.ModuleName, - icaTypes.ModuleName, - authTypes.ModuleName, - bankTypes.ModuleName, - distributionTypes.ModuleName, - slashingTypes.ModuleName, - mintTypes.ModuleName, - genutilTypes.ModuleName, - evidenceTypes.ModuleName, - authz.ModuleName, - feegrant.ModuleName, - paramsTypes.ModuleName, - vestingTypes.ModuleName, + upgrade.ModuleName, + mint.ModuleName, + distribution.ModuleName, + slashing.ModuleName, ) application.moduleManager.SetOrderEndBlockers( - crisisTypes.ModuleName, - govTypes.ModuleName, - stakingTypes.ModuleName, - ibcTransferTypes.ModuleName, - ibcHost.ModuleName, - icaTypes.ModuleName, - feegrant.ModuleName, - authz.ModuleName, - capabilityTypes.ModuleName, - authTypes.ModuleName, - bankTypes.ModuleName, - distributionTypes.ModuleName, - slashingTypes.ModuleName, - mintTypes.ModuleName, - genutilTypes.ModuleName, - evidenceTypes.ModuleName, - paramsTypes.ModuleName, - upgradeTypes.ModuleName, - vestingTypes.ModuleName, + crisis.ModuleName, + gov.ModuleName, + staking.ModuleName, + ordersModule.Name(), ) application.moduleManager.SetOrderInitGenesis( - capabilityTypes.ModuleName, - bankTypes.ModuleName, - distributionTypes.ModuleName, - stakingTypes.ModuleName, - slashingTypes.ModuleName, - govTypes.ModuleName, - mintTypes.ModuleName, - crisisTypes.ModuleName, - ibcTransferTypes.ModuleName, - ibcHost.ModuleName, - icaTypes.ModuleName, - evidenceTypes.ModuleName, - feegrant.ModuleName, - authz.ModuleName, - authTypes.ModuleName, - genutilTypes.ModuleName, - paramsTypes.ModuleName, - upgradeTypes.ModuleName, - vestingTypes.ModuleName, - + auth.ModuleName, + distribution.ModuleName, + staking.ModuleName, + bank.ModuleName, + slashing.ModuleName, + gov.ModuleName, + mint.ModuleName, + supply.ModuleName, + crisis.ModuleName, + genutil.ModuleName, + evidence.ModuleName, + assets.Prototype().Name(), + classifications.Prototype().Name(), + identities.Prototype().Name(), + maintainers.Prototype().Name(), metas.Prototype().Name(), + orders.Prototype().Name(), + splits.Prototype().Name(), ) application.moduleManager.RegisterInvariants(&application.crisisKeeper) - application.moduleManager.RegisterRoutes(application.BaseApp.Router(), application.BaseApp.QueryRouter(), legacyAmino) - - configurator := module.NewConfigurator(application.codec, application.MsgServiceRouter(), application.GRPCQueryRouter()) - application.moduleManager.RegisterServices(configurator) + application.moduleManager.RegisterRoutes(application.BaseApp.Router(), application.BaseApp.QueryRouter()) module.NewSimulationManager( - auth.NewAppModule(application.codec, AccountKeeper, authSimulation.RandomGenesisAccounts), - bank.NewAppModule(application.codec, BankKeeper, AccountKeeper), - capability.NewAppModule(application.codec, *CapabilityKeeper), - feeGrantModule.NewAppModule(application.codec, AccountKeeper, BankKeeper, FeeGrantKeeper, interfaceRegistry), - authzModule.NewAppModule(application.codec, AuthzKeeper, AccountKeeper, BankKeeper, interfaceRegistry), - gov.NewAppModule(application.codec, GovKeeper, AccountKeeper, BankKeeper), - mint.NewAppModule(application.codec, MintKeeper, AccountKeeper), - staking.NewAppModule(application.codec, application.stakingKeeper, AccountKeeper, BankKeeper), - distribution.NewAppModule(application.codec, application.distributionKeeper, AccountKeeper, BankKeeper, application.stakingKeeper), - slashing.NewAppModule(application.codec, application.slashingKeeper, AccountKeeper, BankKeeper, application.stakingKeeper), - params.NewAppModule(ParamsKeeper), - evidence.NewAppModule(EvidenceKeeper), - ibc.NewAppModule(IBCKeeper), - ibcTransfer.NewAppModule(IBCTransferKeeper), - + auth.NewAppModule(accountKeeper), + bank.NewAppModule(bankKeeper, accountKeeper), + supply.NewAppModule(supplyKeeper, accountKeeper), + gov.NewAppModule(govKeeper, accountKeeper, supplyKeeper), + mint.NewAppModule(mintKeeper), + staking.NewAppModule(application.stakingKeeper, accountKeeper, supplyKeeper), + distribution.NewAppModule(application.distributionKeeper, accountKeeper, supplyKeeper, application.stakingKeeper), + slashing.NewAppModule(application.slashingKeeper, accountKeeper, application.stakingKeeper), + params.NewAppModule(), + assets.Prototype(), + classifications.Prototype(), + identities.Prototype(), + maintainers.Prototype(), metas.Prototype(), + orders.Prototype(), + splits.Prototype(), ).RegisterStoreDecoders() application.BaseApp.MountKVStores(application.keys) application.BaseApp.MountTransientStores(transientStoreKeys) - application.BaseApp.MountMemoryStores(memoryStoreKeys) - application.BaseApp.SetAnteHandler(sdkTypes.ChainAnteDecorators( - ante.NewSetUpContextDecorator(), - ante.NewRejectExtensionOptionsDecorator(), - ante.NewValidateBasicDecorator(), - ante.NewTxTimeoutHeightDecorator(), - ante.NewValidateMemoDecorator(AccountKeeper), - ante.NewConsumeGasForTxSizeDecorator(AccountKeeper), - ante.NewDeductFeeDecorator(AccountKeeper, BankKeeper, FeeGrantKeeper), - ante.NewSetPubKeyDecorator(AccountKeeper), - ante.NewValidateSigCountDecorator(AccountKeeper), - ante.NewSigGasConsumeDecorator(AccountKeeper, ante.DefaultSigVerificationGasConsumer), - ante.NewSigVerificationDecorator(AccountKeeper, txConfig.SignModeHandler()), - ante.NewIncrementSequenceDecorator(AccountKeeper), - ibcAnte.NewAnteDecorator(IBCKeeper), - )) + application.BaseApp.SetBeginBlocker(application.moduleManager.BeginBlock) application.BaseApp.SetEndBlocker(application.moduleManager.EndBlock) application.BaseApp.SetInitChainer(func(context sdkTypes.Context, requestInitChain abciTypes.RequestInitChain) abciTypes.ResponseInitChain { var genesisState map[string]json.RawMessage - if err := tendermintJSON.Unmarshal(requestInitChain.AppStateBytes, &genesisState); err != nil { - panic(err) - } - - UpgradeKeeper.SetModuleVersionMap(context, application.moduleManager.GetVersionMap()) - - return application.moduleManager.InitGenesis(context, application.codec, genesisState) + application.codec.MustUnmarshalJSON(requestInitChain.AppStateBytes, &genesisState) + return application.moduleManager.InitGenesis(context, genesisState) }) - - UpgradeKeeper.SetUpgradeHandler( - upgradeName, - func(ctx sdkTypes.Context, _ upgradeTypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { - fromVM[icaTypes.ModuleName] = ica.NewAppModule(nil, &ICAHostKeeper).ConsensusVersion() - controllerParams := icaControllerTypes.Params{} - hostParams := icaHostTypes.Params{ - HostEnabled: true, - AllowMessages: []string{ - authzMsgExec, - authzMsgGrant, - authzMsgRevoke, - bankMsgSend, - bankMsgMultiSend, - distrMsgSetWithdrawAddr, - distrMsgWithdrawValidatorCommission, - distrMsgFundCommunityPool, - distrMsgWithdrawDelegatorReward, - feegrantMsgGrantAllowance, - feegrantMsgRevokeAllowance, - govMsgVoteWeighted, - govMsgSubmitProposal, - govMsgDeposit, - govMsgVote, - stakingMsgEditValidator, - stakingMsgDelegate, - stakingMsgUndelegate, - stakingMsgBeginRedelegate, - stakingMsgCreateValidator, - vestingMsgCreateVestingAccount, - transferMsgTransfer, - liquidityMsgCreatePool, - liquidityMsgSwapWithinBatch, - liquidityMsgDepositWithinBatch, - liquidityMsgWithdrawWithinBatch, - }, - } - ica.NewAppModule(nil, &ICAHostKeeper).InitModule(ctx, controllerParams, hostParams) - - return application.moduleManager.RunMigrations(ctx, configurator, fromVM) - }, - ) - - upgradeInfo, err := UpgradeKeeper.ReadUpgradeInfoFromDisk() - if err != nil { - panic(err) - } - - if upgradeInfo.Name == upgradeName && !UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { - storeUpgrades := storeTypes.StoreUpgrades{ - Added: []string{icaHostTypes.StoreKey}, - } - - // configure store loader that checks if version == upgradeHeight and applies store upgrades - application.SetStoreLoader(upgradeTypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades)) - } + application.BaseApp.SetAnteHandler(auth.NewAnteHandler(accountKeeper, supplyKeeper, ante.DefaultSigVerificationGasConsumer)) if loadLatest { - err := application.BaseApp.LoadLatestVersion() + err := application.BaseApp.LoadLatestVersion(application.keys[baseapp.MainStoreKey]) if err != nil { tendermintOS.Exit(err.Error()) } @@ -708,35 +567,26 @@ func (application application) Initialize(logger tendermintLog.Logger, db tender return &application } +func makeCodec(moduleBasicManager module.BasicManager) *codec.Codec { + Codec := codec.New() + moduleBasicManager.RegisterCodec(Codec) + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + + return Codec +} -const ( - appName = "GaiaApp" - upgradeName = "v7-Theta" - - authzMsgExec = "/cosmos.authz.v1beta1.MsgExec" - authzMsgGrant = "/cosmos.authz.v1beta1.MsgGrant" - authzMsgRevoke = "/cosmos.authz.v1beta1.MsgRevoke" - bankMsgSend = "/cosmos.bank.v1beta1.MsgSend" - bankMsgMultiSend = "/cosmos.bank.v1beta1.MsgMultiSend" - distrMsgSetWithdrawAddr = "/cosmos.distribution.v1beta1.MsgSetWithdrawAddress" - distrMsgWithdrawValidatorCommission = "/cosmos.distribution.v1beta1.MsgWithdrawValidatorCommission" - distrMsgFundCommunityPool = "/cosmos.distribution.v1beta1.MsgFundCommunityPool" - distrMsgWithdrawDelegatorReward = "/cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward" - feegrantMsgGrantAllowance = "/cosmos.feegrant.v1beta1.MsgGrantAllowance" - feegrantMsgRevokeAllowance = "/cosmos.feegrant.v1beta1.MsgRevokeAllowance" - govMsgVoteWeighted = "/cosmos.gov.v1beta1.MsgVoteWeighted" - govMsgSubmitProposal = "/cosmos.gov.v1beta1.MsgSubmitProposal" - govMsgDeposit = "/cosmos.gov.v1beta1.MsgDeposit" - govMsgVote = "/cosmos.gov.v1beta1.MsgVote" - stakingMsgEditValidator = "/cosmos.staking.v1beta1.MsgEditValidator" - stakingMsgDelegate = "/cosmos.staking.v1beta1.MsgDelegate" - stakingMsgUndelegate = "/cosmos.staking.v1beta1.MsgUndelegate" - stakingMsgBeginRedelegate = "/cosmos.staking.v1beta1.MsgBeginRedelegate" - stakingMsgCreateValidator = "/cosmos.staking.v1beta1.MsgCreateValidator" - vestingMsgCreateVestingAccount = "/cosmos.vesting.v1beta1.MsgCreateVestingAccount" - transferMsgTransfer = "/ibc.applications.transfer.v1.MsgTransfer" - liquidityMsgCreatePool = "/tendermint.liquidity.v1beta1.MsgCreatePool" - liquidityMsgSwapWithinBatch = "/tendermint.liquidity.v1beta1.MsgSwapWithinBatch" - liquidityMsgDepositWithinBatch = "/tendermint.liquidity.v1beta1.MsgDepositWithinBatch" - liquidityMsgWithdrawWithinBatch = "/tendermint.liquidity.v1beta1.MsgWithdrawWithinBatch" -) +func NewApplication(name string, moduleBasicManager module.BasicManager, enabledWasmProposalTypeList []wasm.ProposalType, moduleAccountPermissions map[string][]string, tokenReceiveAllowedModules map[string]bool) applications.Application { + return &application{ + name: name, + moduleBasicManager: moduleBasicManager, + codec: makeCodec(moduleBasicManager), + enabledWasmProposalTypeList: enabledWasmProposalTypeList, + moduleAccountPermissions: moduleAccountPermissions, + tokenReceiveAllowedModules: tokenReceiveAllowedModules, + } +} diff --git a/schema/applications/base/encoding/encoding.go b/schema/applications/base/encoding/encoding.go deleted file mode 100644 index 4c966ab0c..000000000 --- a/schema/applications/base/encoding/encoding.go +++ /dev/null @@ -1,31 +0,0 @@ -package encoding - -import ( - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/x/auth/tx" -) - -// EncodingConfig specifies the concrete encoding types to use for a given app. -// This is provided for compatibility between protobuf and amino implementations. -type EncodingConfig struct { - InterfaceRegistry types.InterfaceRegistry - Marshaler codec.Marshaler - TxConfig client.TxConfig - LegacyAmino *codec.LegacyAmino -} - -func MakeEncodingConfig() EncodingConfig { - amino := codec.NewLegacyAmino() - interfaceRegistry := types.NewInterfaceRegistry() - marshaler := codec.NewProtoCodec(interfaceRegistry) - txCfg := tx.NewTxConfig(marshaler, tx.DefaultSignModes) - - return EncodingConfig{ - InterfaceRegistry: interfaceRegistry, - Marshaler: marshaler, - TxConfig: txCfg, - LegacyAmino: amino, - } -} diff --git a/schema/applications/base/simulationApplication.go b/schema/applications/base/simulationApplication.go new file mode 100644 index 000000000..ce3e218ec --- /dev/null +++ b/schema/applications/base/simulationApplication.go @@ -0,0 +1,405 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "encoding/json" + "io" + "os" + "path/filepath" + "testing" + + "github.com/CosmWasm/wasmd/x/wasm" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/store" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/exported" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/crisis" + "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/evidence" + "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/supply" + "github.com/cosmos/cosmos-sdk/x/upgrade" + "github.com/spf13/viper" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + "github.com/tendermint/tendermint/crypto/ed25519" + "github.com/tendermint/tendermint/libs/log" + tendermintTypes "github.com/tendermint/tendermint/types" + tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/modules/assets" + "github.com/AssetMantle/modules/modules/classifications" + "github.com/AssetMantle/modules/modules/identities" + "github.com/AssetMantle/modules/modules/maintainers" + "github.com/AssetMantle/modules/modules/metas" + "github.com/AssetMantle/modules/modules/orders" + "github.com/AssetMantle/modules/modules/splits" + wasmUtilities "github.com/AssetMantle/modules/utilities/wasm" + + "github.com/AssetMantle/modules/schema/applications" +) + +type SimulationApplication struct { + application + + transientStoreKeys map[string]*sdkTypes.TransientStoreKey + subspaces map[string]params.Subspace + simulationManager *module.SimulationManager + + AccountKeeper auth.AccountKeeper + BankKeeper bank.Keeper + SupplyKeeper supply.Keeper + StakingKeeper staking.Keeper + SlashingKeeper slashing.Keeper + MintKeeper mint.Keeper + DistributionKeeper distribution.Keeper + GovKeeper gov.Keeper + CrisisKeeper crisis.Keeper + UpgradeKeeper upgrade.Keeper + ParamsKeeper params.Keeper + EvidenceKeeper evidence.Keeper +} + +var _ applications.SimulationApplication = (*SimulationApplication)(nil) + +func (simulationApplication SimulationApplication) Codec() *codec.Codec { + return simulationApplication.codec +} + +func (simulationApplication SimulationApplication) BeginBlocker(ctx sdkTypes.Context, req abciTypes.RequestBeginBlock) abciTypes.ResponseBeginBlock { + return simulationApplication.moduleManager.BeginBlock(ctx, req) +} + +func (simulationApplication SimulationApplication) EndBlocker(ctx sdkTypes.Context, req abciTypes.RequestEndBlock) abciTypes.ResponseEndBlock { + return simulationApplication.moduleManager.EndBlock(ctx, req) +} + +func (simulationApplication SimulationApplication) InitChainer(ctx sdkTypes.Context, req abciTypes.RequestInitChain) abciTypes.ResponseInitChain { + var genesisState simapp.GenesisState + + simulationApplication.codec.MustUnmarshalJSON(req.AppStateBytes, &genesisState) + + return simulationApplication.moduleManager.InitGenesis(ctx, genesisState) +} + +func (simulationApplication SimulationApplication) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteList []string) (json.RawMessage, []tendermintTypes.GenesisValidator, error) { + return simulationApplication.ExportApplicationStateAndValidators(forZeroHeight, jailWhiteList) +} + +func (simulationApplication SimulationApplication) ModuleAccountAddrs() map[string]bool { + return simulationApplication.tokenReceiveAllowedModules +} + +func (simulationApplication SimulationApplication) SimulationManager() *module.SimulationManager { + return simulationApplication.simulationManager +} + +func (simulationApplication SimulationApplication) ModuleManager() *module.Manager { + return simulationApplication.moduleManager +} + +func (simulationApplication SimulationApplication) GetBaseApp() *baseapp.BaseApp { + return &simulationApplication.BaseApp +} + +func (simulationApplication SimulationApplication) GetKey(storeKey string) *sdkTypes.KVStoreKey { + return simulationApplication.keys[storeKey] +} + +func (simulationApplication SimulationApplication) GetTKey(storeKey string) *sdkTypes.TransientStoreKey { + return simulationApplication.transientStoreKeys[storeKey] +} + +func (simulationApplication SimulationApplication) GetSubspace(moduleName string) params.Subspace { + return simulationApplication.subspaces[moduleName] +} + +func (simulationApplication SimulationApplication) GetModuleAccountPermissions() map[string][]string { + return simulationApplication.moduleAccountPermissions +} + +func (simulationApplication SimulationApplication) GetBlackListedAddresses() map[string]bool { + blacklistedAddrs := make(map[string]bool) + for acc := range simulationApplication.moduleAccountPermissions { + blacklistedAddrs[supply.NewModuleAddress(acc).String()] = !simulationApplication.tokenReceiveAllowedModules[acc] + } + + return blacklistedAddrs +} + +func (simulationApplication SimulationApplication) CheckBalance(t *testing.T, address sdkTypes.AccAddress, coins sdkTypes.Coins) { + ctxCheck := simulationApplication.BaseApp.NewContext(true, abciTypes.Header{}) + res := simulationApplication.AccountKeeper.GetAccount(ctxCheck, address) + + require.True(t, coins.IsEqual(res.GetCoins())) +} + +func (simulationApplication SimulationApplication) AddTestAddresses(context sdkTypes.Context, accountNumber int, amount sdkTypes.Int) []sdkTypes.AccAddress { + testAddresses := make([]sdkTypes.AccAddress, accountNumber) + + for i := 0; i < accountNumber; i++ { + pk := ed25519.GenPrivKey().PubKey() + testAddresses[i] = sdkTypes.AccAddress(pk.Address()) + } + + initCoins := sdkTypes.NewCoins(sdkTypes.NewCoin(simulationApplication.StakingKeeper.BondDenom(context), amount)) + totalSupply := sdkTypes.NewCoins(sdkTypes.NewCoin(simulationApplication.StakingKeeper.BondDenom(context), amount.MulRaw(int64(len(testAddresses))))) + prevSupply := simulationApplication.SupplyKeeper.GetSupply(context) + simulationApplication.SupplyKeeper.SetSupply(context, supply.NewSupply(prevSupply.GetTotal().Add(totalSupply...))) + + // fill all the addresses with some coins, set the loose pool tokens simultaneously + for _, addr := range testAddresses { + _, err := simulationApplication.BankKeeper.AddCoins(context, addr, initCoins) + if err != nil { + panic(err) + } + } + + return testAddresses +} + +func (simulationApplication SimulationApplication) Setup(isCheckTx bool) applications.SimulationApplication { + db := tendermintDB.NewMemDB() + newSimulationApplication := simulationApplication.Initialize(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0, map[int64]bool{}, simulationApplication.GetDefaultNodeHome()).(*SimulationApplication) + + if !isCheckTx { + // init chain must be called to stop deliverState from being nil + genesisState := simulationApplication.GetModuleBasicManager().DefaultGenesis() + + stateBytes, err := codec.MarshalJSONIndent(simulationApplication.Codec(), genesisState) + if err != nil { + panic(err) + } + + // Initialize the chain + newSimulationApplication.InitChain( + abciTypes.RequestInitChain{ + Validators: []abciTypes.ValidatorUpdate{}, + AppStateBytes: stateBytes, + }, + ) + } + + return newSimulationApplication +} + +func (simulationApplication SimulationApplication) SetupWithGenesisAccounts(accounts []exported.GenesisAccount) applications.SimulationApplication { + db := tendermintDB.NewMemDB() + newSimulationApplication := simulationApplication.Initialize(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0, map[int64]bool{}, simulationApplication.GetDefaultNodeHome()).(*SimulationApplication) + + // initialize the chain with the passed in genesis accounts + genesisState := simulationApplication.GetModuleBasicManager().DefaultGenesis() + + authGenesis := auth.NewGenesisState(auth.DefaultParams(), accounts) + genesisStateBz := simulationApplication.Codec().MustMarshalJSON(authGenesis) + genesisState[auth.ModuleName] = genesisStateBz + + stateBytes, err := codec.MarshalJSONIndent(simulationApplication.Codec(), genesisState) + if err != nil { + panic(err) + } + + // Initialize the chain + newSimulationApplication.InitChain( + abciTypes.RequestInitChain{ + Validators: []abciTypes.ValidatorUpdate{}, + AppStateBytes: stateBytes, + }, + ) + + newSimulationApplication.Commit() + newSimulationApplication.BeginBlock(abciTypes.RequestBeginBlock{Header: abciTypes.Header{Height: simulationApplication.application.BaseApp.LastBlockHeight() + 1}}) + + return newSimulationApplication +} + +func (simulationApplication SimulationApplication) NewTestApplication(isCheckTx bool) (applications.SimulationApplication, sdkTypes.Context) { + app := simulationApplication.Setup(isCheckTx) + ctx := simulationApplication.GetBaseApp().NewContext(isCheckTx, abciTypes.Header{}) + + return app, ctx +} + +func (simulationApplication SimulationApplication) InitializeSimulationApplication(logger log.Logger, db tendermintDB.DB, traceStore io.Writer, loadLatest bool, invCheckPeriod uint, skipUpgradeHeights map[int64]bool, home string, baseAppOptions ...func(*baseapp.BaseApp)) applications.SimulationApplication { + cache := store.NewCommitKVStoreCacheManager() + baseAppOptions = append(baseAppOptions, baseapp.SetInterBlockCache(cache), baseapp.SetMinGasPrices(viper.GetString("minimum-gas-prices"))) + simulationApplication.application = *simulationApplication.Initialize(logger, db, traceStore, loadLatest, invCheckPeriod, skipUpgradeHeights, home, baseAppOptions...).(*application) + + simulationApplication.transientStoreKeys = sdkTypes.NewTransientStoreKeys(params.TStoreKey) + + simulationApplication.ParamsKeeper = params.NewKeeper( + simulationApplication.codec, + simulationApplication.keys[params.StoreKey], + simulationApplication.transientStoreKeys[params.TStoreKey], + ) + + simulationApplication.AccountKeeper = auth.NewAccountKeeper( + simulationApplication.codec, + simulationApplication.keys[auth.StoreKey], + simulationApplication.ParamsKeeper.Subspace(auth.DefaultParamspace), + auth.ProtoBaseAccount, + ) + + blacklistedAddresses := make(map[string]bool) + for account := range simulationApplication.moduleAccountPermissions { + blacklistedAddresses[supply.NewModuleAddress(account).String()] = !simulationApplication.tokenReceiveAllowedModules[account] + } + + simulationApplication.BankKeeper = bank.NewBaseKeeper( + simulationApplication.AccountKeeper, + simulationApplication.ParamsKeeper.Subspace(bank.DefaultParamspace), + blacklistedAddresses, + ) + + simulationApplication.SupplyKeeper = supply.NewKeeper( + simulationApplication.codec, + simulationApplication.keys[supply.StoreKey], + simulationApplication.AccountKeeper, + simulationApplication.BankKeeper, + simulationApplication.moduleAccountPermissions, + ) + + simulationApplication.StakingKeeper = simulationApplication.stakingKeeper + + simulationApplication.MintKeeper = mint.NewKeeper( + simulationApplication.codec, + simulationApplication.keys[mint.StoreKey], + simulationApplication.ParamsKeeper.Subspace(mint.DefaultParamspace), + &simulationApplication.StakingKeeper, + simulationApplication.SupplyKeeper, + auth.FeeCollectorName, + ) + + blackListedModuleAddresses := make(map[string]bool) + for moduleAccount := range simulationApplication.moduleAccountPermissions { + blackListedModuleAddresses[supply.NewModuleAddress(moduleAccount).String()] = true + } + + simulationApplication.DistributionKeeper = simulationApplication.distributionKeeper + + simulationApplication.SlashingKeeper = simulationApplication.slashingKeeper + + simulationApplication.CrisisKeeper = simulationApplication.crisisKeeper + + simulationApplication.UpgradeKeeper = upgrade.NewKeeper( + skipUpgradeHeights, + simulationApplication.keys[upgrade.StoreKey], + simulationApplication.codec, + ) + + simulationApplication.EvidenceKeeper = *evidence.NewKeeper( + simulationApplication.codec, + simulationApplication.keys[evidence.StoreKey], + simulationApplication.ParamsKeeper.Subspace(evidence.DefaultParamspace), + &simulationApplication.StakingKeeper, + simulationApplication.SlashingKeeper, + ) + + evidenceRouter := evidence.NewRouter() + simulationApplication.EvidenceKeeper.SetRouter(evidenceRouter) + + simulationApplication.StakingKeeper = simulationApplication.stakingKeeper + + var wasmRouter = simulationApplication.BaseApp.Router() + + wasmDir := filepath.Join(home, wasm.ModuleName) + + wasmWrap := struct { + Wasm wasm.WasmConfig `mapstructure:"wasm"` + }{ + Wasm: wasm.DefaultWasmConfig(), + } + + err := viper.Unmarshal(&wasmWrap) + if err != nil { + panic("error while reading wasm config: " + err.Error()) + } + + wasmConfig := wasmWrap.Wasm + + wasmKeeper := wasm.NewKeeper( + simulationApplication.codec, + simulationApplication.keys[wasm.StoreKey], + simulationApplication.ParamsKeeper.Subspace(wasm.DefaultParamspace), + simulationApplication.AccountKeeper, + simulationApplication.BankKeeper, + simulationApplication.StakingKeeper, + wasmRouter, + wasmDir, + wasmConfig, + staking.ModuleName, + &wasm.MessageEncoders{Custom: wasmUtilities.CustomEncoder(assets.Prototype(), classifications.Prototype(), identities.Prototype(), maintainers.Prototype(), metas.Prototype(), orders.Prototype(), splits.Prototype())}, + nil) + + govRouter := gov.NewRouter().AddRoute( + gov.RouterKey, + gov.ProposalHandler, + ).AddRoute( + params.RouterKey, + params.NewParamChangeProposalHandler(simulationApplication.ParamsKeeper), + ).AddRoute( + distribution.RouterKey, + distribution.NewCommunityPoolSpendProposalHandler(simulationApplication.DistributionKeeper), + ).AddRoute( + upgrade.RouterKey, + upgrade.NewSoftwareUpgradeProposalHandler(simulationApplication.UpgradeKeeper), + ) + + if len(simulationApplication.enabledWasmProposalTypeList) != 0 { + govRouter.AddRoute(wasm.RouterKey, wasm.NewWasmProposalHandler(wasmKeeper, simulationApplication.enabledWasmProposalTypeList)) + } + + simulationApplication.GovKeeper = gov.NewKeeper( + simulationApplication.codec, + simulationApplication.keys[gov.StoreKey], + simulationApplication.ParamsKeeper.Subspace(gov.DefaultParamspace).WithKeyTable(gov.ParamKeyTable()), + simulationApplication.SupplyKeeper, + &simulationApplication.StakingKeeper, + govRouter, + ) + + simulationApplication.simulationManager = module.NewSimulationManager( + auth.NewAppModule(simulationApplication.AccountKeeper), + bank.NewAppModule(simulationApplication.BankKeeper, simulationApplication.AccountKeeper), + supply.NewAppModule(simulationApplication.SupplyKeeper, simulationApplication.AccountKeeper), + gov.NewAppModule(simulationApplication.GovKeeper, simulationApplication.AccountKeeper, simulationApplication.SupplyKeeper), + mint.NewAppModule(simulationApplication.MintKeeper), + staking.NewAppModule(simulationApplication.StakingKeeper, simulationApplication.AccountKeeper, simulationApplication.SupplyKeeper), + distribution.NewAppModule(simulationApplication.DistributionKeeper, simulationApplication.AccountKeeper, simulationApplication.SupplyKeeper, simulationApplication.StakingKeeper), + slashing.NewAppModule(simulationApplication.SlashingKeeper, simulationApplication.AccountKeeper, simulationApplication.StakingKeeper), + params.NewAppModule(), + assets.Prototype(), + classifications.Prototype(), + identities.Prototype(), + maintainers.Prototype(), + metas.Prototype(), + orders.Prototype(), + splits.Prototype(), + ) + + return &simulationApplication +} + +func NewSimulationApplication(name string, moduleBasicManager module.BasicManager, enabledWasmProposalTypeList []wasm.ProposalType, moduleAccountPermissions map[string][]string, tokenReceiveAllowedModules map[string]bool) applications.SimulationApplication { + return &SimulationApplication{ + application: application{ + name: name, + moduleBasicManager: moduleBasicManager, + codec: makeCodec(moduleBasicManager), + enabledWasmProposalTypeList: enabledWasmProposalTypeList, + moduleAccountPermissions: moduleAccountPermissions, + tokenReceiveAllowedModules: tokenReceiveAllowedModules, + }, + } +} diff --git a/schema/applications/simulationApplication.go b/schema/applications/simulationApplication.go index 2ec91ffb2..ffae89eb5 100644 --- a/schema/applications/simulationApplication.go +++ b/schema/applications/simulationApplication.go @@ -1,20 +1,23 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package applications import ( + "io" "testing" + tendermintDB "github.com/tendermint/tm-db" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/auth/exported" + "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - paramTypes "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/cosmos/cosmos-sdk/x/params" ) type SimulationApplication interface { @@ -24,7 +27,7 @@ type SimulationApplication interface { GetBaseApp() *baseapp.BaseApp GetKey(storeKey string) *sdk.KVStoreKey GetTKey(storeKey string) *sdk.TransientStoreKey - GetSubspace(moduleName string) paramTypes.Subspace + GetSubspace(moduleName string) params.Subspace GetModuleAccountPermissions() map[string][]string GetBlackListedAddresses() map[string]bool ModuleManager() *module.Manager @@ -34,6 +37,7 @@ type SimulationApplication interface { AddTestAddresses(sdk.Context, int, sdk.Int) []sdk.AccAddress Setup(bool) SimulationApplication - //SetupWithGenesisAccounts([]exported.GenesisAccount) SimulationApplication + SetupWithGenesisAccounts([]exported.GenesisAccount) SimulationApplication NewTestApplication(bool) (SimulationApplication, sdk.Context) + InitializeSimulationApplication(logger log.Logger, db tendermintDB.DB, traceStore io.Writer, loadLatest bool, invCheckPeriod uint, skipUpgradeHeights map[int64]bool, home string, baseAppOptions ...func(*baseapp.BaseApp)) SimulationApplication } diff --git a/schema/codec.go b/schema/codec.go index 15607a5d5..48dc7eaf8 100644 --- a/schema/codec.go +++ b/schema/codec.go @@ -4,11 +4,60 @@ package schema import ( - "reflect" - "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/schema/data" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + "github.com/AssetMantle/modules/schema/errors" + baseErrors "github.com/AssetMantle/modules/schema/errors/base" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/parameters" + baseParameters "github.com/AssetMantle/modules/schema/parameters/base" + "github.com/AssetMantle/modules/schema/properties" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/qualified" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" + "github.com/AssetMantle/modules/schema/traits" + typesSchema "github.com/AssetMantle/modules/schema/types" + baseTypes "github.com/AssetMantle/modules/schema/types/base" ) -func RegisterModuleConcrete(codec *codec.LegacyAmino, o interface{}) { - codec.RegisterConcrete(o, reflect.TypeOf(o).PkgPath()+"/"+reflect.TypeOf(o).Name(), nil) +func RegisterCodec(codec *codec.Codec) { + + data.RegisterCodec(codec) + baseData.RegisterCodec(codec) + + documents.RegisterCodec(codec) + baseDocuments.RegisterCodec(codec) + + errors.RegisterCodec(codec) + baseErrors.RegisterCodec(codec) + + helpers.RegisterCodec(codec) + + ids.RegisterCodec(codec) + baseIDs.RegisterCodec(codec) + + lists.RegisterCodec(codec) + baseLists.RegisterCodec(codec) + + parameters.RegisterCodec(codec) + baseParameters.RegisterCodec(codec) + + properties.RegisterCodec(codec) + baseProperties.RegisterCodec(codec) + + qualified.RegisterCodec(codec) + baseQualified.RegisterCodec(codec) + + traits.RegisterCodec(codec) + + typesSchema.RegisterCodec(codec) + baseTypes.RegisterCodec(codec) } diff --git a/schema/codec_test.go b/schema/codec_test.go new file mode 100644 index 000000000..25bb62d12 --- /dev/null +++ b/schema/codec_test.go @@ -0,0 +1,24 @@ +package schema + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + {"Test for Register Codec", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/data/base/accAddressData.go b/schema/data/base/accAddressData.go index 1178137ca..dea02575c 100644 --- a/schema/data/base/accAddressData.go +++ b/schema/data/base/accAddressData.go @@ -10,64 +10,67 @@ import ( "github.com/AssetMantle/modules/schema/data" dataConstants "github.com/AssetMantle/modules/schema/data/constants" + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" "github.com/AssetMantle/modules/schema/ids" baseIDs "github.com/AssetMantle/modules/schema/ids/base" "github.com/AssetMantle/modules/schema/traits" ) -var _ data.AccAddressData = (*Data_AccAddressData)(nil) - -func (accAddressData *Data_AccAddressData) Unmarshal(bytes []byte) error { - // TODO implement me - panic("implement me") +type accAddressData struct { + Value sdkTypes.AccAddress `json:"value"` } -func (accAddressData *Data_AccAddressData) GetID() ids.ID { - return baseIDs.GenerateDataID(accAddressData) +var _ data.AccAddressData = (*accAddressData)(nil) + +func (accAddressData accAddressData) GetID() ids.DataID { + return baseIDs.NewDataID(accAddressData) } -func (accAddressData *Data_AccAddressData) Compare(listable traits.Listable) int { - compareAccAddressData, err := dataFromInterface(listable) +func (accAddressData accAddressData) Compare(listable traits.Listable) int { + compareAccAddressData, err := accAddressDataFromInterface(listable) if err != nil { panic(err) } - return bytes.Compare(accAddressData.Bytes(), compareAccAddressData.Bytes()) + + return bytes.Compare(accAddressData.Value.Bytes(), compareAccAddressData.Value.Bytes()) } -func (accAddressData *Data_AccAddressData) String() string { - return sdkTypes.AccAddress(accAddressData.AccAddressData.Value).String() +func (accAddressData accAddressData) String() string { + return accAddressData.Value.String() } -func (accAddressData *Data_AccAddressData) Bytes() []byte { - return sdkTypes.AccAddress(accAddressData.AccAddressData.Value).Bytes() +func (accAddressData accAddressData) Bytes() []byte { + return accAddressData.Value.Bytes() } -func (accAddressData *Data_AccAddressData) GetType() ids.ID { +func (accAddressData accAddressData) GetType() ids.StringID { return dataConstants.AccAddressDataID } -func (accAddressData *Data_AccAddressData) ZeroValue() data.Data { - return AccAddressDataPrototype() +func (accAddressData accAddressData) ZeroValue() data.Data { + return NewAccAddressData(sdkTypes.AccAddress{}) } -func (accAddressData *Data_AccAddressData) GenerateHashID() ids.ID { +func (accAddressData accAddressData) GenerateHashID() ids.HashID { if accAddressData.Compare(accAddressData.ZeroValue()) == 0 { return baseIDs.GenerateHashID() } return baseIDs.GenerateHashID(accAddressData.Bytes()) } -func (accAddressData *Data_AccAddressData) Get() sdkTypes.AccAddress { - return accAddressData.AccAddressData.Value +func (accAddressData accAddressData) Get() sdkTypes.AccAddress { + return accAddressData.Value } -func AccAddressDataPrototype() data.Data { - return NewAccAddressData(sdkTypes.AccAddress{}) +func accAddressDataFromInterface(listable traits.Listable) (accAddressData, error) { + switch value := listable.(type) { + case accAddressData: + return value, nil + default: + return accAddressData{}, errorConstants.MetaDataError + } } -func GenerateAccAddressData(value sdkTypes.AccAddress) data.Data { - return NewAccAddressData(value) +func AccAddressDataPrototype() data.AccAddressData { + return accAddressData{}.ZeroValue().(data.AccAddressData) } -func NewAccAddressData(value sdkTypes.AccAddress) data.Data { - return &Data{ - Impl: &Data_AccAddressData{ - AccAddressData: &AccAddressData{ - Value: value, - }, - }} +func NewAccAddressData(value sdkTypes.AccAddress) data.AccAddressData { + return accAddressData{ + Value: value, + } } diff --git a/schema/data/base/accAddressData.pb.go b/schema/data/base/accAddressData.pb.go deleted file mode 100644 index d3b625cbe..000000000 --- a/schema/data/base/accAddressData.pb.go +++ /dev/null @@ -1,322 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/data/base/accAddressData.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type AccAddressData struct { - Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *AccAddressData) Reset() { *m = AccAddressData{} } -func (m *AccAddressData) String() string { return proto.CompactTextString(m) } -func (*AccAddressData) ProtoMessage() {} -func (*AccAddressData) Descriptor() ([]byte, []int) { - return fileDescriptor_4cb3a873274e32cc, []int{0} -} -func (m *AccAddressData) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AccAddressData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AccAddressData.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *AccAddressData) XXX_Merge(src proto.Message) { - xxx_messageInfo_AccAddressData.Merge(m, src) -} -func (m *AccAddressData) XXX_Size() int { - return m.Size() -} -func (m *AccAddressData) XXX_DiscardUnknown() { - xxx_messageInfo_AccAddressData.DiscardUnknown(m) -} - -var xxx_messageInfo_AccAddressData proto.InternalMessageInfo - -func (m *AccAddressData) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func init() { - proto.RegisterType((*AccAddressData)(nil), "base.AccAddressData") -} - -func init() { - proto.RegisterFile("schema/data/base/accAddressData.proto", fileDescriptor_4cb3a873274e32cc) -} - -var fileDescriptor_4cb3a873274e32cc = []byte{ - // 212 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2d, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x4f, 0x49, 0x2c, 0x49, 0xd4, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x4f, 0x4c, 0x4e, - 0x76, 0x4c, 0x49, 0x29, 0x4a, 0x2d, 0x2e, 0x76, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, 0x2f, - 0xc9, 0x17, 0x62, 0x01, 0x49, 0x29, 0xa9, 0x71, 0xf1, 0x39, 0xa2, 0xc8, 0x0a, 0x89, 0x70, 0xb1, - 0x96, 0x25, 0xe6, 0x94, 0xa6, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0xf0, 0x04, 0x41, 0x38, 0x4e, 0x33, - 0x18, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, - 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x81, 0x8b, 0x23, 0x39, 0x3f, 0x57, - 0x0f, 0x64, 0x98, 0x93, 0x30, 0xaa, 0x51, 0x01, 0x20, 0x7b, 0x02, 0x18, 0xa3, 0xf4, 0xd3, 0x33, - 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x1d, 0x8b, 0x8b, 0x53, 0x4b, 0x7c, 0x13, - 0xf3, 0x4a, 0x72, 0x52, 0xf5, 0x73, 0xf3, 0x53, 0x4a, 0x73, 0x52, 0x8b, 0xf5, 0xd1, 0xdd, 0xbb, - 0x88, 0x89, 0xd9, 0x29, 0x22, 0x62, 0x15, 0x13, 0x8b, 0x53, 0x62, 0x71, 0xea, 0x29, 0x08, 0xf5, - 0x88, 0x49, 0x00, 0x44, 0xc5, 0xb8, 0x07, 0x38, 0xf9, 0xa6, 0x96, 0x24, 0x82, 0xd4, 0xbe, 0x82, - 0xc8, 0x24, 0xb1, 0x81, 0xfd, 0x63, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x07, 0xe4, 0x8c, 0x3d, - 0xf8, 0x00, 0x00, 0x00, -} - -func (m *AccAddressData) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AccAddressData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AccAddressData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - i -= len(m.Value) - copy(dAtA[i:], m.Value) - i = encodeVarintAccAddressData(dAtA, i, uint64(len(m.Value))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintAccAddressData(dAtA []byte, offset int, v uint64) int { - offset -= sovAccAddressData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *AccAddressData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Value) - if l > 0 { - n += 1 + l + sovAccAddressData(uint64(l)) - } - return n -} - -func sovAccAddressData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozAccAddressData(x uint64) (n int) { - return sovAccAddressData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *AccAddressData) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAccAddressData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AccAddressData: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AccAddressData: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAccAddressData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthAccAddressData - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthAccAddressData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...) - if m.Value == nil { - m.Value = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAccAddressData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAccAddressData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipAccAddressData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAccAddressData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAccAddressData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAccAddressData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthAccAddressData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupAccAddressData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthAccAddressData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthAccAddressData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowAccAddressData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupAccAddressData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/data/base/accAddressData.proto b/schema/data/base/accAddressData.proto deleted file mode 100644 index 66f113715..000000000 --- a/schema/data/base/accAddressData.proto +++ /dev/null @@ -1,6 +0,0 @@ -syntax = "proto3"; -package base; - -message AccAddressData{ - bytes value = 1; -} \ No newline at end of file diff --git a/schema/data/base/booleanData.pb.go b/schema/data/base/booleanData.pb.go deleted file mode 100644 index e31680d7b..000000000 --- a/schema/data/base/booleanData.pb.go +++ /dev/null @@ -1,310 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/data/base/booleanData.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type BooleanData struct { - Value bool `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *BooleanData) Reset() { *m = BooleanData{} } -func (m *BooleanData) String() string { return proto.CompactTextString(m) } -func (*BooleanData) ProtoMessage() {} -func (*BooleanData) Descriptor() ([]byte, []int) { - return fileDescriptor_8c29d335636045f0, []int{0} -} -func (m *BooleanData) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BooleanData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BooleanData.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *BooleanData) XXX_Merge(src proto.Message) { - xxx_messageInfo_BooleanData.Merge(m, src) -} -func (m *BooleanData) XXX_Size() int { - return m.Size() -} -func (m *BooleanData) XXX_DiscardUnknown() { - xxx_messageInfo_BooleanData.DiscardUnknown(m) -} - -var xxx_messageInfo_BooleanData proto.InternalMessageInfo - -func (m *BooleanData) GetValue() bool { - if m != nil { - return m.Value - } - return false -} - -func init() { - proto.RegisterType((*BooleanData)(nil), "base.BooleanData") -} - -func init() { - proto.RegisterFile("schema/data/base/booleanData.proto", fileDescriptor_8c29d335636045f0) -} - -var fileDescriptor_8c29d335636045f0 = []byte{ - // 209 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2a, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x4f, 0x49, 0x2c, 0x49, 0xd4, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x4f, 0xca, 0xcf, - 0xcf, 0x49, 0x4d, 0xcc, 0x73, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, - 0x01, 0x89, 0x2b, 0x29, 0x73, 0x71, 0x3b, 0x21, 0xa4, 0x84, 0x44, 0xb8, 0x58, 0xcb, 0x12, 0x73, - 0x4a, 0x53, 0x25, 0x18, 0x15, 0x18, 0x35, 0x38, 0x82, 0x20, 0x1c, 0xa7, 0xa9, 0x8c, 0x27, 0x1e, - 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, - 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0xc0, 0xc5, 0x91, 0x9c, 0x9f, 0xab, 0x07, 0x32, 0xc9, - 0x49, 0x00, 0xc9, 0x9c, 0x00, 0x90, 0x0d, 0x01, 0x8c, 0x51, 0xfa, 0xe9, 0x99, 0x25, 0x19, 0xa5, - 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x8e, 0xc5, 0xc5, 0xa9, 0x25, 0xbe, 0x89, 0x79, 0x25, 0x39, - 0xa9, 0xfa, 0xb9, 0xf9, 0x29, 0xa5, 0x39, 0xa9, 0xc5, 0xfa, 0xe8, 0xce, 0x5c, 0xc4, 0xc4, 0xec, - 0x14, 0x11, 0xb1, 0x8a, 0x89, 0xc5, 0x29, 0xb1, 0x38, 0xf5, 0x14, 0x84, 0x7a, 0xc4, 0x24, 0x00, - 0xa2, 0x62, 0xdc, 0x03, 0x9c, 0x7c, 0x53, 0x4b, 0x12, 0x41, 0x6a, 0x5f, 0x41, 0x64, 0x92, 0xd8, - 0xc0, 0x3e, 0x31, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x88, 0x0e, 0xbd, 0x82, 0xef, 0x00, 0x00, - 0x00, -} - -func (m *BooleanData) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *BooleanData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *BooleanData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Value { - i-- - if m.Value { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintBooleanData(dAtA []byte, offset int, v uint64) int { - offset -= sovBooleanData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *BooleanData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Value { - n += 2 - } - return n -} - -func sovBooleanData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozBooleanData(x uint64) (n int) { - return sovBooleanData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *BooleanData) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBooleanData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: BooleanData: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BooleanData: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowBooleanData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Value = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipBooleanData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthBooleanData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipBooleanData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowBooleanData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowBooleanData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowBooleanData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthBooleanData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupBooleanData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthBooleanData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthBooleanData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowBooleanData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupBooleanData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/data/base/booleanData.proto b/schema/data/base/booleanData.proto deleted file mode 100644 index 002dedd50..000000000 --- a/schema/data/base/booleanData.proto +++ /dev/null @@ -1,6 +0,0 @@ -syntax = "proto3"; -package base; - -message BooleanData{ - bool value = 1; -} \ No newline at end of file diff --git a/schema/data/base/codec.go b/schema/data/base/codec.go index 189733a5d..bb2a6ca00 100644 --- a/schema/data/base/codec.go +++ b/schema/data/base/codec.go @@ -6,22 +6,15 @@ package base import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/AssetMantle/modules/schema" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { - schema.RegisterModuleConcrete(codec, AccAddressData{}) - schema.RegisterModuleConcrete(codec, BooleanData{}) - schema.RegisterModuleConcrete(codec, DecData{}) - schema.RegisterModuleConcrete(codec, HeightData{}) - schema.RegisterModuleConcrete(codec, IDData{}) - schema.RegisterModuleConcrete(codec, StringData{}) - schema.RegisterModuleConcrete(codec, Data_AccAddressData{}) - schema.RegisterModuleConcrete(codec, Data_BooleanData{}) - schema.RegisterModuleConcrete(codec, Data_DecData{}) - schema.RegisterModuleConcrete(codec, Data_HeightData{}) - schema.RegisterModuleConcrete(codec, Data_IdData{}) - schema.RegisterModuleConcrete(codec, Data_StringData{}) - schema.RegisterModuleConcrete(codec, Data{}) - codec.RegisterInterface((*isData_Impl)(nil), nil) +func RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, accAddressData{}) + codecUtilities.RegisterModuleConcrete(codec, booleanData{}) + codecUtilities.RegisterModuleConcrete(codec, decData{}) + codecUtilities.RegisterModuleConcrete(codec, heightData{}) + codecUtilities.RegisterModuleConcrete(codec, idData{}) + codecUtilities.RegisterModuleConcrete(codec, listData{}) + codecUtilities.RegisterModuleConcrete(codec, stringData{}) } diff --git a/schema/data/base/codec_test.go b/schema/data/base/codec_test.go new file mode 100644 index 000000000..f8fde6322 --- /dev/null +++ b/schema/data/base/codec_test.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + + {"+ve", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/data/base/data.go b/schema/data/base/data.go deleted file mode 100644 index e03c31ae1..000000000 --- a/schema/data/base/data.go +++ /dev/null @@ -1,38 +0,0 @@ -package base - -import ( - "github.com/AssetMantle/modules/schema/data" - errorConstants "github.com/AssetMantle/modules/schema/errors/constants" - "github.com/AssetMantle/modules/schema/ids" - "github.com/AssetMantle/modules/schema/traits" -) - -var _ data.Data = (*Data)(nil) - -func (x *Data) GetID() ids.ID { - return x.Impl.(data.Data).GetID() -} -func (x *Data) Bytes() []byte { - return x.Impl.(data.Data).Bytes() -} -func (x *Data) GetType() ids.ID { - return x.Impl.(data.Data).GetType() -} -func (x *Data) ZeroValue() data.Data { - return x.Impl.(data.Data).ZeroValue() -} -func (x *Data) GenerateHashID() ids.ID { - return x.Impl.(data.Data).GenerateHashID() -} -func (x *Data) Compare(listable traits.Listable) int { - return x.Impl.(data.Data).Compare(listable) -} - -func dataFromInterface(listable traits.Listable) (data.Data, error) { - switch value := listable.(type) { - case data.Data: - return value, nil - default: - panic(errorConstants.MetaDataError) - } -} diff --git a/schema/data/base/data.pb.go b/schema/data/base/data.pb.go deleted file mode 100644 index 7cff5c62d..000000000 --- a/schema/data/base/data.pb.go +++ /dev/null @@ -1,799 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/data/base/data.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Data struct { - // Types that are valid to be assigned to Impl: - // *Data_AccAddressData - // *Data_BooleanData - // *Data_DecData - // *Data_HeightData - // *Data_IdData - // *Data_StringData - Impl isData_Impl `protobuf_oneof:"impl"` -} - -func (m *Data) Reset() { *m = Data{} } -func (m *Data) String() string { return proto.CompactTextString(m) } -func (*Data) ProtoMessage() {} -func (*Data) Descriptor() ([]byte, []int) { - return fileDescriptor_21ddc08ef6219022, []int{0} -} -func (m *Data) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Data) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Data.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Data) XXX_Merge(src proto.Message) { - xxx_messageInfo_Data.Merge(m, src) -} -func (m *Data) XXX_Size() int { - return m.Size() -} -func (m *Data) XXX_DiscardUnknown() { - xxx_messageInfo_Data.DiscardUnknown(m) -} - -var xxx_messageInfo_Data proto.InternalMessageInfo - -type isData_Impl interface { - isData_Impl() - MarshalTo([]byte) (int, error) - Size() int -} - -type Data_AccAddressData struct { - AccAddressData *AccAddressData `protobuf:"bytes,1,opt,name=accAddressData,proto3,oneof" json:"accAddressData,omitempty"` -} -type Data_BooleanData struct { - BooleanData *BooleanData `protobuf:"bytes,2,opt,name=booleanData,proto3,oneof" json:"booleanData,omitempty"` -} -type Data_DecData struct { - DecData *DecData `protobuf:"bytes,3,opt,name=decData,proto3,oneof" json:"decData,omitempty"` -} -type Data_HeightData struct { - HeightData *HeightData `protobuf:"bytes,4,opt,name=heightData,proto3,oneof" json:"heightData,omitempty"` -} -type Data_IdData struct { - IdData *IDData `protobuf:"bytes,5,opt,name=idData,proto3,oneof" json:"idData,omitempty"` -} -type Data_StringData struct { - StringData *StringData `protobuf:"bytes,7,opt,name=stringData,proto3,oneof" json:"stringData,omitempty"` -} - -func (*Data_AccAddressData) isData_Impl() {} -func (*Data_BooleanData) isData_Impl() {} -func (*Data_DecData) isData_Impl() {} -func (*Data_HeightData) isData_Impl() {} -func (*Data_IdData) isData_Impl() {} -func (*Data_StringData) isData_Impl() {} - -func (m *Data) GetImpl() isData_Impl { - if m != nil { - return m.Impl - } - return nil -} - -func (m *Data) GetAccAddressData() *AccAddressData { - if x, ok := m.GetImpl().(*Data_AccAddressData); ok { - return x.AccAddressData - } - return nil -} - -func (m *Data) GetBooleanData() *BooleanData { - if x, ok := m.GetImpl().(*Data_BooleanData); ok { - return x.BooleanData - } - return nil -} - -func (m *Data) GetDecData() *DecData { - if x, ok := m.GetImpl().(*Data_DecData); ok { - return x.DecData - } - return nil -} - -func (m *Data) GetHeightData() *HeightData { - if x, ok := m.GetImpl().(*Data_HeightData); ok { - return x.HeightData - } - return nil -} - -func (m *Data) GetIdData() *IDData { - if x, ok := m.GetImpl().(*Data_IdData); ok { - return x.IdData - } - return nil -} - -func (m *Data) GetStringData() *StringData { - if x, ok := m.GetImpl().(*Data_StringData); ok { - return x.StringData - } - return nil -} - -// XXX_OneofWrappers is for the internal use of the proto package. -func (*Data) XXX_OneofWrappers() []interface{} { - return []interface{}{ - (*Data_AccAddressData)(nil), - (*Data_BooleanData)(nil), - (*Data_DecData)(nil), - (*Data_HeightData)(nil), - (*Data_IdData)(nil), - (*Data_StringData)(nil), - } -} - -func init() { - proto.RegisterType((*Data)(nil), "base.Data") -} - -func init() { proto.RegisterFile("schema/data/base/data.proto", fileDescriptor_21ddc08ef6219022) } - -var fileDescriptor_21ddc08ef6219022 = []byte{ - // 373 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x91, 0x41, 0x4b, 0xf3, 0x30, - 0x1c, 0xc6, 0xdb, 0xae, 0xef, 0xf6, 0x9a, 0xa9, 0xcc, 0xe2, 0xa1, 0x4c, 0x2c, 0x3a, 0x50, 0xf4, - 0xd2, 0xc2, 0xc4, 0xab, 0xb0, 0x30, 0xb0, 0x1e, 0x06, 0xa3, 0x5e, 0x86, 0x78, 0x49, 0xdb, 0xb0, - 0x16, 0xda, 0x65, 0x2c, 0xd9, 0xd7, 0x10, 0x3f, 0x83, 0x47, 0x3f, 0x85, 0x47, 0xf1, 0xb4, 0xa3, - 0x47, 0xe9, 0x6e, 0x7e, 0x0a, 0x49, 0x32, 0xd7, 0x6c, 0x05, 0x4f, 0x69, 0xff, 0xcf, 0xef, 0x79, - 0xc2, 0xff, 0x09, 0x38, 0xa2, 0x51, 0x82, 0x73, 0xe4, 0xc5, 0x88, 0x21, 0x2f, 0x44, 0x14, 0x8b, - 0x2f, 0x77, 0x3a, 0x23, 0x8c, 0x58, 0x26, 0x1f, 0xb4, 0xcf, 0x2a, 0x08, 0x8a, 0xa2, 0x5e, 0x1c, - 0xcf, 0x30, 0xa5, 0xfd, 0x35, 0xdc, 0xee, 0x54, 0xb0, 0x90, 0x90, 0x0c, 0xa3, 0x89, 0xc2, 0x38, - 0xd5, 0xdb, 0x70, 0xa4, 0xe8, 0xa7, 0x15, 0x3d, 0xc1, 0xe9, 0x38, 0x61, 0x0a, 0x72, 0x5c, 0x41, - 0xd2, 0xf8, 0xcf, 0x04, 0xca, 0x66, 0xe9, 0x64, 0x5c, 0x22, 0x9d, 0x37, 0x03, 0x98, 0xfc, 0xd7, - 0xba, 0x01, 0xfb, 0x9b, 0x9b, 0xd8, 0xfa, 0x89, 0x7e, 0xd1, 0xec, 0x1e, 0xba, 0xdc, 0xe8, 0xf6, - 0x36, 0x34, 0x5f, 0x0b, 0xb6, 0x68, 0xeb, 0x1a, 0x34, 0x95, 0x15, 0x6d, 0x43, 0x98, 0x0f, 0xa4, - 0x19, 0x96, 0x82, 0xaf, 0x05, 0x2a, 0x67, 0x5d, 0x82, 0xc6, 0x6a, 0x6b, 0xbb, 0x26, 0x2c, 0x7b, - 0xd2, 0xd2, 0x97, 0x43, 0x5f, 0x0b, 0x7e, 0x75, 0xab, 0x0b, 0x40, 0x59, 0x80, 0x6d, 0x0a, 0xba, - 0x25, 0x69, 0x7f, 0x3d, 0xf7, 0xb5, 0x40, 0xa1, 0xac, 0x73, 0x50, 0x97, 0x8d, 0xd8, 0xff, 0x04, - 0xbf, 0x2b, 0xf9, 0xbb, 0xfe, 0x8a, 0x5d, 0xa9, 0x3c, 0xbb, 0xac, 0xc6, 0x6e, 0xa8, 0xd9, 0xf7, - 0xeb, 0x39, 0xcf, 0x2e, 0x29, 0x58, 0x07, 0x66, 0x9a, 0x4f, 0x33, 0xf8, 0xa4, 0xbf, 0x17, 0x8e, - 0xbe, 0x28, 0x1c, 0xfd, 0xab, 0x70, 0xf4, 0xe7, 0xa5, 0xa3, 0x2d, 0x96, 0x8e, 0xf6, 0xb9, 0x74, - 0x34, 0xf0, 0x3f, 0x22, 0xb9, 0x48, 0x81, 0x3b, 0xdc, 0x32, 0xe4, 0x95, 0x0f, 0xf5, 0x07, 0x6f, - 0x9c, 0xb2, 0x64, 0x1e, 0xba, 0x11, 0xc9, 0xbd, 0x1e, 0xa5, 0x98, 0x0d, 0xd0, 0x84, 0x65, 0xd8, - 0xcb, 0x49, 0x3c, 0xcf, 0x30, 0xf5, 0xb6, 0x9f, 0xed, 0xc5, 0xa8, 0xc1, 0xd1, 0xe8, 0xd5, 0x30, - 0x21, 0xa2, 0xf8, 0x43, 0x1e, 0x85, 0xd1, 0xe2, 0xc7, 0xe3, 0xed, 0x10, 0x0e, 0x30, 0x43, 0x9c, - 0xfd, 0x96, 0x4a, 0x58, 0x17, 0x4f, 0x7b, 0xf5, 0x13, 0x00, 0x00, 0xff, 0xff, 0x2e, 0x3b, 0xb5, - 0x13, 0xcf, 0x02, 0x00, 0x00, -} - -func (m *Data) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Data) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Impl != nil { - { - size := m.Impl.Size() - i -= size - if _, err := m.Impl.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - } - } - return len(dAtA) - i, nil -} - -func (m *Data_AccAddressData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data_AccAddressData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.AccAddressData != nil { - { - size, err := m.AccAddressData.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} -func (m *Data_BooleanData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data_BooleanData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.BooleanData != nil { - { - size, err := m.BooleanData.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - return len(dAtA) - i, nil -} -func (m *Data_DecData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data_DecData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.DecData != nil { - { - size, err := m.DecData.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - return len(dAtA) - i, nil -} -func (m *Data_HeightData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data_HeightData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.HeightData != nil { - { - size, err := m.HeightData.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - return len(dAtA) - i, nil -} -func (m *Data_IdData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data_IdData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.IdData != nil { - { - size, err := m.IdData.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - return len(dAtA) - i, nil -} -func (m *Data_StringData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data_StringData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.StringData != nil { - { - size, err := m.StringData.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - return len(dAtA) - i, nil -} -func encodeVarintData(dAtA []byte, offset int, v uint64) int { - offset -= sovData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Data) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Impl != nil { - n += m.Impl.Size() - } - return n -} - -func (m *Data_AccAddressData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.AccAddressData != nil { - l = m.AccAddressData.Size() - n += 1 + l + sovData(uint64(l)) - } - return n -} -func (m *Data_BooleanData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.BooleanData != nil { - l = m.BooleanData.Size() - n += 1 + l + sovData(uint64(l)) - } - return n -} -func (m *Data_DecData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.DecData != nil { - l = m.DecData.Size() - n += 1 + l + sovData(uint64(l)) - } - return n -} -func (m *Data_HeightData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.HeightData != nil { - l = m.HeightData.Size() - n += 1 + l + sovData(uint64(l)) - } - return n -} -func (m *Data_IdData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.IdData != nil { - l = m.IdData.Size() - n += 1 + l + sovData(uint64(l)) - } - return n -} -func (m *Data_StringData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.StringData != nil { - l = m.StringData.Size() - n += 1 + l + sovData(uint64(l)) - } - return n -} - -func sovData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozData(x uint64) (n int) { - return sovData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Data) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Data: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Data: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AccAddressData", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &AccAddressData{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &Data_AccAddressData{v} - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field BooleanData", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &BooleanData{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &Data_BooleanData{v} - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DecData", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &DecData{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &Data_DecData{v} - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HeightData", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &HeightData{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &Data_HeightData{v} - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IdData", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &IDData{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &Data_IdData{v} - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StringData", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &StringData{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &Data_StringData{v} - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/data/base/data.proto b/schema/data/base/data.proto deleted file mode 100644 index 8830394d9..000000000 --- a/schema/data/base/data.proto +++ /dev/null @@ -1,20 +0,0 @@ -syntax = "proto3"; -package base; -import "schema/data/base/accAddressData.proto"; -import "schema/data/base/booleanData.proto"; -import "schema/data/base/decData.proto"; -import "schema/data/base/heightData.proto"; -import "schema/data/base/idData.proto"; -import "schema/data/base/stringData.proto"; - - -message Data{ - oneof impl{ - AccAddressData accAddressData = 1; - BooleanData booleanData = 2; - DecData decData = 3; - HeightData heightData = 4; - IDData idData = 5; - StringData stringData = 7; - } -} \ No newline at end of file diff --git a/schema/data/base/decData.go b/schema/data/base/decData.go index db3942968..0bc4bbb87 100644 --- a/schema/data/base/decData.go +++ b/schema/data/base/decData.go @@ -4,67 +4,77 @@ package base import ( - "bytes" - sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/AssetMantle/modules/schema/data" dataConstants "github.com/AssetMantle/modules/schema/data/constants" + "github.com/AssetMantle/modules/schema/errors/constants" "github.com/AssetMantle/modules/schema/ids" baseIDs "github.com/AssetMantle/modules/schema/ids/base" "github.com/AssetMantle/modules/schema/traits" ) -var _ data.DecData = (*Data_DecData)(nil) - -func (decData *Data_DecData) Unmarshal(bytes []byte) error { - // TODO implement me - panic("implement me") +type decData struct { + Value sdkTypes.Dec `json:"value"` } -func (decData *Data_DecData) GetID() ids.ID { - return baseIDs.GenerateDataID(decData) + +var _ data.DecData = (*decData)(nil) + +func (decData decData) GetID() ids.DataID { + return baseIDs.NewDataID(decData) } -func (decData *Data_DecData) Compare(listable traits.Listable) int { - compareDecData, err := dataFromInterface(listable) +func (decData decData) Compare(listable traits.Listable) int { + compareDecData, err := decDataFromInterface(listable) if err != nil { panic(err) } - return bytes.Compare(decData.Bytes(), compareDecData.Bytes()) + if decData.Value.GT(compareDecData.Value) { + return 1 + } else if decData.Value.LT(compareDecData.Value) { + return -1 + } + + return 0 } -func (decData *Data_DecData) String() string { - return decData.DecData.Value.String() +func (decData decData) String() string { + return decData.Value.String() } -func (decData *Data_DecData) Bytes() []byte { - return sdkTypes.SortableDecBytes(decData.DecData.Value) +func (decData decData) Bytes() []byte { + return decData.Value.Bytes() } -func (decData *Data_DecData) GetType() ids.ID { +func (decData decData) GetType() ids.StringID { return dataConstants.DecDataID } -func (decData *Data_DecData) ZeroValue() data.Data { +func (decData decData) ZeroValue() data.Data { return NewDecData(sdkTypes.ZeroDec()) } -func (decData *Data_DecData) GenerateHashID() ids.ID { +func (decData decData) GenerateHashID() ids.HashID { if decData.Compare(decData.ZeroValue()) == 0 { return baseIDs.GenerateHashID() } return baseIDs.GenerateHashID(decData.Bytes()) } -func (decData *Data_DecData) Get() sdkTypes.Dec { - return decData.DecData.Value +func (decData decData) Get() sdkTypes.Dec { + return decData.Value +} + +func decDataFromInterface(listable traits.Listable) (decData, error) { + switch value := listable.(type) { + case decData: + return value, nil + default: + return decData{}, constants.MetaDataError + } } -func DecDataPrototype() data.Data { - return NewDecData(sdkTypes.ZeroDec()).ZeroValue().(data.DecData) +func DecDataPrototype() data.DecData { + return decData{}.ZeroValue().(data.DecData) } -func NewDecData(value sdkTypes.Dec) data.Data { - return &Data{ - Impl: &Data_DecData{ - DecData: &DecData{ - Value: value, - }, - }, +func NewDecData(value sdkTypes.Dec) data.DecData { + return decData{ + Value: value, } } diff --git a/schema/data/base/decData.pb.go b/schema/data/base/decData.pb.go deleted file mode 100644 index 5d7cbe9e4..000000000 --- a/schema/data/base/decData.pb.go +++ /dev/null @@ -1,318 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/data/base/decData.proto - -package base - -import ( - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type DecData struct { - Value github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=value,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"value"` -} - -func (m *DecData) Reset() { *m = DecData{} } -func (m *DecData) String() string { return proto.CompactTextString(m) } -func (*DecData) ProtoMessage() {} -func (*DecData) Descriptor() ([]byte, []int) { - return fileDescriptor_31cbbdd3167e4e16, []int{0} -} -func (m *DecData) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DecData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DecData.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DecData) XXX_Merge(src proto.Message) { - xxx_messageInfo_DecData.Merge(m, src) -} -func (m *DecData) XXX_Size() int { - return m.Size() -} -func (m *DecData) XXX_DiscardUnknown() { - xxx_messageInfo_DecData.DiscardUnknown(m) -} - -var xxx_messageInfo_DecData proto.InternalMessageInfo - -func init() { - proto.RegisterType((*DecData)(nil), "base.DecData") -} - -func init() { proto.RegisterFile("schema/data/base/decData.proto", fileDescriptor_31cbbdd3167e4e16) } - -var fileDescriptor_31cbbdd3167e4e16 = []byte{ - // 252 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2b, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x4f, 0x49, 0x2c, 0x49, 0xd4, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x4f, 0x49, 0x4d, - 0x76, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x89, 0x49, 0x89, - 0xa4, 0xe7, 0xa7, 0xe7, 0x83, 0x05, 0xf4, 0x41, 0x2c, 0x88, 0x9c, 0x92, 0x3f, 0x17, 0xbb, 0x0b, - 0x44, 0xb1, 0x90, 0x0b, 0x17, 0x6b, 0x59, 0x62, 0x4e, 0x69, 0xaa, 0x04, 0xa3, 0x02, 0xa3, 0x06, - 0xa7, 0x93, 0xde, 0x89, 0x7b, 0xf2, 0x0c, 0xb7, 0xee, 0xc9, 0xab, 0xa5, 0x67, 0x96, 0x64, 0x94, - 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x27, 0xe7, 0x17, 0xe7, 0xe6, 0x17, 0x43, 0x29, 0xdd, 0xe2, - 0x94, 0x6c, 0xfd, 0x92, 0xca, 0x82, 0xd4, 0x62, 0x3d, 0x97, 0xd4, 0xe4, 0x20, 0x88, 0x66, 0xa7, - 0x89, 0x8c, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, - 0xc7, 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0xc0, 0xc5, 0x91, 0x9c, 0x9f, - 0xab, 0x07, 0x72, 0x8b, 0x13, 0x0f, 0xd4, 0xce, 0x00, 0x90, 0x1b, 0x02, 0x18, 0xa3, 0xf4, 0x91, - 0xec, 0x70, 0x2c, 0x2e, 0x4e, 0x2d, 0xf1, 0x4d, 0xcc, 0x2b, 0xc9, 0x49, 0xd5, 0xcf, 0xcd, 0x4f, - 0x29, 0xcd, 0x49, 0x2d, 0xd6, 0x47, 0xf7, 0xe0, 0x22, 0x26, 0x66, 0xa7, 0x88, 0x88, 0x55, 0x4c, - 0x2c, 0x4e, 0x89, 0xc5, 0xa9, 0xa7, 0x20, 0xd4, 0x23, 0x26, 0x01, 0x10, 0x15, 0xe3, 0x1e, 0xe0, - 0xe4, 0x9b, 0x5a, 0x92, 0x08, 0x52, 0xfb, 0x0a, 0x22, 0x93, 0xc4, 0x06, 0xf6, 0xab, 0x31, 0x20, - 0x00, 0x00, 0xff, 0xff, 0x0f, 0xff, 0xcb, 0xb8, 0x29, 0x01, 0x00, 0x00, -} - -func (m *DecData) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DecData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DecData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Value.Size() - i -= size - if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintDecData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintDecData(dAtA []byte, offset int, v uint64) int { - offset -= sovDecData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *DecData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Value.Size() - n += 1 + l + sovDecData(uint64(l)) - return n -} - -func sovDecData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozDecData(x uint64) (n int) { - return sovDecData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *DecData) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDecData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DecData: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DecData: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDecData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthDecData - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthDecData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipDecData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDecData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipDecData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowDecData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowDecData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowDecData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthDecData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupDecData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthDecData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthDecData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowDecData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupDecData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/data/base/decData.proto b/schema/data/base/decData.proto deleted file mode 100644 index 913e592ea..000000000 --- a/schema/data/base/decData.proto +++ /dev/null @@ -1,7 +0,0 @@ -syntax = "proto3"; -package base; -import "gogoproto/gogo.proto"; - -message DecData{ - string value = 1 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; -} \ No newline at end of file diff --git a/schema/data/base/heightData.pb.go b/schema/data/base/heightData.pb.go deleted file mode 100644 index 1b6f4d3de..000000000 --- a/schema/data/base/heightData.pb.go +++ /dev/null @@ -1,301 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/data/base/heightData.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type HeightData struct { - Value int64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *HeightData) Reset() { *m = HeightData{} } -func (m *HeightData) String() string { return proto.CompactTextString(m) } -func (*HeightData) ProtoMessage() {} -func (*HeightData) Descriptor() ([]byte, []int) { - return fileDescriptor_675e2f1db0d6c929, []int{0} -} -func (m *HeightData) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *HeightData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_HeightData.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *HeightData) XXX_Merge(src proto.Message) { - xxx_messageInfo_HeightData.Merge(m, src) -} -func (m *HeightData) XXX_Size() int { - return m.Size() -} -func (m *HeightData) XXX_DiscardUnknown() { - xxx_messageInfo_HeightData.DiscardUnknown(m) -} - -var xxx_messageInfo_HeightData proto.InternalMessageInfo - -func (m *HeightData) GetValue() int64 { - if m != nil { - return m.Value - } - return 0 -} - -func init() { - proto.RegisterType((*HeightData)(nil), "base.HeightData") -} - -func init() { proto.RegisterFile("schema/data/base/heightData.proto", fileDescriptor_675e2f1db0d6c929) } - -var fileDescriptor_675e2f1db0d6c929 = []byte{ - // 208 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2c, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x4f, 0x49, 0x2c, 0x49, 0xd4, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x48, 0xcd, - 0x4c, 0xcf, 0x28, 0x71, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, - 0x09, 0x2b, 0x29, 0x71, 0x71, 0x79, 0xc0, 0x65, 0x84, 0x44, 0xb8, 0x58, 0xcb, 0x12, 0x73, 0x4a, - 0x53, 0x25, 0x18, 0x15, 0x18, 0x35, 0x98, 0x83, 0x20, 0x1c, 0xa7, 0x29, 0x8c, 0x27, 0x1e, 0xc9, - 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, - 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0xc0, 0xc5, 0x91, 0x9c, 0x9f, 0xab, 0x07, 0x32, 0xc8, 0x89, - 0x1f, 0x61, 0x4c, 0x00, 0xc8, 0xfc, 0x00, 0xc6, 0x28, 0xfd, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, - 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0xc7, 0xe2, 0xe2, 0xd4, 0x12, 0xdf, 0xc4, 0xbc, 0x92, 0x9c, 0x54, - 0xfd, 0xdc, 0xfc, 0x94, 0xd2, 0x9c, 0xd4, 0x62, 0x7d, 0x74, 0x37, 0x2e, 0x62, 0x62, 0x76, 0x8a, - 0x88, 0x58, 0xc5, 0xc4, 0xe2, 0x94, 0x58, 0x9c, 0x7a, 0x0a, 0x42, 0x3d, 0x62, 0x12, 0x00, 0x51, - 0x31, 0xee, 0x01, 0x4e, 0xbe, 0xa9, 0x25, 0x89, 0x20, 0xb5, 0xaf, 0x20, 0x32, 0x49, 0x6c, 0x60, - 0x7f, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xd6, 0x1e, 0xb4, 0x6f, 0xec, 0x00, 0x00, 0x00, -} - -func (m *HeightData) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *HeightData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *HeightData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Value != 0 { - i = encodeVarintHeightData(dAtA, i, uint64(m.Value)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintHeightData(dAtA []byte, offset int, v uint64) int { - offset -= sovHeightData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *HeightData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Value != 0 { - n += 1 + sovHeightData(uint64(m.Value)) - } - return n -} - -func sovHeightData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozHeightData(x uint64) (n int) { - return sovHeightData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *HeightData) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHeightData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: HeightData: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: HeightData: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - m.Value = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHeightData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Value |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipHeightData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHeightData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipHeightData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHeightData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHeightData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHeightData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthHeightData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupHeightData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthHeightData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthHeightData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowHeightData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupHeightData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/data/base/heightData.proto b/schema/data/base/heightData.proto deleted file mode 100644 index 506439754..000000000 --- a/schema/data/base/heightData.proto +++ /dev/null @@ -1,6 +0,0 @@ -syntax = "proto3"; -package base; - -message HeightData{ - int64 value = 1; -} \ No newline at end of file diff --git a/schema/data/base/idData.go b/schema/data/base/idData.go index a5552a950..129fe5484 100644 --- a/schema/data/base/idData.go +++ b/schema/data/base/idData.go @@ -8,57 +8,63 @@ import ( "github.com/AssetMantle/modules/schema/data" dataConstants "github.com/AssetMantle/modules/schema/data/constants" + "github.com/AssetMantle/modules/schema/errors/constants" "github.com/AssetMantle/modules/schema/ids" baseIDs "github.com/AssetMantle/modules/schema/ids/base" "github.com/AssetMantle/modules/schema/traits" ) -var _ data.IDData = (*Data_IdData)(nil) - -func (idData *Data_IdData) Unmarshal(bytes []byte) error { - // TODO implement me - panic("implement me") +type idData struct { + Value ids.ID `json:"value"` } -func (idData *Data_IdData) GetID() ids.ID { - return baseIDs.GenerateDataID(idData) + +var _ data.IDData = (*idData)(nil) + +func (idData idData) GetID() ids.DataID { + return baseIDs.NewDataID(idData) } -func (idData *Data_IdData) Compare(listable traits.Listable) int { - compareIDData, err := dataFromInterface(listable) +func (idData idData) Compare(listable traits.Listable) int { + compareIDData, err := idDataFromInterface(listable) if err != nil { panic(err) } - return bytes.Compare(idData.Bytes(), compareIDData.Bytes()) + return bytes.Compare(idData.Value.Bytes(), compareIDData.Value.Bytes()) } -func (idData *Data_IdData) String() string { - return idData.IdData.String() +func (idData idData) String() string { + return idData.Value.String() } -func (idData *Data_IdData) Bytes() []byte { - return idData.Bytes() +func (idData idData) Bytes() []byte { + return idData.Value.Bytes() } -func (idData *Data_IdData) GetType() ids.ID { +func (idData idData) GetType() ids.StringID { return dataConstants.IDDataID } -func (idData *Data_IdData) ZeroValue() data.Data { - return IDDataPrototype() +func (idData idData) ZeroValue() data.Data { + return NewIDData(baseIDs.NewStringID("")) } -func (idData *Data_IdData) GenerateHashID() ids.ID { +func (idData idData) GenerateHashID() ids.HashID { return baseIDs.GenerateHashID(idData.Bytes()) } -func (idData *Data_IdData) Get() ids.ID { - return idData.IdData.Value +func (idData idData) Get() ids.ID { + return idData.Value } -func IDDataPrototype() data.Data { - return NewIDData(baseIDs.NewStringID("")) +func idDataFromInterface(listable traits.Listable) (idData, error) { + switch value := listable.(type) { + case idData: + return value, nil + default: + return idData{}, constants.MetaDataError + } +} + +func IDDataPrototype() data.IDData { + return idData{}.ZeroValue().(data.IDData) } -func NewIDData(value ids.ID) data.Data { - return &Data{ - Impl: &Data_IdData{ - IdData: &IDData{ - Value: value.(*baseIDs.ID), - }, - }, +func NewIDData(value ids.ID) data.IDData { + return idData{ + Value: value, } } diff --git a/schema/data/base/idData.pb.go b/schema/data/base/idData.pb.go deleted file mode 100644 index 5aabef540..000000000 --- a/schema/data/base/idData.pb.go +++ /dev/null @@ -1,329 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/data/base/idData.proto - -package base - -import ( - fmt "fmt" - base "github.com/AssetMantle/modules/schema/ids/base" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type IDData struct { - Value *base.ID `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *IDData) Reset() { *m = IDData{} } -func (m *IDData) String() string { return proto.CompactTextString(m) } -func (*IDData) ProtoMessage() {} -func (*IDData) Descriptor() ([]byte, []int) { - return fileDescriptor_236bb2fd4767a5b7, []int{0} -} -func (m *IDData) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *IDData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_IDData.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *IDData) XXX_Merge(src proto.Message) { - xxx_messageInfo_IDData.Merge(m, src) -} -func (m *IDData) XXX_Size() int { - return m.Size() -} -func (m *IDData) XXX_DiscardUnknown() { - xxx_messageInfo_IDData.DiscardUnknown(m) -} - -var xxx_messageInfo_IDData proto.InternalMessageInfo - -func (m *IDData) GetValue() *base.ID { - if m != nil { - return m.Value - } - return nil -} - -func init() { - proto.RegisterType((*IDData)(nil), "base.IDData") -} - -func init() { proto.RegisterFile("schema/data/base/idData.proto", fileDescriptor_236bb2fd4767a5b7) } - -var fileDescriptor_236bb2fd4767a5b7 = []byte{ - // 226 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2d, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x4f, 0x49, 0x2c, 0x49, 0xd4, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x4c, 0x71, - 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x09, 0x49, 0x49, 0x40, - 0x15, 0x65, 0xa6, 0x14, 0xc3, 0xd4, 0x40, 0xe4, 0x95, 0xd4, 0xb9, 0xd8, 0x3c, 0x5d, 0x40, 0xea, - 0x85, 0x64, 0xb9, 0x58, 0xcb, 0x12, 0x73, 0x4a, 0x53, 0x25, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, - 0xd8, 0xf5, 0x32, 0x53, 0x8a, 0xf5, 0x3c, 0x5d, 0x82, 0x20, 0xa2, 0x4e, 0x13, 0x18, 0x4f, 0x3c, - 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, - 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x81, 0x8b, 0x23, 0x39, 0x3f, 0x57, 0x0f, 0x64, 0xac, - 0x13, 0xb7, 0x27, 0xd8, 0xee, 0x00, 0x90, 0xd1, 0x01, 0x8c, 0x51, 0xfa, 0xe9, 0x99, 0x25, 0x19, - 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x8e, 0xc5, 0xc5, 0xa9, 0x25, 0xbe, 0x89, 0x79, 0x25, - 0x39, 0xa9, 0xfa, 0xb9, 0xf9, 0x29, 0xa5, 0x39, 0xa9, 0xc5, 0xfa, 0xe8, 0x4e, 0x5f, 0xc4, 0xc4, - 0xec, 0x14, 0x11, 0xb1, 0x8a, 0x89, 0xc5, 0x29, 0xb1, 0x38, 0xf5, 0x14, 0x84, 0x7a, 0xc4, 0x24, - 0x00, 0xa2, 0x62, 0xdc, 0x03, 0x9c, 0x7c, 0x53, 0x4b, 0x12, 0x41, 0x6a, 0x5f, 0x41, 0x64, 0x92, - 0xd8, 0xc0, 0x5e, 0x30, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0xf5, 0xb4, 0x5b, 0xc5, 0x03, 0x01, - 0x00, 0x00, -} - -func (m *IDData) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *IDData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *IDData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Value != nil { - { - size, err := m.Value.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintIdData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintIdData(dAtA []byte, offset int, v uint64) int { - offset -= sovIdData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *IDData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Value != nil { - l = m.Value.Size() - n += 1 + l + sovIdData(uint64(l)) - } - return n -} - -func sovIdData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozIdData(x uint64) (n int) { - return sovIdData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *IDData) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIdData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: IDData: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: IDData: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIdData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthIdData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthIdData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Value == nil { - m.Value = &base.ID{} - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipIdData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthIdData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipIdData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthIdData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupIdData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthIdData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthIdData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowIdData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupIdData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/data/base/idData.proto b/schema/data/base/idData.proto deleted file mode 100644 index 61d49b58b..000000000 --- a/schema/data/base/idData.proto +++ /dev/null @@ -1,8 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/ids/base/id.proto"; - -message IDData { - ids.ID value = 1; -} \ No newline at end of file diff --git a/schema/data/base/listData_test.go b/schema/data/base/listData_test.go index ca8facca3..e93d25c25 100644 --- a/schema/data/base/listData_test.go +++ b/schema/data/base/listData_test.go @@ -61,7 +61,7 @@ func TestNewListData(t *testing.T) { {"+ve empty datalist", args{baseLists.NewDataList([]data.Data{}...)}, listData{}.ZeroValue()}, {"+ve address string", args{baseLists.NewDataList(NewStringData(fromAddress))}, listData{baseLists.NewDataList(NewStringData(fromAddress))}}, // TODO: Check address format - //{"-ve wrong address string format", args{baseLists.NewDataList(NewStringData(fromAddress))}, listData{}.ZeroValue()}, + // {"-ve wrong address string format", args{baseLists.NewDataList(NewStringData(fromAddress))}, listData{}.ZeroValue()}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/schema/data/base/stringData.go b/schema/data/base/stringData.go index 8bbdd93f3..3fad6e21f 100644 --- a/schema/data/base/stringData.go +++ b/schema/data/base/stringData.go @@ -4,61 +4,67 @@ package base import ( - "bytes" + "strings" "github.com/AssetMantle/modules/schema/data" dataConstants "github.com/AssetMantle/modules/schema/data/constants" + "github.com/AssetMantle/modules/schema/errors/constants" "github.com/AssetMantle/modules/schema/ids" baseIDs "github.com/AssetMantle/modules/schema/ids/base" "github.com/AssetMantle/modules/schema/traits" ) -var _ data.StringData = (*Data_StringData)(nil) - -func (stringData *Data_StringData) Unmarshal(bytes []byte) error { - // TODO implement me - panic("implement me") +type stringData struct { + Value string `json:"value"` } -func (stringData *Data_StringData) GetID() ids.ID { - return baseIDs.GenerateDataID(stringData) + +var _ data.StringData = (*stringData)(nil) + +func (stringData stringData) GetID() ids.DataID { + return baseIDs.NewDataID(stringData) } -func (stringData *Data_StringData) Compare(listable traits.Listable) int { - compareStringData, err := dataFromInterface(listable) +func (stringData stringData) Compare(listable traits.Listable) int { + compareStringData, err := stringDataFromInterface(listable) if err != nil { panic(err) } - return bytes.Compare(stringData.Bytes(), compareStringData.Bytes()) + return strings.Compare(stringData.Value, compareStringData.Value) } -func (stringData *Data_StringData) String() string { - return stringData.StringData.String() +func (stringData stringData) String() string { + return stringData.Value } -func (stringData *Data_StringData) Bytes() []byte { - return []byte(stringData.String()) +func (stringData stringData) Bytes() []byte { + return []byte(stringData.Value) } -func (stringData *Data_StringData) GetType() ids.ID { +func (stringData stringData) GetType() ids.StringID { return dataConstants.StringDataID } -func (stringData *Data_StringData) ZeroValue() data.Data { +func (stringData stringData) ZeroValue() data.Data { return NewStringData("") } -func (stringData *Data_StringData) GenerateHashID() ids.ID { +func (stringData stringData) GenerateHashID() ids.HashID { return baseIDs.GenerateHashID(stringData.Bytes()) } -func (stringData *Data_StringData) Get() string { - return stringData.StringData.Value +func (stringData stringData) Get() string { + return stringData.Value } -func StringDataPrototype() data.Data { - return NewStringData("") +func stringDataFromInterface(listable traits.Listable) (stringData, error) { + switch value := listable.(type) { + case stringData: + return value, nil + default: + return stringData{}, constants.MetaDataError + } +} + +func StringDataPrototype() data.StringData { + return stringData{}.ZeroValue().(data.StringData) } -func NewStringData(value string) data.Data { - return &Data{ - Impl: &Data_StringData{ - StringData: &StringData{ - Value: value, - }, - }, +func NewStringData(value string) data.StringData { + return stringData{ + Value: value, } } diff --git a/schema/data/base/stringData.pb.go b/schema/data/base/stringData.pb.go deleted file mode 100644 index 75c4d1061..000000000 --- a/schema/data/base/stringData.pb.go +++ /dev/null @@ -1,317 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/data/base/stringData.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type StringData struct { - Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *StringData) Reset() { *m = StringData{} } -func (m *StringData) String() string { return proto.CompactTextString(m) } -func (*StringData) ProtoMessage() {} -func (*StringData) Descriptor() ([]byte, []int) { - return fileDescriptor_7649f0b4a236d0fc, []int{0} -} -func (m *StringData) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *StringData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_StringData.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *StringData) XXX_Merge(src proto.Message) { - xxx_messageInfo_StringData.Merge(m, src) -} -func (m *StringData) XXX_Size() int { - return m.Size() -} -func (m *StringData) XXX_DiscardUnknown() { - xxx_messageInfo_StringData.DiscardUnknown(m) -} - -var xxx_messageInfo_StringData proto.InternalMessageInfo - -func (m *StringData) GetValue() string { - if m != nil { - return m.Value - } - return "" -} - -func init() { - proto.RegisterType((*StringData)(nil), "base.StringData") -} - -func init() { proto.RegisterFile("schema/data/base/stringData.proto", fileDescriptor_7649f0b4a236d0fc) } - -var fileDescriptor_7649f0b4a236d0fc = []byte{ - // 208 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2c, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x4f, 0x49, 0x2c, 0x49, 0xd4, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x2f, 0x2e, 0x29, - 0xca, 0xcc, 0x4b, 0x77, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, - 0x09, 0x2b, 0x29, 0x71, 0x71, 0x05, 0xc3, 0x65, 0x84, 0x44, 0xb8, 0x58, 0xcb, 0x12, 0x73, 0x4a, - 0x53, 0x25, 0x18, 0x15, 0x18, 0x35, 0x38, 0x83, 0x20, 0x1c, 0xa7, 0x29, 0x8c, 0x27, 0x1e, 0xc9, - 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, - 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0xc0, 0xc5, 0x91, 0x9c, 0x9f, 0xab, 0x07, 0x32, 0xc8, 0x89, - 0x1f, 0x61, 0x4c, 0x00, 0xc8, 0xfc, 0x00, 0xc6, 0x28, 0xfd, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, - 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0xc7, 0xe2, 0xe2, 0xd4, 0x12, 0xdf, 0xc4, 0xbc, 0x92, 0x9c, 0x54, - 0xfd, 0xdc, 0xfc, 0x94, 0xd2, 0x9c, 0xd4, 0x62, 0x7d, 0x74, 0x37, 0x2e, 0x62, 0x62, 0x76, 0x8a, - 0x88, 0x58, 0xc5, 0xc4, 0xe2, 0x94, 0x58, 0x9c, 0x7a, 0x0a, 0x42, 0x3d, 0x62, 0x12, 0x00, 0x51, - 0x31, 0xee, 0x01, 0x4e, 0xbe, 0xa9, 0x25, 0x89, 0x20, 0xb5, 0xaf, 0x20, 0x32, 0x49, 0x6c, 0x60, - 0x7f, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x99, 0xb5, 0x0a, 0x4c, 0xec, 0x00, 0x00, 0x00, -} - -func (m *StringData) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *StringData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *StringData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - i -= len(m.Value) - copy(dAtA[i:], m.Value) - i = encodeVarintStringData(dAtA, i, uint64(len(m.Value))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintStringData(dAtA []byte, offset int, v uint64) int { - offset -= sovStringData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *StringData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Value) - if l > 0 { - n += 1 + l + sovStringData(uint64(l)) - } - return n -} - -func sovStringData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozStringData(x uint64) (n int) { - return sovStringData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *StringData) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStringData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: StringData: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: StringData: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStringData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthStringData - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStringData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipStringData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthStringData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipStringData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStringData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStringData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStringData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthStringData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupStringData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthStringData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthStringData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowStringData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupStringData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/data/base/stringData.proto b/schema/data/base/stringData.proto deleted file mode 100644 index 338382734..000000000 --- a/schema/data/base/stringData.proto +++ /dev/null @@ -1,6 +0,0 @@ -syntax = "proto3"; -package base; - -message StringData{ - string value = 1; -} \ No newline at end of file diff --git a/schema/data/codec.go b/schema/data/codec.go index ad6f2c366..66d4292f2 100644 --- a/schema/data/codec.go +++ b/schema/data/codec.go @@ -7,7 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { +func RegisterCodec(codec *codec.Codec) { codec.RegisterInterface((*AccAddressData)(nil), nil) codec.RegisterInterface((*BooleanData)(nil), nil) codec.RegisterInterface((*Data)(nil), nil) diff --git a/schema/data/codec_test.go b/schema/data/codec_test.go new file mode 100644 index 000000000..eb06e7190 --- /dev/null +++ b/schema/data/codec_test.go @@ -0,0 +1,29 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package data + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + // var Codec = codec.New() + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + + {"+ve Codec", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/data/data.go b/schema/data/data.go index 6e0aa917b..efcc46e6c 100644 --- a/schema/data/data.go +++ b/schema/data/data.go @@ -8,21 +8,18 @@ import ( "github.com/AssetMantle/modules/schema/traits" ) -// TODO URI and PropertyID data type +// TODO URI and ID data type type Data interface { - GetID() ids.ID + GetID() ids.DataID - Size() int - Unmarshal([]byte) error - MarshalTo([]byte) (int, error) String() string Bytes() []byte - GetType() ids.ID + GetType() ids.StringID ZeroValue() Data - // GenerateHash returns the hash of the Data as an PropertyID - // * Returns PropertyID of empty bytes when the value of Data is that Data type's zero value - GenerateHashID() ids.ID + // GenerateHash returns the hash of the Data as an ID + // * Returns ID of empty bytes when the value of Data is that Data type's zero value + GenerateHashID() ids.HashID traits.Listable } diff --git a/schema/data/utilities/string.go b/schema/data/utilities/string.go index 165b36115..24b8a9d1c 100644 --- a/schema/data/utilities/string.go +++ b/schema/data/utilities/string.go @@ -11,10 +11,12 @@ import ( dataConstants "github.com/AssetMantle/modules/schema/data/constants" errorConstants "github.com/AssetMantle/modules/schema/errors/constants" baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" baseTypes "github.com/AssetMantle/modules/schema/types/base" + stringUtilities "github.com/AssetMantle/modules/utilities/string" ) -func readAccAddressData(dataString string) (data.Data, error) { +func readAccAddressData(dataString string) (data.AccAddressData, error) { if dataString == "" { return base.AccAddressDataPrototype(), nil } @@ -26,7 +28,7 @@ func readAccAddressData(dataString string) (data.Data, error) { return base.NewAccAddressData(accAddress), nil } -func readBooleanData(dataString string) (data.Data, error) { +func readBooleanData(dataString string) (data.BooleanData, error) { if dataString == "" { return base.BooleanDataPrototype(), nil } @@ -38,7 +40,7 @@ func readBooleanData(dataString string) (data.Data, error) { return base.NewBooleanData(Bool), nil } -func readDecData(dataString string) (data.Data, error) { +func readDecData(dataString string) (data.DecData, error) { if dataString == "" { return base.DecDataPrototype(), nil } @@ -50,7 +52,7 @@ func readDecData(dataString string) (data.Data, error) { return base.NewDecData(dec), nil } -func readHeightData(dataString string) (data.Data, error) { +func readHeightData(dataString string) (data.HeightData, error) { if dataString == "" { return base.HeightDataPrototype(), nil } @@ -63,16 +65,34 @@ func readHeightData(dataString string) (data.Data, error) { return base.NewHeightData(baseTypes.NewHeight(height)), nil } -// TODO read complex IDs than string PropertyID -func readIDData(dataString string) (data.Data, error) { +// TODO read complex IDs than string ID +func readIDData(dataString string) (data.IDData, error) { if dataString == "" { return base.IDDataPrototype(), nil } return base.NewIDData(baseIDs.NewStringID(dataString)), nil } +func readListData(dataString string) (data.ListData, error) { + if dataString == "" { + return base.ListDataPrototype(), nil + } + + dataStringList := stringUtilities.SplitListString(dataString) + dataList := make([]data.Data, len(dataStringList)) -func readStringData(dataString string) (data.Data, error) { + for i, datumString := range dataStringList { + Data, err := ReadData(datumString) + if err != nil { + return base.ListDataPrototype(), err + } + + dataList[i] = Data + } + + return base.NewListData(baseLists.NewDataList(dataList...)), nil +} +func readStringData(dataString string) (data.StringData, error) { if dataString == "" { return base.StringDataPrototype(), nil } @@ -98,18 +118,20 @@ func ReadData(dataString string) (data.Data, error) { var err error - switch baseIDs.NewStringID(dataTypeString).String() { - case dataConstants.AccAddressDataID.String(): + switch baseIDs.NewStringID(dataTypeString) { + case dataConstants.AccAddressDataID: Data, err = readAccAddressData(dataValueString) - case dataConstants.BooleanDataID.String(): + case dataConstants.BooleanDataID: Data, err = readBooleanData(dataValueString) - case dataConstants.DecDataID.String(): + case dataConstants.DecDataID: Data, err = readDecData(dataValueString) - case dataConstants.HeightDataID.String(): + case dataConstants.HeightDataID: Data, err = readHeightData(dataValueString) - case dataConstants.IDDataID.String(): + case dataConstants.IDDataID: Data, err = readIDData(dataValueString) - case dataConstants.StringDataID.String(): + case dataConstants.ListDataID: + Data, err = readListData(dataValueString) + case dataConstants.StringDataID: Data, err = readStringData(dataValueString) default: Data, err = nil, errorConstants.UnsupportedParameter diff --git a/schema/documents/asset.go b/schema/documents/asset.go new file mode 100644 index 000000000..9c0dbeb90 --- /dev/null +++ b/schema/documents/asset.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package documents + +import ( + "github.com/AssetMantle/modules/schema/capabilities" +) + +type Asset interface { + capabilities.Burnable + capabilities.Lockable + capabilities.Splittable + + Document +} diff --git a/schema/documents/base/asset.go b/schema/documents/base/asset.go new file mode 100644 index 000000000..5e8f5d607 --- /dev/null +++ b/schema/documents/base/asset.go @@ -0,0 +1,43 @@ +package base + +import ( + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/properties" + "github.com/AssetMantle/modules/schema/properties/constants" + "github.com/AssetMantle/modules/schema/qualified" +) + +type asset struct { + documents.Document +} + +var _ documents.Asset = (*asset)(nil) + +func (asset asset) GetBurn() properties.Property { + if burn := asset.GetProperty(constants.BurnHeightProperty.GetID()); burn != nil { + return burn + } + + return constants.BurnHeightProperty +} +func (asset asset) GetLock() properties.Property { + if lock := asset.GetProperty(constants.LockProperty.GetID()); lock != nil { + return lock + } + + return constants.LockProperty +} +func (asset asset) GetSupply() properties.Property { + if supply := asset.GetProperty(constants.SupplyProperty.GetID()); supply != nil { + return supply + } + + return constants.SupplyProperty +} + +func NewAsset(classificationID ids.ClassificationID, immutables qualified.Immutables, mutables qualified.Mutables) documents.Asset { + return asset{ + Document: NewDocument(classificationID, immutables, mutables), + } +} diff --git a/schema/documents/base/classification.go b/schema/documents/base/classification.go new file mode 100644 index 000000000..29cdc196a --- /dev/null +++ b/schema/documents/base/classification.go @@ -0,0 +1,19 @@ +package base + +import ( + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/qualified" +) + +type classification struct { + documents.Document +} + +var _ documents.Classification = (*classification)(nil) + +func NewClassification(immutables qualified.Immutables, mutables qualified.Mutables) documents.Classification { + return classification{ + Document: NewDocument(base.NewClassificationID(immutables, mutables), immutables, mutables), + } +} diff --git a/schema/documents/base/classification_test.go b/schema/documents/base/classification_test.go new file mode 100644 index 000000000..cc1253659 --- /dev/null +++ b/schema/documents/base/classification_test.go @@ -0,0 +1,49 @@ +package base + +import ( + "reflect" + "testing" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/qualified" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +func Test_new_Classification(t *testing.T) { + immutables := baseQualified.NewImmutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID1"), baseData.NewStringData("ImmutableData")))) + mutables := baseQualified.NewMutables(baseLists.NewPropertyList(baseProperties.NewMesaProperty(baseIDs.NewStringID("ID2"), baseData.NewStringData("MutableData")))) + + testClassification := NewClassification(immutables, mutables) + type fields struct { + immutables qualified.Immutables + mutables qualified.Mutables + } + tests := []struct { + name string + fields fields + want documents.Classification + wantError bool + }{ + {"+ve", fields{immutables, mutables}, testClassification, false}, + {"nil immutables", fields{nil, mutables}, testClassification, true}, + {"nil mutables", fields{immutables, nil}, testClassification, true}, + {"nil", fields{nil, nil}, testClassification, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + defer func() { + r := recover() + if (r != nil) != tt.wantError { + t.Errorf("lol") + } + }() + if got := NewClassification(tt.fields.immutables, tt.fields.mutables); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewClassification() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/schema/documents/base/codec.go b/schema/documents/base/codec.go new file mode 100644 index 000000000..8cd273e87 --- /dev/null +++ b/schema/documents/base/codec.go @@ -0,0 +1,19 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +func RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, asset{}) + codecUtilities.RegisterModuleConcrete(codec, classification{}) + codecUtilities.RegisterModuleConcrete(codec, document{}) + codecUtilities.RegisterModuleConcrete(codec, identity{}) + codecUtilities.RegisterModuleConcrete(codec, maintainer{}) + codecUtilities.RegisterModuleConcrete(codec, order{}) +} diff --git a/schema/documents/base/document.go b/schema/documents/base/document.go new file mode 100644 index 000000000..01676e223 --- /dev/null +++ b/schema/documents/base/document.go @@ -0,0 +1,56 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/properties" + "github.com/AssetMantle/modules/schema/qualified" +) + +type document struct { + ids.ClassificationID + qualified.Immutables + qualified.Mutables +} + +var _ documents.Document = (*document)(nil) + +func (document document) GenerateHashID() ids.HashID { + return base.GenerateHashID(document.GetClassificationID().Bytes(), document.GetImmutables().GenerateHashID().Bytes()) +} +func (document document) GetClassificationID() ids.ClassificationID { + return document.ClassificationID +} +func (document document) GetProperty(propertyID ids.PropertyID) properties.Property { + if property := document.Immutables.GetImmutablePropertyList().GetProperty(propertyID); property != nil { + return property + } else if property := document.Mutables.GetMutablePropertyList().GetProperty(propertyID); property != nil { + return property + } else { + return nil + } +} +func (document document) GetImmutables() qualified.Immutables { + return document.Immutables +} +func (document document) GetMutables() qualified.Mutables { + return document.Mutables +} + +// TODO write test case +func (document document) Mutate(propertyList ...properties.Property) documents.Document { + document.Mutables = document.Mutables.Mutate(propertyList...) + return document +} + +func NewDocument(classificationID ids.ClassificationID, immutables qualified.Immutables, mutables qualified.Mutables) documents.Document { + return document{ + ClassificationID: classificationID, + Immutables: immutables, + Mutables: mutables, + } +} diff --git a/schema/documents/base/documents.go b/schema/documents/base/documents.go deleted file mode 100644 index 79ee8f99f..000000000 --- a/schema/documents/base/documents.go +++ /dev/null @@ -1,35 +0,0 @@ -package base - -// -//import ( -// "github.com/AssetMantle/modules/schema/documents" -// "github.com/AssetMantle/modules/schema/ids" -// "github.com/AssetMantle/modules/schema/properties" -// "github.com/AssetMantle/modules/schema/qualified" -//) -// -//var _ documents.Document = (*Documents)(nil) -// -//func (x *Documents) GenerateHashID() ids.HashID { -// return x.Impl.(documents.Document).GenerateHashID() -//} -// -//func (x *Documents) GetClassificationID() ids.ClassificationID { -// return x.Impl.(documents.Document).GetClassificationID() -//} -// -//func (x *Documents) GetProperty(id ids.PropertyID) properties.Property { -// return x.Impl.(documents.Document).GetProperty(id) -//} -// -//func (x *Documents) GetImmutables() qualified.Immutables { -// return x.Impl.(documents.Document).GetImmutables() -//} -// -//func (x *Documents) GetMutables() qualified.Mutables { -// return x.Impl.(documents.Document).GetMutables() -//} -// -//func (x *Documents) Mutate(property ...properties.Property) documents.Document { -// return x.Impl.(documents.Document).Mutate(property...) -//} diff --git a/schema/documents/base/documents.pb.go b/schema/documents/base/documents.pb.go deleted file mode 100644 index b63832ad0..000000000 --- a/schema/documents/base/documents.pb.go +++ /dev/null @@ -1,41 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/documents/base/documents.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -func init() { - proto.RegisterFile("schema/documents/base/documents.proto", fileDescriptor_c7dc52f0bc20c3a7) -} - -var fileDescriptor_c7dc52f0bc20c3a7 = []byte{ - // 181 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2d, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x4f, 0xc9, 0x4f, 0x2e, 0xcd, 0x4d, 0xcd, 0x2b, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, - 0x4e, 0x45, 0x70, 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x58, 0x40, 0xa2, 0x4e, 0x33, 0x18, - 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, - 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x81, 0x8b, 0x23, 0x39, 0x3f, 0x57, 0x0f, - 0xac, 0x88, 0xcf, 0x05, 0xa6, 0x37, 0x00, 0xa4, 0x35, 0x80, 0x31, 0xca, 0x24, 0x3d, 0xb3, 0x24, - 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0xdf, 0xb1, 0xb8, 0x38, 0xb5, 0xc4, 0x37, 0x31, 0xaf, - 0x24, 0x27, 0x55, 0x3f, 0x37, 0x3f, 0xa5, 0x34, 0x27, 0xb5, 0x58, 0x1f, 0xab, 0x13, 0x16, 0x31, - 0x31, 0x3b, 0x45, 0x44, 0xac, 0x62, 0x62, 0x71, 0x4a, 0x2c, 0x4e, 0x3d, 0x05, 0xa1, 0x1e, 0x31, - 0x09, 0x80, 0xa8, 0x18, 0xf7, 0x00, 0x27, 0xdf, 0xd4, 0x92, 0xc4, 0x94, 0xc4, 0x92, 0xc4, 0x57, - 0x10, 0x99, 0x24, 0x36, 0xb0, 0x3b, 0x8d, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x17, 0x66, 0xbe, - 0x4e, 0xd0, 0x00, 0x00, 0x00, -} diff --git a/schema/documents/base/documents.proto b/schema/documents/base/documents.proto deleted file mode 100644 index dfec5bad0..000000000 --- a/schema/documents/base/documents.proto +++ /dev/null @@ -1,19 +0,0 @@ -syntax = "proto3"; -package base; -// -//import "schema/documents/base/document.proto"; -//import "schema/documents/base/asset.proto"; -//import "schema/documents/base/classification.proto"; -//import "schema/documents/base/identity.proto"; -//import "schema/documents/base/maintainer.proto"; -// -// -//message Documents { -// oneof impl { -// Asset asset = 1; -// Classification classification = 2; -// Document document = 3; -// Identity identity = 4; -// Maintainer maintainer = 5; -// } -//} \ No newline at end of file diff --git a/schema/documents/base/identity.go b/schema/documents/base/identity.go new file mode 100644 index 000000000..eff7ea1dd --- /dev/null +++ b/schema/documents/base/identity.go @@ -0,0 +1,61 @@ +package base + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/data" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/properties/constants" + "github.com/AssetMantle/modules/schema/qualified" + "github.com/AssetMantle/modules/schema/types" +) + +type identity struct { + documents.Document +} + +var _ documents.Identity = (*identity)(nil) + +func (identity identity) GetExpiry() types.Height { + if property := identity.Document.GetProperty(constants.ExpiryHeightProperty.GetID()); property != nil && property.IsMeta() { + return property.(properties.MetaProperty).GetData().(data.HeightData).Get() + } + + return constants.ExpiryHeightProperty.GetData().(data.HeightData).Get() +} +func (identity identity) GetAuthentication() lists.DataList { + if property := identity.Document.GetProperty(constants.AuthenticationProperty.GetID()); property != nil && property.IsMeta() { + return base.NewDataList(property.(properties.MetaProperty).GetData().(data.ListData).Get()...) + } + + return base.NewDataList(constants.AuthenticationProperty.GetData().(data.ListData).Get()...) +} +func (identity identity) IsProvisioned(accAddress sdkTypes.AccAddress) bool { + _, isProvisioned := identity.GetAuthentication().Search(baseData.NewAccAddressData(accAddress)) + return isProvisioned +} +func (identity identity) ProvisionAddress(accAddresses ...sdkTypes.AccAddress) documents.Identity { + identity.Document = identity.Document.Mutate(baseProperties.NewMetaProperty(constants.AuthenticationProperty.GetKey(), baseData.NewListData(identity.GetAuthentication().Add(accAddressesToData(accAddresses...)...)))) + return identity +} +func (identity identity) UnprovisionAddress(accAddresses ...sdkTypes.AccAddress) documents.Identity { + identity.Document = identity.Document.Mutate(baseProperties.NewMetaProperty(constants.AuthenticationProperty.GetKey(), baseData.NewListData(identity.GetAuthentication().Remove(accAddressesToData(accAddresses...)...)))) + return identity +} +func accAddressesToData(accAddresses ...sdkTypes.AccAddress) []data.Data { + accAddressData := make([]data.Data, len(accAddresses)) + for i, accAddress := range accAddresses { + accAddressData[i] = baseData.NewAccAddressData(accAddress) + } + return accAddressData +} + +func NewIdentity(classificationID ids.ClassificationID, immutables qualified.Immutables, mutables qualified.Mutables) documents.Identity { + return identity{Document: NewDocument(classificationID, immutables, mutables)} +} diff --git a/schema/documents/base/identity_test.go b/schema/documents/base/identity_test.go new file mode 100644 index 000000000..4a5879fb6 --- /dev/null +++ b/schema/documents/base/identity_test.go @@ -0,0 +1,223 @@ +package base + +import ( + "fmt" + "reflect" + "testing" + + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/properties/constants" + "github.com/AssetMantle/modules/schema/qualified" + "github.com/AssetMantle/modules/schema/types" +) + +func TestNewIdentity(t *testing.T) { + classificationID, immutables, mutables, testDocument := createTestInput() + testIdentity := identity{testDocument} + type args struct { + classificationID ids.ClassificationID + immutables qualified.Immutables + mutables qualified.Mutables + } + tests := []struct { + name string + args args + want documents.Identity + }{ + {"+ve", args{classificationID, immutables, mutables}, testIdentity}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewIdentity(tt.args.classificationID, tt.args.immutables, tt.args.mutables); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewIdentity() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_identity_IsProvisioned(t *testing.T) { + classificationID, immutables, mutables, _ := createTestInput() + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + fromAccAddress2, err := sdkTypes.AccAddressFromBech32("cosmos1u6xn6rv07p2yzzj2rm8st04x54xe5ur0t9nl5j") + require.Nil(t, err) + testIdentity := NewIdentity(classificationID, immutables, mutables) + testIdentity.ProvisionAddress(fromAccAddress) + + type fields struct { + Document documents.Identity + } + type args struct { + accAddress sdkTypes.AccAddress + } + tests := []struct { + name string + fields fields + args args + want bool + }{ + {"+ve", fields{testIdentity}, args{fromAccAddress}, true}, + {"-ve", fields{testIdentity}, args{fromAccAddress2}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + identity := tt.fields.Document + if got := identity.IsProvisioned(tt.args.accAddress); got != tt.want { + t.Errorf("IsProvisioned() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_identity_GetExpiry(t *testing.T) { + _, _, _, testDocument := createTestInput() + testIdentity := identity{testDocument} + type fields struct { + Document documents.Identity + } + tests := []struct { + name string + fields fields + want types.Height + }{ + {"+ve", fields{testIdentity}, constants.ExpiryHeightProperty.GetData().(data.HeightData).Get()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + identity := tt.fields.Document + + if got := identity.GetExpiry(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetExpiry() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_identity_ProvisionAddress(t *testing.T) { + classificationID, immutables, mutables, testDocument := createTestInput() + testIdentity := identity{testDocument} + testIdentity2 := testIdentity + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + fromAccAddress2, err := sdkTypes.AccAddressFromBech32("cosmos1u6xn6rv07p2yzzj2rm8st04x54xe5ur0t9nl5j") + require.Nil(t, err) + testIdentity.Document = testIdentity.Document.Mutate(baseProperties.NewMetaProperty(constants.AuthenticationProperty.GetKey(), base.NewListData(testIdentity.GetAuthentication().Add(accAddressesToData([]sdkTypes.AccAddress{fromAccAddress}...)...)))) + fmt.Println("TEST: ", testIdentity.IsProvisioned(fromAccAddress)) + type fields struct { + Document documents.Identity + } + type args struct { + accAddresses []sdkTypes.AccAddress + } + tests := []struct { + name string + fields fields + args args + want bool + }{ + {"+ve", fields{identity{NewDocument(classificationID, immutables, mutables)}}, args{[]sdkTypes.AccAddress{fromAccAddress}}, testIdentity.IsProvisioned(fromAccAddress)}, + {"+ve", fields{identity{NewDocument(classificationID, immutables, mutables)}}, args{[]sdkTypes.AccAddress{fromAccAddress2}}, testIdentity2.IsProvisioned(fromAccAddress)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + identity := identity{ + Document: tt.fields.Document, + } + if got := identity.ProvisionAddress(tt.args.accAddresses...).IsProvisioned(tt.args.accAddresses[0]); !reflect.DeepEqual(got, tt.want) { + t.Errorf("ProvisionAddress() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_identity_GetAuthentication(t *testing.T) { + classificationID, immutables, mutables, _ := createTestInput() + + type fields struct { + Document documents.Identity + } + + tests := []struct { + name string + fields fields + want lists.DataList + }{ + {"+ve", fields{identity{NewDocument(classificationID, immutables, mutables)}}, baseLists.NewDataList(constants.AuthenticationProperty.GetData().(data.ListData).Get()...)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + identity := identity{ + tt.fields.Document, + } + + if got := identity.GetAuthentication(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetAuthentication() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_accAddressesToData(t *testing.T) { + type args struct { + accAddresses []sdkTypes.AccAddress + } + tests := []struct { + name string + args args + want []data.Data + }{ + // {"+ve", args{}, }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := accAddressesToData(tt.args.accAddresses...); !reflect.DeepEqual(got, tt.want) { + t.Errorf("accAddressesToData() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_identity_UnprovisionAddress(t *testing.T) { + classificationID, immutables, mutables, testDocument := createTestInput() + testIdentity := identity{testDocument} + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + type fields struct { + Document documents.Identity + } + type args struct { + accAddresses []sdkTypes.AccAddress + } + tests := []struct { + name string + fields fields + args args + want documents.Identity + }{ + // TODO: panic: MetaDataError fix it after + // https://github.com/AssetMantle/modules/issues/59 + {"+ve", fields{identity{NewDocument(classificationID, immutables, mutables)}}, args{[]sdkTypes.AccAddress{fromAccAddress}}, testIdentity}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + identity := identity{ + Document: tt.fields.Document, + } + if got := identity.UnprovisionAddress(tt.args.accAddresses...); !reflect.DeepEqual(got, tt.want) { + t.Errorf("UnprovisionAddress() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/schema/documents/base/maintainer.go b/schema/documents/base/maintainer.go new file mode 100644 index 000000000..27b3addb3 --- /dev/null +++ b/schema/documents/base/maintainer.go @@ -0,0 +1,100 @@ +package base + +import ( + "github.com/AssetMantle/modules/schema/data" + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/ids/constansts" + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" + constantProperties "github.com/AssetMantle/modules/schema/properties/constants" + baseQualified "github.com/AssetMantle/modules/schema/qualified/base" +) + +type maintainer struct { + documents.Document +} + +var _ documents.Maintainer = (*maintainer)(nil) + +func (maintainer maintainer) GetIdentityID() ids.IdentityID { + if property := maintainer.GetProperty(constantProperties.IdentityIDProperty.GetID()); property != nil && property.IsMeta() { + return property.(properties.MetaProperty).GetData().(data.IDData).Get().(ids.IdentityID) + } + return constantProperties.IdentityIDProperty.GetData().(data.IDData).Get().(ids.IdentityID) +} +func (maintainer maintainer) GetMaintainedClassificationID() ids.ClassificationID { + if property := maintainer.GetProperty(constantProperties.MaintainedClassificationIDProperty.GetID()); property != nil && property.IsMeta() { + return property.(properties.MetaProperty).GetData().(data.IDData).Get().(ids.ClassificationID) + } + return constantProperties.MaintainedClassificationIDProperty.GetData().(data.IDData).Get().(ids.ClassificationID) +} +func (maintainer maintainer) GetMaintainedProperties() data.ListData { + if property := maintainer.GetProperty(constantProperties.MaintainedPropertiesProperty.GetID()); property != nil && property.IsMeta() { + return property.(properties.MetaProperty).GetData().(data.ListData) + } + + return constantProperties.MaintainedPropertiesProperty.GetData().(data.ListData) +} +func (maintainer maintainer) GetPermissions() data.ListData { + if property := maintainer.GetProperty(constantProperties.PermissionsProperty.GetID()); property != nil && property.IsMeta() { + return property.(properties.MetaProperty).GetData().(data.ListData) + } + + return constantProperties.PermissionsProperty.GetData().(data.ListData) +} +func (maintainer maintainer) CanMintAsset() bool { + _, can := maintainer.GetPermissions().Search(baseData.NewIDData(constansts.Mint)) + return can +} +func (maintainer maintainer) CanBurnAsset() bool { + _, can := maintainer.GetPermissions().Search(baseData.NewIDData(constansts.Burn)) + return can +} +func (maintainer maintainer) CanRenumerateAsset() bool { + _, can := maintainer.GetPermissions().Search(baseData.NewIDData(constansts.Renumerate)) + return can +} +func (maintainer maintainer) CanAddMaintainer() bool { + _, can := maintainer.GetPermissions().Search(baseData.NewIDData(constansts.Add)) + return can +} +func (maintainer maintainer) CanRemoveMaintainer() bool { + _, can := maintainer.GetPermissions().Search(baseData.NewIDData(constansts.Remove)) + return can +} +func (maintainer maintainer) CanMutateMaintainer() bool { + _, can := maintainer.GetPermissions().Search(baseData.NewIDData(constansts.Mutate)) + return can +} +func (maintainer maintainer) MaintainsProperty(propertyID ids.PropertyID) bool { + _, found := maintainer.GetMaintainedProperties().Search(baseData.NewIDData(propertyID)) + return found +} + +// TODO: Move to a common package +func idListToDataList(idList lists.IDList) lists.DataList { + dataList := baseLists.NewDataList() + for _, id := range idList.GetList() { + dataList = dataList.Add(baseData.NewIDData(id)) + } + return dataList +} + +func NewMaintainer(identityID ids.IdentityID, maintainedClassificationID ids.ClassificationID, maintainedPropertyIDList lists.IDList, permissions lists.IDList) documents.Maintainer { + return maintainer{ + Document: NewDocument(constansts.MaintainerClassificationID, + baseQualified.NewImmutables(baseLists.NewPropertyList( + baseProperties.NewMetaProperty(constantProperties.IdentityIDProperty.GetKey(), baseData.NewIDData(identityID)), + baseProperties.NewMetaProperty(constantProperties.MaintainedClassificationIDProperty.GetKey(), baseData.NewIDData(maintainedClassificationID)), + )), + baseQualified.NewMutables(baseLists.NewPropertyList( + baseProperties.NewMetaProperty(constantProperties.MaintainedPropertiesProperty.GetKey(), baseData.NewListData(idListToDataList(maintainedPropertyIDList))), + baseProperties.NewMetaProperty(constantProperties.PermissionsProperty.GetKey(), baseData.NewListData(idListToDataList(permissions))), + )), + ), + } +} diff --git a/schema/documents/base/order.go b/schema/documents/base/order.go new file mode 100644 index 000000000..cf5c9849d --- /dev/null +++ b/schema/documents/base/order.go @@ -0,0 +1,72 @@ +package base + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/documents" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/properties" + "github.com/AssetMantle/modules/schema/properties/constants" + "github.com/AssetMantle/modules/schema/qualified" + "github.com/AssetMantle/modules/schema/types" +) + +type order struct { + documents.Document +} + +var _ documents.Order = (*order)(nil) + +func (order order) GetExchangeRate() sdkTypes.Dec { + if property := order.GetProperty(constants.ExchangeRateProperty.GetID()); property != nil && property.IsMeta() { + return property.(properties.MetaProperty).GetData().(data.DecData).Get() + } + return constants.ExchangeRateProperty.GetData().(data.DecData).Get() +} +func (order order) GetCreationHeight() types.Height { + if property := order.GetProperty(constants.CreationHeightProperty.GetID()); property != nil && property.IsMeta() { + return property.(properties.MetaProperty).GetData().(data.HeightData).Get() + } + return constants.CreationHeightProperty.GetData().(data.HeightData).Get() +} +func (order order) GetMakerOwnableID() ids.OwnableID { + if property := order.GetProperty(constants.MakerOwnableIDProperty.GetID()); property != nil && property.IsMeta() { + return property.(properties.MetaProperty).GetData().(data.IDData).Get().(ids.OwnableID) + } + return constants.MakerOwnableIDProperty.GetData().(data.IDData).Get().(ids.OwnableID) +} +func (order order) GetTakerOwnableID() ids.OwnableID { + if property := order.GetProperty(constants.TakerOwnableIDProperty.GetID()); property != nil && property.IsMeta() { + return property.(properties.MetaProperty).GetData().(data.IDData).Get().(ids.OwnableID) + } + return constants.TakerOwnableIDProperty.GetData().(data.IDData).Get().(ids.OwnableID) +} +func (order order) GetMakerID() ids.IdentityID { + if property := order.GetProperty(constants.MakerIDProperty.GetID()); property != nil && property.IsMeta() { + return property.(properties.MetaProperty).GetData().(data.IDData).Get().(ids.IdentityID) + } + return constants.MakerIDProperty.GetData().(data.IDData).Get().(ids.IdentityID) +} +func (order order) GetTakerID() ids.IdentityID { + if property := order.GetProperty(constants.TakerIDProperty.GetID()); property != nil && property.IsMeta() { + return property.(properties.MetaProperty).GetData().(data.IDData).Get().(ids.IdentityID) + } + return constants.TakerIDProperty.GetData().(data.IDData).Get().(ids.IdentityID) +} +func (order order) GetExpiryHeight() types.Height { + if property := order.GetProperty(constants.ExpiryHeightProperty.GetID()); property != nil && property.IsMeta() { + return property.(properties.MetaProperty).GetData().(data.HeightData).Get() + } + return constants.ExpiryHeightProperty.GetData().(data.HeightData).Get() +} +func (order order) GetMakerOwnableSplit() sdkTypes.Dec { + if property := order.GetProperty(constants.MakerOwnableSplitProperty.GetID()); property != nil && property.IsMeta() { + return property.(properties.MetaProperty).GetData().(data.DecData).Get() + } + return constants.MakerOwnableSplitProperty.GetData().(data.DecData).Get() +} + +func NewOrder(classificationID ids.ClassificationID, immutables qualified.Immutables, mutables qualified.Mutables) documents.Order { + return order{Document: NewDocument(classificationID, immutables, mutables)} +} diff --git a/schema/documents/classification.go b/schema/documents/classification.go new file mode 100644 index 000000000..b499b20b9 --- /dev/null +++ b/schema/documents/classification.go @@ -0,0 +1,8 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package documents + +type Classification interface { + Document +} diff --git a/schema/documents/codec.go b/schema/documents/codec.go new file mode 100644 index 000000000..5c1367c8d --- /dev/null +++ b/schema/documents/codec.go @@ -0,0 +1,17 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package documents + +import ( + "github.com/cosmos/cosmos-sdk/codec" +) + +func RegisterCodec(codec *codec.Codec) { + codec.RegisterInterface((*Asset)(nil), nil) + codec.RegisterInterface((*Classification)(nil), nil) + codec.RegisterInterface((*Document)(nil), nil) + codec.RegisterInterface((*Identity)(nil), nil) + codec.RegisterInterface((*Maintainer)(nil), nil) + codec.RegisterInterface((*Order)(nil), nil) +} diff --git a/schema/documents/constants/classification.go b/schema/documents/constants/classification.go new file mode 100644 index 000000000..260ddcff7 --- /dev/null +++ b/schema/documents/constants/classification.go @@ -0,0 +1,10 @@ +package constants + +import ( + baseDocuments "github.com/AssetMantle/modules/schema/documents/base" + constantsQualified "github.com/AssetMantle/modules/schema/qualified/constants" +) + +var NubClassification = baseDocuments.NewClassification(constantsQualified.NubImmutables, constantsQualified.NubMutables) + +var MaintainerClassification = baseDocuments.NewClassification(constantsQualified.MaintainerImmutables, constantsQualified.MaintainerMutables) diff --git a/schema/documents/document.go b/schema/documents/document.go new file mode 100644 index 000000000..86447be1b --- /dev/null +++ b/schema/documents/document.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package documents + +import ( + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/properties" + "github.com/AssetMantle/modules/schema/qualified" +) + +type Document interface { + GenerateHashID() ids.HashID + GetClassificationID() ids.ClassificationID + // GetProperty returns property from a document searching in both Mutables and Immutables + // * Returns nil if property is not found + GetProperty(ids.PropertyID) properties.Property + GetImmutables() qualified.Immutables + GetMutables() qualified.Mutables + + Mutate(...properties.Property) Document +} diff --git a/schema/documents/identity.go b/schema/documents/identity.go new file mode 100644 index 000000000..27a15012d --- /dev/null +++ b/schema/documents/identity.go @@ -0,0 +1,29 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package documents + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/types" +) + +type Identity interface { + + // TODO removal for expired identity + // GetExpiry returns the expiry property of an Identity + // * If the property is not found, it returns a default value and not nil + GetExpiry() types.Height + + // GetAuthentication returns the authentication property of an Identity + // * If the property is not found, it returns a default value and not nil + GetAuthentication() lists.DataList + + IsProvisioned(sdkTypes.AccAddress) bool + ProvisionAddress(...sdkTypes.AccAddress) Identity + UnprovisionAddress(...sdkTypes.AccAddress) Identity + + Document +} diff --git a/schema/documents/maintainer.go b/schema/documents/maintainer.go new file mode 100644 index 000000000..3d9c5689a --- /dev/null +++ b/schema/documents/maintainer.go @@ -0,0 +1,26 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package documents + +import ( + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/ids" +) + +type Maintainer interface { + GetIdentityID() ids.IdentityID + GetMaintainedClassificationID() ids.ClassificationID + GetMaintainedProperties() data.ListData + GetPermissions() data.ListData + + CanMintAsset() bool + CanBurnAsset() bool + CanRenumerateAsset() bool + CanAddMaintainer() bool + CanRemoveMaintainer() bool + CanMutateMaintainer() bool + MaintainsProperty(ids.PropertyID) bool + + Document +} diff --git a/schema/documents/order.go b/schema/documents/order.go new file mode 100644 index 000000000..6d6c59cd3 --- /dev/null +++ b/schema/documents/order.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package documents + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/types" +) + +type Order interface { + GetExchangeRate() sdkTypes.Dec + GetCreationHeight() types.Height + GetMakerOwnableID() ids.OwnableID + GetTakerOwnableID() ids.OwnableID + GetMakerID() ids.IdentityID + GetTakerID() ids.IdentityID + GetExpiryHeight() types.Height + GetMakerOwnableSplit() sdkTypes.Dec + + Document +} diff --git a/schema/errors/base/codec.go b/schema/errors/base/codec.go new file mode 100644 index 000000000..ce1828c88 --- /dev/null +++ b/schema/errors/base/codec.go @@ -0,0 +1,9 @@ +package base + +import ( + "github.com/cosmos/cosmos-sdk/codec" +) + +func RegisterCodec(codec *codec.Codec) { + +} diff --git a/schema/errors/codec.go b/schema/errors/codec.go index 267905a3e..c67f1ec36 100644 --- a/schema/errors/codec.go +++ b/schema/errors/codec.go @@ -4,7 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { +func RegisterCodec(codec *codec.Codec) { codec.RegisterInterface((*error)(nil), nil) codec.RegisterInterface((*Error)(nil), nil) } diff --git a/schema/helpers/base/auxiliary_test.go b/schema/helpers/base/auxiliary_test.go new file mode 100644 index 000000000..0e695d46a --- /dev/null +++ b/schema/helpers/base/auxiliary_test.go @@ -0,0 +1,133 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "reflect" + "testing" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/utilities/test/schema/helpers/base" +) + +func TestNewAuxiliary(t *testing.T) { + type args struct { + name string + keeperPrototype func() helpers.AuxiliaryKeeper + } + tests := []struct { + name string + args args + want helpers.Auxiliary + }{ + + // TODO get it verified as it's failing + {"+ve", args{"testAuxiliary", base.TestAuxiliaryKeeperPrototype}, auxiliary{name: "testAuxiliary", keeperPrototype: base.TestAuxiliaryKeeperPrototype}}, + {"nil", args{"nil", nil}, auxiliary{"nil", nil, nil}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewAuxiliary(tt.args.name, tt.args.keeperPrototype); !reflect.DeepEqual(got.GetName(), tt.want.GetName()) { + t.Errorf("NewAuxiliary() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_auxiliary_GetKeeper(t *testing.T) { + context, _, _ := base.SetupTest(t) + type fields struct { + name string + auxiliaryKeeper helpers.AuxiliaryKeeper + keeperPrototype func() helpers.AuxiliaryKeeper + } + tests := []struct { + name string + fields fields + want helpers.AuxiliaryKeeper + }{ + + {"+ve", fields{"testAuxiliary", base.TestAuxiliaryKeeperPrototype(), base.TestAuxiliaryKeeperPrototype}, auxiliary{name: "testAuxiliary", keeperPrototype: base.TestAuxiliaryKeeperPrototype}.auxiliaryKeeper}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliary := auxiliary{ + name: tt.fields.name, + auxiliaryKeeper: tt.fields.auxiliaryKeeper, + keeperPrototype: tt.fields.keeperPrototype, + } + if got := auxiliary.GetKeeper().Help(context, nil); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetKeeper() = %T, want %T", got, tt.want) + } + }) + } +} + +func Test_auxiliary_GetName(t *testing.T) { + type fields struct { + name string + auxiliaryKeeper helpers.AuxiliaryKeeper + keeperPrototype func() helpers.AuxiliaryKeeper + } + tests := []struct { + name string + fields fields + want string + }{ + + {"+ve", fields{"testAuxiliary", base.TestAuxiliaryKeeperPrototype(), base.TestAuxiliaryKeeperPrototype}, auxiliary{name: "testAuxiliary", keeperPrototype: base.TestAuxiliaryKeeperPrototype}.name}, + {"nil", fields{"", nil, nil}, ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliary := auxiliary{ + name: tt.fields.name, + auxiliaryKeeper: tt.fields.auxiliaryKeeper, + keeperPrototype: tt.fields.keeperPrototype, + } + if got := auxiliary.GetName(); got != tt.want { + t.Errorf("GetName() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_auxiliary_Initialize(t *testing.T) { + _, storeKey, _ := base.SetupTest(t) + + Mapper := NewMapper(base.KeyPrototype, base.MappablePrototype).Initialize(storeKey) + Auxiliary := auxiliary{"testAuxiliary", base.TestAuxiliaryKeeperPrototype(), base.TestAuxiliaryKeeperPrototype} + Auxiliary.auxiliaryKeeper = Auxiliary.keeperPrototype().Initialize(Mapper, nil, nil).(helpers.AuxiliaryKeeper) + type fields struct { + name string + auxiliaryKeeper helpers.AuxiliaryKeeper + keeperPrototype func() helpers.AuxiliaryKeeper + } + type args struct { + mapper helpers.Mapper + parameters helpers.Parameters + auxiliaryKeepers []interface{} + } + tests := []struct { + name string + fields fields + args args + want helpers.Auxiliary + }{ + // TODO find fix + // {"+ve", fields{"testAuxiliary", base.TestAuxiliaryKeeperPrototype(), base.TestAuxiliaryKeeperPrototype}, args{mapper: Mapper, parameters: nil, auxiliaryKeepers: nil}, Auxiliary}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + auxiliary := auxiliary{ + name: tt.fields.name, + auxiliaryKeeper: tt.fields.auxiliaryKeeper, + keeperPrototype: tt.fields.keeperPrototype, + } + if got := auxiliary.Initialize(tt.args.mapper, tt.args.parameters, tt.args.auxiliaryKeepers...); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Initialize() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/schema/helpers/base/cliCommand.go b/schema/helpers/base/cliCommand.go index 7a44e348b..cd672e1e6 100644 --- a/schema/helpers/base/cliCommand.go +++ b/schema/helpers/base/cliCommand.go @@ -6,7 +6,7 @@ package base import ( "fmt" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/spf13/cobra" @@ -85,11 +85,11 @@ func (cliCommand cliCommand) ReadString(cliFlag helpers.CLIFlag) string { panic(fmt.Errorf("uregistered flag %v type %T", cliFlag.GetName(), cliFlag.GetValue())) } -func (cliCommand cliCommand) ReadBaseReq(context client.Context) rest.BaseReq { +func (cliCommand cliCommand) ReadBaseReq(cliContext context.CLIContext) rest.BaseReq { return rest.BaseReq{ - From: context.GetFromAddress().String(), - ChainID: context.ChainID, - Simulate: context.Simulate, + From: cliContext.GetFromAddress().String(), + ChainID: cliContext.ChainID, + Simulate: cliContext.Simulate, } } func (cliCommand cliCommand) CreateCommand(runE func(command *cobra.Command, args []string) error) *cobra.Command { @@ -100,9 +100,8 @@ func (cliCommand cliCommand) CreateCommand(runE func(command *cobra.Command, arg RunE: runE, } cliCommand.registerFlags(command) - flags.AddTxFlagsToCmd(command) - return command + return flags.PostCommands(command)[0] } func NewCLICommand(use string, short string, long string, cliFlagList []helpers.CLIFlag) helpers.CLICommand { diff --git a/schema/helpers/base/cliCommand_test.go b/schema/helpers/base/cliCommand_test.go new file mode 100644 index 000000000..b0be1056e --- /dev/null +++ b/schema/helpers/base/cliCommand_test.go @@ -0,0 +1,318 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "reflect" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/rest" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" +) + +func initialize() (helpers.CLICommand, []helpers.CLIFlag) { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + cliContext := context.NewCLIContext().WithCodec(Codec) + cliContext = cliContext.WithChainID("chainID") + + testCliFlag := NewCLIFlag("name", "value", ",usage") + testCliFlag2 := NewCLIFlag("name2", int64(-1), ",usage") + testCliFlag3 := NewCLIFlag("name3", 123, ",usage") + testCliFlag4 := NewCLIFlag("name4", false, ",usage") + testCliFlagList := []helpers.CLIFlag{testCliFlag, testCliFlag2, testCliFlag3, testCliFlag4} + testCliCommand := NewCLICommand("", "", "", testCliFlagList).(cliCommand) + return testCliCommand, testCliFlagList +} + +func TestNewCLICommand(t *testing.T) { + _, testCliFlagList := initialize() + type args struct { + use string + short string + long string + cliFlagList []helpers.CLIFlag + } + tests := []struct { + name string + args args + want helpers.CLICommand + }{ + + {"+ve", args{"", "", "", testCliFlagList}, cliCommand{"", "", "", testCliFlagList}}, + {"nil", args{"", "", "", nil}, cliCommand{"", "", "", nil}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewCLICommand(tt.args.use, tt.args.short, tt.args.long, tt.args.cliFlagList); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewCLICommand() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_cliCommand_CreateCommand(t *testing.T) { + // _, testCliFlagList := initialize() + type fields struct { + use string + short string + long string + cliFlagList []helpers.CLIFlag + } + type args struct { + runE func(command *cobra.Command, args []string) error + } + tests := []struct { + name string + fields fields + args args + want *cobra.Command + }{ + // TODO: Add test cases. + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cliCommand := cliCommand{ + use: tt.fields.use, + short: tt.fields.short, + long: tt.fields.long, + cliFlagList: tt.fields.cliFlagList, + } + if got := cliCommand.CreateCommand(tt.args.runE); !reflect.DeepEqual(got, tt.want) { + t.Errorf("CreateCommand() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_cliCommand_ReadBaseReq(t *testing.T) { + _, testCliFlagList := initialize() + + type fields struct { + use string + short string + long string + cliFlagList []helpers.CLIFlag + } + type args struct { + cliContext context.CLIContext + } + tests := []struct { + name string + fields fields + args args + want rest.BaseReq + }{ + + {"+ve", fields{"", "", "", testCliFlagList}, args{context.CLIContext{ChainID: "chainID"}}, rest.BaseReq{ChainID: "chainID"}}, + {"-ve for nil", fields{"", "", "", nil}, args{context.CLIContext{ChainID: ""}}, rest.BaseReq{ChainID: ""}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cliCommand := cliCommand{ + use: tt.fields.use, + short: tt.fields.short, + long: tt.fields.long, + cliFlagList: tt.fields.cliFlagList, + } + if got := cliCommand.ReadBaseReq(tt.args.cliContext); !reflect.DeepEqual(got, tt.want) { + t.Errorf("ReadBaseReq() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_cliCommand_ReadBool(t *testing.T) { + testCliCommand, testCLiFlagList := initialize() + + type fields struct { + use string + short string + long string + cliFlagList []helpers.CLIFlag + } + type args struct { + cliFlag helpers.CLIFlag + } + tests := []struct { + name string + fields fields + args args + want bool + }{ + + {"+ve", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name4", false, ",usage")}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cliCommand := cliCommand{ + use: tt.fields.use, + short: tt.fields.short, + long: tt.fields.long, + cliFlagList: tt.fields.cliFlagList, + } + if got := cliCommand.ReadBool(tt.args.cliFlag); got != tt.want { + t.Errorf("ReadBool() = %v, want %v", got, tt.want) + } + }) + } + require.Panics(t, func() { + testCliCommand.ReadString(NewCLIFlag("name", 1, ",usage")) + }) +} + +func Test_cliCommand_ReadInt(t *testing.T) { + _, testCLiFlagList := initialize() + type fields struct { + use string + short string + long string + cliFlagList []helpers.CLIFlag + } + type args struct { + cliFlag helpers.CLIFlag + } + tests := []struct { + name string + fields fields + args args + want int + shouldPanic bool + }{ + + {"-ve flag name not an int flag", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name", "value", ",usage")}, 0, true}, + {"-ve unregistered flag", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name", 1, ",usage")}, 1, true}, + {"+ve", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name3", 123, ",usage")}, 0, false}, + {"-ve should panic", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name4", struct{}{}, ",usage")}, 0, true}, + // {"-ve should not panic", fields{"", "", "", nil}, args{NewCLIFlag("name4", 123, ",usage")}, 0, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cliCommand := cliCommand{ + use: tt.fields.use, + short: tt.fields.short, + long: tt.fields.long, + cliFlagList: tt.fields.cliFlagList, + } + if tt.shouldPanic { + assert.Panics(t, func() { cliCommand.ReadInt(tt.args.cliFlag) }, "The code did not panic, but it should panic") + } else { + if got := cliCommand.ReadInt(tt.args.cliFlag); got != tt.want { + t.Errorf("ReadInt() = %v, want %v", got, tt.want) + } + } + }) + } +} + +func Test_cliCommand_ReadInt64(t *testing.T) { + _, testCLiFlagList := initialize() + type fields struct { + use string + short string + long string + cliFlagList []helpers.CLIFlag + } + type args struct { + cliFlag helpers.CLIFlag + } + tests := []struct { + name string + fields fields + args args + want int64 + shouldPanic bool + }{ + + {"-ve flag name not an int64 flag", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name", "value", ",usage")}, 1, true}, + {"-ve unregistered flag", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name2", int64(1), ",usage")}, 1, true}, + {"+ve", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name2", int64(-1), ",usage")}, 0, false}, + {"-ve should panic", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name4", struct{}{}, ",usage")}, 0, true}, + {"-ve should panic for nil", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name2", nil, ",usage")}, 0, true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cliCommand := cliCommand{ + use: tt.fields.use, + short: tt.fields.short, + long: tt.fields.long, + cliFlagList: tt.fields.cliFlagList, + } + if tt.shouldPanic { + assert.Panics(t, func() { cliCommand.ReadInt(tt.args.cliFlag) }, "The code did not panic, but it should panic") + } else { + if got := cliCommand.ReadInt64(tt.args.cliFlag); got != tt.want { + t.Errorf("ReadInt64() = %v, want %v", got, tt.want) + } + } + }) + } +} + +func Test_cliCommand_ReadString(t *testing.T) { + _, testCLiFlagList := initialize() + type fields struct { + use string + short string + long string + cliFlagList []helpers.CLIFlag + } + type args struct { + cliFlag helpers.CLIFlag + } + tests := []struct { + name string + fields fields + args args + want string + shouldPanic bool + }{ + + {"+ve", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name", "value", ",usage")}, "", false}, + {"-ve unregistered flag", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name", "value1", ",usage")}, "", true}, + {"-ve should panic", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name3", 1, ",usage")}, "0", true}, + {"-ve flag name not a string flag", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name2", int64(-1), ",usage")}, "0", true}, + {"-ve should panic for nil", fields{"", "", "", testCLiFlagList}, args{NewCLIFlag("name2", nil, ",usage")}, "0", true}} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cliCommand := cliCommand{ + use: tt.fields.use, + short: tt.fields.short, + long: tt.fields.long, + cliFlagList: tt.fields.cliFlagList, + } + if tt.shouldPanic { + assert.Panics(t, func() { cliCommand.ReadInt(tt.args.cliFlag) }, "The code did not panic, but it should panic") + } else { + if got := cliCommand.ReadString(tt.args.cliFlag); got != tt.want { + t.Errorf("ReadString() = %v, want %v", got, tt.want) + } + } + }) + } +} + +func Test_cliCommand_registerFlags(t *testing.T) { + _, testCLiFlagList := initialize() + testCliCommand := NewCLICommand("", "", "", testCLiFlagList).(cliCommand) + + require.NotPanics(t, func() { + testCliCommand.registerFlags(&cobra.Command{}) + }) +} diff --git a/schema/helpers/base/cliFlag_test.go b/schema/helpers/base/cliFlag_test.go new file mode 100644 index 000000000..ae384f2d3 --- /dev/null +++ b/schema/helpers/base/cliFlag_test.go @@ -0,0 +1,32 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" +) + +func Test_CliFlag(t *testing.T) { + testCliFlag := NewCLIFlag("name", "value", ",usage") + require.Panics(t, func() { + NewCLIFlag("name", struct{}{}, ",usage").Register(&cobra.Command{}) + }) + // GetName method test + require.Equal(t, "name", testCliFlag.GetName()) + // GetSupply method test + require.Equal(t, "value", testCliFlag.GetValue()) + + // ReadCLIValue method test + require.Equal(t, "", testCliFlag.ReadCLIValue()) + require.Equal(t, int64(0), NewCLIFlag("name", int64(-1), ",usage").ReadCLIValue()) + require.Equal(t, 0, NewCLIFlag("name", 123, ",usage").ReadCLIValue()) + require.Equal(t, false, NewCLIFlag("name", false, ",usage").ReadCLIValue()) + require.Panics(t, func() { + NewCLIFlag("name", struct{}{}, ",usage").ReadCLIValue() + }) + +} diff --git a/schema/helpers/base/collection_test.go b/schema/helpers/base/collection_test.go new file mode 100644 index 000000000..b24b3e17d --- /dev/null +++ b/schema/helpers/base/collection_test.go @@ -0,0 +1,58 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "reflect" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/utilities/test/schema/helpers/base" +) + +func TestCollection(t *testing.T) { + context, storeKey, _ := base.SetupTest(t) + Mapper := NewMapper(base.KeyPrototype, base.MappablePrototype).Initialize(storeKey) + + // Initialize + Collection := collection{}.Initialize(context, Mapper).(collection) + require.Equal(t, reflect.TypeOf(Mapper), reflect.TypeOf(Collection.mapper)) + + // Add + collection1 := Collection.Add(base.NewMappable("test1", "value1")) + require.Equal(t, []helpers.Mappable{base.NewMappable("test1", "value1")}, collection1.GetList()) + require.Nil(t, collection1.GetKey()) + + _ = Collection.Add(base.NewMappable("test2", "value2")) + _ = Collection.Add(base.NewMappable("test3", "value3")) + + // Mutate + Collection.Mutate(base.NewMappable("test2", "value3")) + require.Equal(t, base.NewMappable("test2", "value3"), Collection.Fetch(base.NewKey("test2")).Get(base.NewKey("test2"))) + require.NotEqual(t, base.NewMappable("test2", "value2"), Collection.Fetch(base.NewKey("test2")).Get(base.NewKey("test2"))) + + // Fetch + require.Equal(t, []helpers.Mappable{base.NewMappable("test1", "value1")}, Collection.Fetch(base.NewKey("test1")).GetList()) + + // GetProperty + Collection.Get(base.NewKey("test1")) + require.Equal(t, nil, Collection.Get(base.NewKey("test1"))) + require.Equal(t, base.NewMappable("test1", "value1"), Collection.Fetch(base.NewKey("test1")).Get(base.NewKey("test1"))) + + // GetKey + require.Equal(t, nil, Collection.GetKey()) + require.Equal(t, base.NewKey("test1"), Collection.Fetch(base.NewKey("test1")).GetKey()) + require.Equal(t, base.NewKey("test4"), Collection.Fetch(base.NewKey("test4")).GetKey()) + + // Get + Collection.GetList() + require.Equal(t, []helpers.Mappable{base.NewMappable("test1", "value1")}, Collection.Fetch(base.NewKey("test1")).GetList()) + + // Remove + Collection.Remove(base.NewMappable("test1", "value0")) + require.Equal(t, []helpers.Mappable(nil), Collection.Fetch(base.NewKey("test1")).GetList()) + +} diff --git a/schema/helpers/base/genesis.go b/schema/helpers/base/genesis.go index a95125c74..beecb7c78 100644 --- a/schema/helpers/base/genesis.go +++ b/schema/helpers/base/genesis.go @@ -8,35 +8,23 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/AssetMantle/modules/schema" "github.com/AssetMantle/modules/schema/errors/constants" "github.com/AssetMantle/modules/schema/helpers" - parametersSchema "github.com/AssetMantle/modules/schema/parameters" + parameters2 "github.com/AssetMantle/modules/schema/parameters" ) type genesis struct { - codec *codec.LegacyAmino + codec *codec.Codec keyPrototype func() helpers.Key mappablePrototype func() helpers.Mappable defaultMappableList []helpers.Mappable - defaultParameterList []parametersSchema.Parameter + defaultParameterList []parameters2.Parameter - MappableList []helpers.Mappable `json:"mappableList"` - ParameterList []parametersSchema.Parameter `json:"parameterList"` -} - -func (genesis genesis) Reset() { - // TODO implement me - panic("implement me") -} -func (genesis genesis) String() string { - // TODO implement me - panic("implement me") -} -func (genesis genesis) ProtoMessage() { - // TODO implement me - panic("implement me") + MappableList []helpers.Mappable `json:"mappableList"` + ParameterList []parameters2.Parameter `json:"parameterList"` } var _ helpers.Genesis = (*genesis)(nil) @@ -96,15 +84,15 @@ func (genesis genesis) Export(context sdkTypes.Context, mapper helpers.Mapper, p return genesis.Initialize(mappableList, parameters.GetList()) } -func (genesis genesis) Encode(jsonCodec codec.JSONCodec) []byte { - bytes, _ := genesis.codec.MarshalJSON(genesis) - // if err != nil { - // panic(err) - // } +func (genesis genesis) Encode() []byte { + bytes, err := genesis.codec.MarshalJSON(genesis) + if err != nil { + panic(err) + } return bytes } -func (genesis genesis) Decode(jsonCodec codec.JSONCodec, byte []byte) helpers.Genesis { +func (genesis genesis) Decode(byte []byte) helpers.Genesis { newGenesis := genesis if err := genesis.codec.UnmarshalJSON(byte, &newGenesis); err != nil { panic(err) @@ -112,7 +100,7 @@ func (genesis genesis) Decode(jsonCodec codec.JSONCodec, byte []byte) helpers.Ge return NewGenesis(genesis.keyPrototype, genesis.mappablePrototype, genesis.defaultMappableList, genesis.defaultParameterList).Initialize(newGenesis.MappableList, newGenesis.ParameterList) } -func (genesis genesis) Initialize(mappableList []helpers.Mappable, parameterList []parametersSchema.Parameter) helpers.Genesis { +func (genesis genesis) Initialize(mappableList []helpers.Mappable, parameterList []parameters2.Parameter) helpers.Genesis { if len(mappableList) == 0 { genesis.MappableList = genesis.defaultMappableList } else { @@ -132,25 +120,25 @@ func (genesis genesis) Initialize(mappableList []helpers.Mappable, parameterList genesis.ParameterList = parameterList } - // if err := genesis.Validate(); err != nil { - // panic(err) - // } + if err := genesis.Validate(); err != nil { + panic(err) + } return genesis } -func (genesis genesis) GetParameterList() []parametersSchema.Parameter { +func (genesis genesis) GetParameterList() []parameters2.Parameter { return genesis.ParameterList } func (genesis genesis) GetMappableList() []helpers.Mappable { return genesis.MappableList } -func NewGenesis(keyPrototype func() helpers.Key, mappablePrototype func() helpers.Mappable, defaultMappableList []helpers.Mappable, defaultParameterList []parametersSchema.Parameter) helpers.Genesis { - Codec := codec.NewLegacyAmino() +func NewGenesis(keyPrototype func() helpers.Key, mappablePrototype func() helpers.Mappable, defaultMappableList []helpers.Mappable, defaultParameterList []parameters2.Parameter) helpers.Genesis { + Codec := codec.New() keyPrototype().RegisterCodec(Codec) mappablePrototype().RegisterCodec(Codec) - helpers.RegisterCodec(Codec) + schema.RegisterCodec(Codec) Codec.Seal() return genesis{ @@ -160,6 +148,6 @@ func NewGenesis(keyPrototype func() helpers.Key, mappablePrototype func() helper defaultMappableList: defaultMappableList, defaultParameterList: defaultParameterList, MappableList: []helpers.Mappable{}, - ParameterList: []parametersSchema.Parameter{}, + ParameterList: []parameters2.Parameter{}, } } diff --git a/schema/helpers/base/genesis_test.go b/schema/helpers/base/genesis_test.go new file mode 100644 index 000000000..eb9bd6f44 --- /dev/null +++ b/schema/helpers/base/genesis_test.go @@ -0,0 +1,51 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + parameters2 "github.com/AssetMantle/modules/schema/parameters" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" + baseTestUtilities "github.com/AssetMantle/modules/utilities/test/schema/helpers/base" +) + +func TestGenesis(t *testing.T) { + context, storeKey, transientStoreKey := baseTestUtilities.SetupTest(t) + codec := baseTestUtilities.MakeCodec() + Mapper := NewMapper(baseTestUtilities.KeyPrototype, baseTestUtilities.MappablePrototype).Initialize(storeKey) + + mappableList := []helpers.Mappable{baseTestUtilities.NewMappable("test", "testValue")} + ParameterList := []parameters2.Parameter{baseTypes.NewParameter(baseIDs.NewStringID("testParameter"), baseData.NewStringData("testData"), func(interface{}) error { return nil })} + Parameters := NewParameters(ParameterList...) + subspace := params.NewSubspace(codec, storeKey, transientStoreKey, "test").WithKeyTable(Parameters.GetKeyTable()) + Parameters = Parameters.Initialize(subspace) + + Genesis := NewGenesis(baseTestUtilities.KeyPrototype, baseTestUtilities.MappablePrototype, mappableList, ParameterList).Initialize(mappableList, ParameterList).(genesis) + + err := Genesis.Validate() + require.Nil(t, err) + + require.Equal(t, mappableList, Genesis.Default().(genesis).MappableList) + require.Equal(t, ParameterList, Genesis.Default().(genesis).defaultParameterList) + + require.Equal(t, mappableList, Genesis.GetMappableList()) + require.Equal(t, ParameterList, Genesis.GetParameterList()) + + require.Equal(t, Genesis.Encode(), Genesis.Decode(Genesis.Encode()).Encode()) + + require.NotPanics(t, func() { + Genesis.Import(context, Mapper, Parameters) + }) + require.NotPanics(t, func() { + err := Genesis.Export(context, Mapper, Parameters).Validate() + require.Nil(t, err) + }) +} diff --git a/schema/helpers/base/invariants.go b/schema/helpers/base/invariants.go deleted file mode 100644 index 55fbeb373..000000000 --- a/schema/helpers/base/invariants.go +++ /dev/null @@ -1,30 +0,0 @@ -package base - -import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - - "github.com/AssetMantle/modules/schema/helpers" -) - -type invariants struct { - moduleName string - route string - invariantList []sdkTypes.Invariant -} - -var _ helpers.Invariants = (*invariants)(nil) - -func (invariants invariants) RegisterInvariants(invariantRegistry sdkTypes.InvariantRegistry) { - for _, invariant := range invariants.invariantList { - // ****** TODO check if route should be different for each invariant - invariantRegistry.RegisterRoute(invariants.moduleName, invariants.route, invariant) - } -} - -func NewInvariants(moduleName, route string, invariantList ...sdkTypes.Invariant) helpers.Invariants { - return invariants{ - moduleName: moduleName, - route: route, - invariantList: invariantList, - } -} diff --git a/schema/helpers/base/mapper.go b/schema/helpers/base/mapper.go index 737db1f85..465a67e14 100644 --- a/schema/helpers/base/mapper.go +++ b/schema/helpers/base/mapper.go @@ -1,28 +1,23 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base import ( "bytes" "fmt" - "github.com/cosmos/cosmos-sdk/types/kv" "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/tendermint/libs/kv" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" ) type mapper struct { kvStoreKey *sdkTypes.KVStoreKey - legacyAminoCodec *codec.LegacyAmino - codec codec.Marshaler + codec *codec.Codec keyPrototype func() helpers.Key mappablePrototype func() helpers.Mappable } @@ -49,10 +44,11 @@ func (mapper mapper) Read(context sdkTypes.Context, key helpers.Key) helpers.Map return nil } - mappable := mapper.mappablePrototype().GetStructReference() + var mappable helpers.Mappable - mapper.codec.MustUnmarshalBinaryBare(Bytes, mappable) - return mappable.(helpers.Mappable) + mapper.codec.MustUnmarshalBinaryBare(Bytes, &mappable) + + return mappable } func (mapper mapper) Update(context sdkTypes.Context, mappable helpers.Mappable) { Bytes := mapper.codec.MustMarshalBinaryBare(mappable) @@ -71,11 +67,11 @@ func (mapper mapper) Iterate(context sdkTypes.Context, partialKey helpers.Key, a defer kvStorePrefixIterator.Close() for ; kvStorePrefixIterator.Valid(); kvStorePrefixIterator.Next() { - mappable := mapper.mappablePrototype().GetStructReference() + var mappable helpers.Mappable - mapper.codec.MustUnmarshalBinaryBare(kvStorePrefixIterator.Value(), mappable) + mapper.codec.MustUnmarshalBinaryBare(kvStorePrefixIterator.Value(), &mappable) - if accumulator(mappable.(helpers.Mappable)) { + if accumulator(mappable) { break } } @@ -89,22 +85,22 @@ func (mapper mapper) ReverseIterate(context sdkTypes.Context, partialKey helpers for ; kvStoreReversePrefixIterator.Valid(); kvStoreReversePrefixIterator.Next() { var mappable helpers.Mappable - mapper.codec.MustUnmarshalBinaryBare(kvStoreReversePrefixIterator.Value(), mappable) + mapper.codec.MustUnmarshalBinaryBare(kvStoreReversePrefixIterator.Value(), &mappable) if accumulator(mappable) { break } } } -func (mapper mapper) StoreDecoder(kvA kv.Pair, kvB kv.Pair) string { +func (mapper mapper) StoreDecoder(_ *codec.Codec, kvA kv.Pair, kvB kv.Pair) string { if bytes.Equal(kvA.Key[:1], mapper.keyPrototype().GenerateStoreKeyBytes()) { var mappableA helpers.Mappable - mapper.codec.MustUnmarshalBinaryBare(kvA.Value, mappableA) + mapper.codec.MustUnmarshalBinaryBare(kvA.Value, &mappableA) var mappableB helpers.Mappable - mapper.codec.MustUnmarshalBinaryBare(kvB.Value, mappableB) + mapper.codec.MustUnmarshalBinaryBare(kvB.Value, &mappableB) return fmt.Sprintf("%v\n%v", mappableA, mappableB) } @@ -116,17 +112,14 @@ func (mapper mapper) Initialize(kvStoreKey *sdkTypes.KVStoreKey) helpers.Mapper return mapper } func NewMapper(keyPrototype func() helpers.Key, mappablePrototype func() helpers.Mappable) helpers.Mapper { - registry := codectypes.NewInterfaceRegistry() - Codec := codec.NewProtoCodec(registry) - LegacyAminoCodec := codec.NewLegacyAmino() - keyPrototype().RegisterLegacyAminoCodec(LegacyAminoCodec) - mappablePrototype().RegisterLegacyAminoCodec(LegacyAminoCodec) - schema.RegisterLegacyAminoCodec(LegacyAminoCodec) - LegacyAminoCodec.Seal() + Codec := codec.New() + keyPrototype().RegisterCodec(Codec) + mappablePrototype().RegisterCodec(Codec) + schema.RegisterCodec(Codec) + Codec.Seal() return mapper{ codec: Codec, - legacyAminoCodec: LegacyAminoCodec, keyPrototype: keyPrototype, mappablePrototype: mappablePrototype, } diff --git a/schema/helpers/base/mapper_test.go b/schema/helpers/base/mapper_test.go index d5d5b51a1..b4527da6f 100644 --- a/schema/helpers/base/mapper_test.go +++ b/schema/helpers/base/mapper_test.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base @@ -9,13 +7,15 @@ import ( "reflect" "testing" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/utilities/test/schema/helpers/base" + "github.com/cosmos/cosmos-sdk/codec" "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/libs/kv" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/utilities/test/schema/helpers/base" ) func TestMapper(t *testing.T) { - context, storeKey, _ := base.SetupTest(t) // NewMapper @@ -51,12 +51,12 @@ func TestMapper(t *testing.T) { // Iterate testMapper.Iterate(context, base.NewKey("test1"), func(mappable helpers.Mappable) bool { return false }) - testMapper.Iteate(context, base.NewKey("test3"), func(mappable helpers.Mappable) bool { return false }) + testMapper.Iterate(context, base.NewKey("test3"), func(mappable helpers.Mappable) bool { return false }) // Store Decoder - //require.Equal(t, "{test1 value1}\n{test1 value1}", testMapper.StoreDecoder(codec.New(), kv.Pair{ - // Key: append([]byte{0x11}, []byte("test1")...), Value: testMapper.legacyAminoCodec.MustMarshalBinaryBare(base.NewMappable("test1", "value1"))}, kv.Pair{ - // Key: append([]byte{0x11}, []byte("test1")...), Value: testMapper.legacyAminoCodec.MustMarshalBinaryBare(base.NewMappable("test1", "value1"))}), - //) + require.Equal(t, "{test1 value1}\n{test1 value1}", testMapper.StoreDecoder(codec.New(), kv.Pair{ + Key: append([]byte{0x11}, []byte("test1")...), Value: testMapper.codec.MustMarshalBinaryBare(base.NewMappable("test1", "value1"))}, kv.Pair{ + Key: append([]byte{0x11}, []byte("test1")...), Value: testMapper.codec.MustMarshalBinaryBare(base.NewMappable("test1", "value1"))}), + ) } diff --git a/schema/helpers/base/module.go b/schema/helpers/base/module.go index 25b9f869e..ae1c74cdf 100644 --- a/schema/helpers/base/module.go +++ b/schema/helpers/base/module.go @@ -1,28 +1,26 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base import ( "encoding/json" "fmt" + "math/rand" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" sdkTypesModule "github.com/cosmos/cosmos-sdk/types/module" - simTypes "github.com/cosmos/cosmos-sdk/types/simulation" - paramTypes "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" "github.com/spf13/cobra" abciTypes "github.com/tendermint/tendermint/abci/types" - "math/rand" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" ) type module struct { @@ -52,11 +50,11 @@ func (module module) GenerateGenesisState(simulationState *sdkTypesModule.Simula module.simulatorPrototype().RandomizedGenesisState(simulationState) } -func (module module) ProposalContents(simState sdkTypesModule.SimulationState) []simTypes.WeightedProposalContent { +func (module module) ProposalContents(_ sdkTypesModule.SimulationState) []simulation.WeightedProposalContent { return module.simulatorPrototype().WeightedProposalContentList() } -func (module module) RandomizedParams(r *rand.Rand) []simTypes.ParamChange { +func (module module) RandomizedParams(r *rand.Rand) []simulation.ParamChange { return module.simulatorPrototype().ParamChangeList(r) } @@ -64,23 +62,26 @@ func (module module) RegisterStoreDecoder(storeDecoderRegistry sdkTypes.StoreDec storeDecoderRegistry[module.name] = module.mapperPrototype().StoreDecoder } -func (module module) WeightedOperations(_ sdkTypesModule.SimulationState) []simTypes.WeightedOperation { +func (module module) WeightedOperations(_ sdkTypesModule.SimulationState) []simulation.WeightedOperation { return nil } func (module module) Name() string { return module.name } - -func (module module) DefaultGenesis(codec codec.JSONMarshaler) json.RawMessage { - return module.genesisPrototype().Default().Encode(codec) +func (module module) RegisterCodec(codec *codec.Codec) { + for _, transaction := range module.transactionsPrototype().GetList() { + transaction.RegisterCodec(codec) + } } - -func (module module) ValidateGenesis(codec codec.JSONMarshaler, txConfig client.TxEncodingConfig, rawMessage json.RawMessage) error { - genesisState := module.genesisPrototype().Decode(codec, rawMessage) +func (module module) DefaultGenesis() json.RawMessage { + return module.genesisPrototype().Default().Encode() +} +func (module module) ValidateGenesis(rawMessage json.RawMessage) error { + genesisState := module.genesisPrototype().Decode(rawMessage) return genesisState.Validate() } -func (module module) RegisterRESTRoutes(cliContext client.Context, router *mux.Router) { +func (module module) RegisterRESTRoutes(cliContext context.CLIContext, router *mux.Router) { for _, query := range module.queriesPrototype().GetList() { router.HandleFunc("/"+module.Name()+"/"+query.GetName()+fmt.Sprintf("/{%s}", query.GetName()), query.RESTQueryHandler(cliContext)).Methods("GET") } @@ -89,15 +90,10 @@ func (module module) RegisterRESTRoutes(cliContext client.Context, router *mux.R router.HandleFunc("/"+module.Name()+"/"+transaction.GetName(), transaction.RESTRequestHandler(cliContext)).Methods("POST") } } -func (module module) RegisterGRPCGatewayRoutes(clientContext client.Context, serveMux *runtime.ServeMux) { - for _, query := range module.queriesPrototype().GetList() { - query.RegisterGRPCGatewayRoute(clientContext, serveMux) - } -} -func (module module) GetTxCmd() *cobra.Command { +func (module module) GetTxCmd(codec *codec.Codec) *cobra.Command { rootTransactionCommand := &cobra.Command{ Use: module.name, - Short: "Get root transaction command.", + Short: "GetProperty root transaction command.", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, @@ -105,7 +101,7 @@ func (module module) GetTxCmd() *cobra.Command { commandList := make([]*cobra.Command, len(module.transactionsPrototype().GetList())) for i, transaction := range module.transactionsPrototype().GetList() { - commandList[i] = transaction.Command() + commandList[i] = transaction.Command(codec) } rootTransactionCommand.AddCommand( @@ -114,10 +110,10 @@ func (module module) GetTxCmd() *cobra.Command { return rootTransactionCommand } -func (module module) GetQueryCmd() *cobra.Command { +func (module module) GetQueryCmd(codec *codec.Codec) *cobra.Command { rootQueryCommand := &cobra.Command{ Use: module.name, - Short: "Get root query command.", + Short: "GetProperty root query command.", DisableFlagParsing: true, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, @@ -125,7 +121,7 @@ func (module module) GetQueryCmd() *cobra.Command { commandList := make([]*cobra.Command, len(module.queriesPrototype().GetList())) for i, query := range module.queriesPrototype().GetList() { - commandList[i] = query.Command() + commandList[i] = query.Command(codec) } rootQueryCommand.AddCommand( @@ -135,20 +131,18 @@ func (module module) GetQueryCmd() *cobra.Command { return rootQueryCommand } func (module module) RegisterInvariants(_ sdkTypes.InvariantRegistry) {} -func (module module) Route() sdkTypes.Route { - return sdkTypes.NewRoute(module.name, module.NewHandler()) +func (module module) Route() string { + return module.name } func (module module) NewHandler() sdkTypes.Handler { return func(context sdkTypes.Context, msg sdkTypes.Msg) (*sdkTypes.Result, error) { context = context.WithEventManager(sdkTypes.NewEventManager()) if module.transactions == nil { - panic(errors.UninitializedUsage) + panic(constants.UninitializedUsage) } - transaction := module.transactions.Get(msg.Type()) - - if transaction != nil { + if transaction := module.transactions.Get(msg.Type()); transaction != nil { return transaction.HandleMessage(context, msg) } @@ -158,10 +152,10 @@ func (module module) NewHandler() sdkTypes.Handler { func (module module) QuerierRoute() string { return module.name } -func (module module) LegacyQuerierHandler(legacyAmino *codec.LegacyAmino) sdkTypes.Querier { +func (module module) NewQuerierHandler() sdkTypes.Querier { return func(context sdkTypes.Context, path []string, requestQuery abciTypes.RequestQuery) ([]byte, error) { if module.queries == nil { - panic(errors.UninitializedUsage) + panic(constants.UninitializedUsage) } if query := module.queries.Get(path[0]); query != nil { @@ -171,24 +165,23 @@ func (module module) LegacyQuerierHandler(legacyAmino *codec.LegacyAmino) sdkTyp return nil, fmt.Errorf("unknown query path, %v for module %v", path[0], module.Name()) } } - -func (module module) InitGenesis(context sdkTypes.Context, codec codec.JSONMarshaler, rawMessage json.RawMessage) []abciTypes.ValidatorUpdate { - genesisState := module.genesisPrototype().Decode(codec, rawMessage) +func (module module) InitGenesis(context sdkTypes.Context, rawMessage json.RawMessage) []abciTypes.ValidatorUpdate { + genesisState := module.genesisPrototype().Decode(rawMessage) if module.mapper == nil || module.parameters == nil { - panic(errors.UninitializedUsage) + panic(constants.UninitializedUsage) } genesisState.Import(context, module.mapper, module.parameters) return []abciTypes.ValidatorUpdate{} } -func (module module) ExportGenesis(context sdkTypes.Context, codec codec.JSONMarshaler) json.RawMessage { +func (module module) ExportGenesis(context sdkTypes.Context) json.RawMessage { if module.mapper == nil || module.parameters == nil { - panic(errors.UninitializedUsage) + panic(constants.UninitializedUsage) } - return module.genesisPrototype().Export(context, module.mapper, module.parameters).Encode(codec) + return module.genesisPrototype().Export(context, module.mapper, module.parameters).Encode() } func (module module) BeginBlock(context sdkTypes.Context, beginBlockRequest abciTypes.RequestBeginBlock) { module.block.Begin(context, beginBlockRequest) @@ -213,10 +206,10 @@ func (module module) DecodeModuleTransactionRequest(transactionName string, rawM return transaction.DecodeTransactionRequest(rawMessage) } - return nil, errors.IncorrectMessage + return nil, constants.IncorrectMessage } -func (module module) Initialize(kvStoreKey *sdkTypes.KVStoreKey, paramsSubspace paramTypes.Subspace, auxiliaryKeepers ...interface{}) helpers.Module { +func (module module) Initialize(kvStoreKey *sdkTypes.KVStoreKey, paramsSubspace params.Subspace, auxiliaryKeepers ...interface{}) helpers.Module { module.mapper = module.mapperPrototype().Initialize(kvStoreKey) module.genesis = module.genesisPrototype().Initialize(module.genesisPrototype().GetMappableList(), module.genesisPrototype().GetParameterList()) @@ -256,32 +249,6 @@ func (module module) Initialize(kvStoreKey *sdkTypes.KVStoreKey, paramsSubspace return module } -func (module module) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - for _, transaction := range module.transactionsPrototype().GetList() { - transaction.RegisterLegacyAminoCodec(codec) - } - - // TODO queries codec can be registered here and removed from common -} - -func (module module) RegisterInterfaces(registry codecTypes.InterfaceRegistry) { - schema.RegisterProtoCodec(registry) - module.genesisPrototype().RegisterInterface(registry) - for _, transaction := range module.transactionsPrototype().GetList() { - transaction.RegisterInterface(registry) - } -} - -func (module module) RegisterServices(configurator sdkTypesModule.Configurator) { - for _, transaction := range module.transactionsPrototype().GetList() { - transaction.RegisterService(configurator) - } - for _, query := range module.queriesPrototype().GetList() { - query.RegisterService(configurator) - } - -} - func NewModule(name string, auxiliariesPrototype func() helpers.Auxiliaries, genesisPrototype func() helpers.Genesis, mapperPrototype func() helpers.Mapper, parametersPrototype func() helpers.Parameters, queriesPrototype func() helpers.Queries, simulatorPrototype func() helpers.Simulator, transactionsPrototype func() helpers.Transactions, blockPrototype func() helpers.Block) helpers.Module { return module{ name: name, diff --git a/schema/helpers/base/module_test.go b/schema/helpers/base/module_test.go index 42dad8bcf..574deaa07 100644 --- a/schema/helpers/base/module_test.go +++ b/schema/helpers/base/module_test.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base @@ -10,18 +8,21 @@ import ( "math/rand" "testing" - clientContext "github.com/cosmos/cosmos-sdk/client" + clientContext "github.com/cosmos/cosmos-sdk/client/context" sdkTypes "github.com/cosmos/cosmos-sdk/types" sdkModule "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/params" "github.com/gorilla/mux" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/schema/types/base" - helpersTestUtilities "github.com/persistenceOne/persistenceSDK/utilities/test/schema/helpers" - baseTestUtilities "github.com/persistenceOne/persistenceSDK/utilities/test/schema/helpers/base" "github.com/stretchr/testify/require" abciTypes "github.com/tendermint/tendermint/abci/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + "github.com/AssetMantle/modules/schema/helpers" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + parameters2 "github.com/AssetMantle/modules/schema/parameters" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" + helpersTestUtilities "github.com/AssetMantle/modules/utilities/test/schema/helpers" + baseTestUtilities "github.com/AssetMantle/modules/utilities/test/schema/helpers/base" ) var auxiliariesPrototype = func() helpers.Auxiliaries { @@ -30,13 +31,13 @@ var auxiliariesPrototype = func() helpers.Auxiliaries { var genesisPrototype = func() helpers.Genesis { return NewGenesis(baseTestUtilities.KeyPrototype, baseTestUtilities.MappablePrototype, []helpers.Mappable{baseTestUtilities.NewMappable("test", "testValue")}, - []types.Parameter{base.NewParameter(base.NewID("testParameter"), base.NewStringData("testData"), func(interface{}) error { return nil })}) + []parameters2.Parameter{baseTypes.NewParameter(baseIDs.NewStringID("testParameter"), baseData.NewStringData("testData"), func(interface{}) error { return nil })}) } var mapperPrototype = func() helpers.Mapper { return NewMapper(baseTestUtilities.KeyPrototype, baseTestUtilities.MappablePrototype) } var parametersPrototype = func() helpers.Parameters { - return NewParameters(base.NewParameter(base.NewID("testParameter"), base.NewStringData("testData"), func(interface{}) error { return nil })) + return NewParameters(baseTypes.NewParameter(baseIDs.NewStringID("testParameter"), baseData.NewStringData("testData"), func(interface{}) error { return nil })) } var queriesPrototype = func() helpers.Queries { return queries{[]helpers.Query{NewQuery("testQuery", "q", "testQuery", "test", baseTestUtilities.TestQueryRequestPrototype, @@ -52,15 +53,15 @@ var blockPrototype = func() helpers.Block { return helpersTestUtilities.TestBloc func TestModule(t *testing.T) { context, storeKey, transientStoreKey := baseTestUtilities.SetupTest(t) codec := baseTestUtilities.MakeCodec() - subspace := params.NewSubspace(codec, storeKey, transientStoreKey, "test") //.WithKeyTable(parametersPrototype().GetKeyTable()) - //subspace.SetParamSet(context, parametersPrototype()) + subspace := params.NewSubspace(codec, storeKey, transientStoreKey, "test") // .WithKeyTable(parametersPrototype().GetKeyTable()) + // subspace.SetParamSet(context, parametersPrototype()) Module := NewModule("test", auxiliariesPrototype, genesisPrototype, mapperPrototype, parametersPrototype, queriesPrototype, simulatorPrototype, transactionsPrototype, blockPrototype).Initialize(storeKey, subspace).(module) // AppModuleBasic require.Equal(t, "test", Module.Name()) - // RegisterLegacyAminoCodec + // RegisterCodec Module.RegisterCodec(codec) require.NotPanics(t, func() { @@ -68,7 +69,6 @@ func TestModule(t *testing.T) { }) require.NotPanics(t, func() { - }) require.Nil(t, Module.ValidateGenesis(Module.DefaultGenesis())) @@ -83,23 +83,23 @@ func TestModule(t *testing.T) { require.Equal(t, "test", Module.GetTxCmd(codec).Name()) require.Equal(t, "test", Module.GetQueryCmd(codec).Name()) - //AppModule + // AppModule require.NotPanics(t, func() { Module.RegisterInvariants(nil) }) require.Equal(t, "test", Module.Route()) - response, Error := Module.NewHandler()(context, baseTestUtilities.NewTestMessage(sdkTypes.AccAddress("addr"), "id")) - require.Nil(t, Error) + response, err := Module.NewHandler()(context, baseTestUtilities.NewTestMessage(sdkTypes.AccAddress("addr"), "id")) + require.Nil(t, err) require.NotNil(t, response) require.Equal(t, "test", Module.QuerierRoute()) - encodedRequest, Error := Module.queries.Get("testQuery").(query).requestPrototype().LegacyAminoEncode() - require.Nil(t, Error) + encodedRequest, err := Module.queries.Get("testQuery").(query).requestPrototype().Encode() + require.Nil(t, err) - queryResponse, Error := Module.NewQuerierHandler()(context, []string{"testQuery"}, abciTypes.RequestQuery{Data: encodedRequest}) - require.Nil(t, Error) + queryResponse, err := Module.NewQuerierHandler()(context, []string{"testQuery"}, abciTypes.RequestQuery{Data: encodedRequest}) + require.Nil(t, err) require.NotNil(t, queryResponse) require.NotPanics(t, func() { @@ -122,8 +122,8 @@ func TestModule(t *testing.T) { Module.WeightedOperations(sdkModule.SimulationState{}) }) - //types.Module + // types.Module require.Equal(t, "testAuxiliary", Module.GetAuxiliary("testAuxiliary").GetName()) - _, Error = Module.DecodeModuleTransactionRequest("TestMessage", json.RawMessage(`{"BaseReq":{"from":"addr"},"ID":"id"}`)) - require.Nil(t, Error) + _, err = Module.DecodeModuleTransactionRequest("TestMessage", json.RawMessage(`{"BaseReq":{"from":"addr"},"ID":"id"}`)) + require.Nil(t, err) } diff --git a/schema/helpers/base/parameters.go b/schema/helpers/base/parameters.go index 79f708456..7232b1d39 100644 --- a/schema/helpers/base/parameters.go +++ b/schema/helpers/base/parameters.go @@ -1,22 +1,23 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base import ( - paramTypes "github.com/cosmos/cosmos-sdk/x/params/types" "strings" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - "github.com/persistenceOne/persistenceSDK/schema/types" + "github.com/cosmos/cosmos-sdk/x/params" + + "github.com/AssetMantle/modules/schema/data" + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/schema/ids" + parameters2 "github.com/AssetMantle/modules/schema/parameters" ) type parameters struct { - parameterList []types.Parameter - paramsSubspace paramTypes.Subspace + parameterList []parameters2.Parameter + paramsSubspace params.Subspace } var _ helpers.Parameters = (*parameters)(nil) @@ -31,8 +32,8 @@ func (parameters parameters) String() string { } func (parameters parameters) Validate() error { for _, parameter := range parameters.parameterList { - if Error := parameter.Validate(); Error != nil { - return Error + if err := parameter.Validate(); err != nil { + return err } } @@ -47,7 +48,7 @@ func (parameters parameters) Equal(compareParameters helpers.Parameters) bool { return true } -func (parameters parameters) Get(id types.ID) types.Parameter { +func (parameters parameters) Get(id ids.ID) parameters2.Parameter { for _, parameter := range parameters.parameterList { if parameter.GetID().Compare(id) == 0 { return parameter @@ -56,23 +57,23 @@ func (parameters parameters) Get(id types.ID) types.Parameter { return nil } -func (parameters parameters) GetList() []types.Parameter { +func (parameters parameters) GetList() []parameters2.Parameter { return parameters.parameterList } -func (parameters parameters) Fetch(context sdkTypes.Context, id types.ID) helpers.Parameters { - var data types.Data +func (parameters parameters) Fetch(context sdkTypes.Context, id ids.ID) helpers.Parameters { + var Data data.Data - parameters.paramsSubspace.Get(context, id.Bytes(), &data) + parameters.paramsSubspace.Get(context, id.Bytes(), &Data) for i, parameter := range parameters.parameterList { if parameter.GetID().Compare(id) == 0 { - parameters.parameterList[i] = parameter.Mutate(data) + parameters.parameterList[i] = parameter.Mutate(Data) } } return parameters } -func (parameters parameters) Mutate(context sdkTypes.Context, newParameter types.Parameter) helpers.Parameters { +func (parameters parameters) Mutate(context sdkTypes.Context, newParameter parameters2.Parameter) helpers.Parameters { for i, parameter := range parameters.parameterList { if parameter.GetID().Compare(newParameter.GetID()) == 0 { parameters.parameterList[i] = newParameter @@ -84,24 +85,24 @@ func (parameters parameters) Mutate(context sdkTypes.Context, newParameter types return parameters } -func (parameters parameters) ParamSetPairs() paramTypes.ParamSetPairs { - paramSetPairList := make([]paramTypes.ParamSetPair, len(parameters.parameterList)) +func (parameters parameters) ParamSetPairs() params.ParamSetPairs { + paramSetPairList := make([]params.ParamSetPair, len(parameters.parameterList)) for i, parameter := range parameters.parameterList { - paramSetPairList[i] = paramTypes.NewParamSetPair(parameter.GetID().Bytes(), parameter.GetData(), parameter.GetValidator()) + paramSetPairList[i] = params.NewParamSetPair(parameter.GetID().Bytes(), parameter.GetData(), parameter.GetValidator()) } return paramSetPairList } -func (parameters parameters) GetKeyTable() paramTypes.KeyTable { - return paramTypes.NewKeyTable().RegisterParamSet(parameters) +func (parameters parameters) GetKeyTable() params.KeyTable { + return params.NewKeyTable().RegisterParamSet(parameters) } -func (parameters parameters) Initialize(paramsSubspace paramTypes.Subspace) helpers.Parameters { +func (parameters parameters) Initialize(paramsSubspace params.Subspace) helpers.Parameters { parameters.paramsSubspace = paramsSubspace return parameters } -func NewParameters(parameterList ...types.Parameter) helpers.Parameters { +func NewParameters(parameterList ...parameters2.Parameter) helpers.Parameters { return parameters{ parameterList: parameterList, } diff --git a/schema/helpers/base/parameters_test.go b/schema/helpers/base/parameters_test.go new file mode 100644 index 000000000..75aa0c225 --- /dev/null +++ b/schema/helpers/base/parameters_test.go @@ -0,0 +1,47 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/stretchr/testify/require" + + baseData "github.com/AssetMantle/modules/schema/data/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + parameters2 "github.com/AssetMantle/modules/schema/parameters" + baseTypes "github.com/AssetMantle/modules/schema/parameters/base" + baseTestUtilities "github.com/AssetMantle/modules/utilities/test/schema/helpers/base" +) + +func TestParameters(t *testing.T) { + context, storeKey, transientStoreKey := baseTestUtilities.SetupTest(t) + codec := baseTestUtilities.MakeCodec() + Parameter := baseTypes.NewParameter(baseIDs.NewStringID("testParameter"), baseData.NewStringData("testData"), func(interface{}) error { return nil }) + ParameterList := []parameters2.Parameter{Parameter} + Parameters := NewParameters(ParameterList...) + subspace := params.NewSubspace(codec, storeKey, transientStoreKey, "test").WithKeyTable(Parameters.GetKeyTable()) + subspace.SetParamSet(context, Parameters) + Parameters = Parameters.Initialize(subspace).(parameters) + + require.NotNil(t, Parameters.ParamSetPairs()) + + require.NotNil(t, Parameters.GetKeyTable()) + + require.Equal(t, true, Parameters.Equal(Parameters)) + + require.Equal(t, true, Parameters.GetList()[0].Equal(Parameter)) + require.Equal(t, `{"id":{"idString":"testParameter"},"data":{"value":"testData"}}`, Parameters.String()) + + err := Parameters.Validate() + require.Nil(t, err) + + require.NotPanics(t, func() { + Parameters.Fetch(context, baseIDs.NewStringID("testParameter")) + }) + + require.Equal(t, "testData123", Parameters.Mutate(context, + baseTypes.NewParameter(baseIDs.NewStringID("testParameter"), baseData.NewStringData("testData123"), func(interface{}) error { return nil })).Get(baseIDs.NewStringID("testParameter")).GetData().String()) +} diff --git a/schema/helpers/base/queries_test.go b/schema/helpers/base/queries_test.go new file mode 100644 index 000000000..fbc932721 --- /dev/null +++ b/schema/helpers/base/queries_test.go @@ -0,0 +1,26 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/helpers" +) + +func TestQueries(t *testing.T) { + Queries1 := NewQueries(query{}) + Queries2 := NewQueries() + + // GetProperty + require.Equal(t, "", Queries1.Get("").GetName()) + require.Equal(t, nil, Queries2.Get("")) + + // Get + require.Equal(t, []helpers.Query{query{}}, Queries1.GetList()) + require.Equal(t, []helpers.Query(nil), Queries2.GetList()) + +} diff --git a/schema/helpers/base/query.go b/schema/helpers/base/query.go index 561693660..cd9ddba72 100644 --- a/schema/helpers/base/query.go +++ b/schema/helpers/base/query.go @@ -1,22 +1,20 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base import ( - "encoding/json" - "github.com/cosmos/cosmos-sdk/client" + "net/http" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - sdkTypesModule "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/persistenceOne/persistenceSDK/schema/helpers" "github.com/spf13/cobra" abciTypes "github.com/tendermint/tendermint/abci/types" - "net/http" + + "github.com/AssetMantle/modules/schema/helpers" ) type query struct { @@ -32,75 +30,57 @@ type query struct { var _ helpers.Query = (*query)(nil) func (query query) GetName() string { return query.name } - -//TODO:see if this approach can be used here when the GRPC service is hit module is not initialized(queryKeeper uninitialised) -//Approach: see if we can change the point where GRPCQuery service hits. -//func (query query) GetCommand() *cobra.Command { -// cmd := query.cliCommand.CreateQueryCommand() -// cmd.RunE = func(cmd *cobra.Command, args []string) error { -// clientCtx, err := client.GetClientQueryContext(cmd) -// if err != nil { -// panic(err) -// } -// queryRequest := query.requestPrototype().FromCLI(query.cliCommand, clientCtx) -// response, Error := query.queryKeeper.QueryInKeeper(cmd, clientCtx, queryRequest) -// if Error != nil { -// return Error -// } -// -// return clientCtx.PrintProto(response) -// } -// return cmd -//} - -func (query query) Command() *cobra.Command { +func (query query) Command(codec *codec.Codec) *cobra.Command { runE := func(command *cobra.Command, args []string) error { - clientContext, err := client.GetClientQueryContext(command) + cliContext := context.NewCLIContext().WithCodec(codec) + + queryRequest, err := query.requestPrototype().FromCLI(query.cliCommand, cliContext) if err != nil { return err } - queryRequest := query.requestPrototype().FromCLI(query.cliCommand, clientContext) - responseBytes, _, Error := query.query(queryRequest, clientContext) - if Error != nil { - return Error + + responseBytes, _, err := query.query(queryRequest, cliContext) + if err != nil { + return err } - var response map[string]interface{} - Error = json.Unmarshal(responseBytes, &response) - if Error != nil { - return Error + response, err := query.responsePrototype().Decode(responseBytes) + if err != nil { + return err } - //TODO: as in QueryResponse the Mappables is types.Mappable in all queries except for splits/ownable Unmarshalling is not possible as it is a interface type here which is oneof (Data) but registered as helpers.Mappable so have printed the responseBytes - return clientContext.PrintString(string(responseBytes)) + return cliContext.PrintOutput(response) } return query.cliCommand.CreateCommand(runE) } func (query query) HandleMessage(context sdkTypes.Context, requestQuery abciTypes.RequestQuery) ([]byte, error) { - //Here as no clientContext is recieved through the Handler codec (JSON.Marshaler is not recieved) - //Used LegacyAmino to decode then - request, Error := query.requestPrototype().LegacyAminoDecode(requestQuery.Data) - if Error != nil { - return nil, Error + request, err := query.requestPrototype().Decode(requestQuery.Data) + if err != nil { + return nil, err } - return query.queryKeeper.QueryInKeeper(context, request) + + return query.queryKeeper.Enquire(context, request).Encode() } -func (query query) RESTQueryHandler(cliContext client.Context) http.HandlerFunc { +func (query query) RESTQueryHandler(outerCliContext context.CLIContext) http.HandlerFunc { return func(responseWriter http.ResponseWriter, httpRequest *http.Request) { responseWriter.Header().Set("Content-Type", "application/json") - cliContext, ok := rest.ParseQueryHeightOrReturnBadRequest(responseWriter, cliContext, httpRequest) + cliContext, ok := rest.ParseQueryHeightOrReturnBadRequest(responseWriter, outerCliContext, httpRequest) if !ok { return } - queryRequest := query.requestPrototype().FromMap(mux.Vars(httpRequest)) - response, height, Error := query.query(queryRequest, cliContext) + queryRequest, err := query.requestPrototype().FromMap(mux.Vars(httpRequest)) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusInternalServerError, err.Error()) + return + } - if Error != nil { - rest.WriteErrorResponse(responseWriter, http.StatusInternalServerError, Error.Error()) + response, height, err := query.query(queryRequest, cliContext) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusInternalServerError, err.Error()) return } @@ -113,23 +93,15 @@ func (query query) Initialize(mapper helpers.Mapper, parameters helpers.Paramete return query } -func (query query) RegisterGRPCGatewayRoute(clientContext client.Context, serveMux *runtime.ServeMux) { - query.keeperPrototype().RegisterGRPCGatewayRoute(clientContext, serveMux) -} - -func (query query) query(queryRequest helpers.QueryRequest, cliContext client.Context) ([]byte, int64, error) { - bytes, Error := queryRequest.Encode(cliContext.JSONMarshaler) - if Error != nil { - return nil, 0, Error +func (query query) query(queryRequest helpers.QueryRequest, cliContext context.CLIContext) ([]byte, int64, error) { + bytes, err := queryRequest.Encode() + if err != nil { + return nil, 0, err } return cliContext.QueryWithData("custom"+"/"+query.moduleName+"/"+query.name, bytes) } -func (query query) RegisterService(configurator sdkTypesModule.Configurator) { - query.keeperPrototype().RegisterService(configurator) -} - func NewQuery(name string, short string, long string, moduleName string, requestPrototype func() helpers.QueryRequest, responsePrototype func() helpers.QueryResponse, keeperPrototype func() helpers.QueryKeeper, flagList ...helpers.CLIFlag) helpers.Query { return query{ name: name, diff --git a/schema/helpers/base/query_test.go b/schema/helpers/base/query_test.go index dcabe8758..1a1f8c74d 100644 --- a/schema/helpers/base/query_test.go +++ b/schema/helpers/base/query_test.go @@ -1,18 +1,18 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base import ( - clientContext "github.com/cosmos/cosmos-sdk/client" - "github.com/persistenceOne/persistenceSDK/utilities/test/schema/helpers/base" - "github.com/stretchr/testify/require" - abciTypes "github.com/tendermint/tendermint/abci/types" "net/http" "net/http/httptest" "testing" + + clientContext "github.com/cosmos/cosmos-sdk/client/context" + "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" + + "github.com/AssetMantle/modules/utilities/test/schema/helpers/base" ) func TestQuery(t *testing.T) { @@ -26,35 +26,39 @@ func TestQuery(t *testing.T) { require.Equal(t, nil, base.TestQueryRequestPrototype().Validate()) require.Equal(t, false, base.TestQueryResponsePrototype().IsSuccessful()) require.Equal(t, nil, base.TestQueryResponsePrototype().GetError()) - encodedResponse, Error := base.TestQueryResponsePrototype().LegacyAminoEncode() - require.Nil(t, Error) - decodedResponse, Error := base.TestQueryResponsePrototype().LegacyAminoDecode(encodedResponse) - require.Nil(t, Error) + encodedResponse, err := base.TestQueryResponsePrototype().Encode() + require.Nil(t, err) + decodedResponse, err := base.TestQueryResponsePrototype().Decode(encodedResponse) + require.Nil(t, err) require.Equal(t, Query.responsePrototype(), decodedResponse) // GetName require.Equal(t, "test", Query.GetName()) - // HandleMessageByLegacyAmino - encodedRequest, Error := Query.requestPrototype().LegacyAminoEncode() - require.Nil(t, Error) + // HandleMessage + encodedRequest, err := Query.requestPrototype().Encode() + require.Nil(t, err) - _, Error = Query.HandleMessageByLegacyAmino(context, abciTypes.RequestQuery{Data: encodedRequest}) - require.Nil(t, Error) + _, err = Query.HandleMessage(context, abciTypes.RequestQuery{Data: encodedRequest}) + require.Nil(t, err) command := Query.Command(codec) command.SetArgs([]string{ "test"}) + err = command.ParseFlags([]string{"--node", "tcp://localhost:26657"}) + require.Nil(t, err) require.Equal(t, `ABCIQuery: Post failed: Post "http://localhost:26657": dial tcp 127.0.0.1:26657: connect: connection refused`, command.ExecuteContext(context.Context()).Error()) + // require.Equal(t, nil, command.ExecuteContext(context.Context())) + // RESTQueryHandler cliContext := clientContext.NewCLIContext().WithCodec(codec).WithChainID("test") Query.RESTQueryHandler(cliContext) - //RPC ERROR - testRequest1, Error := http.NewRequest("GET", "/test", nil) - require.Nil(t, Error) + // RPC ERROR + testRequest1, err := http.NewRequest("GET", "/test", nil) + require.Nil(t, err) responseRecorder := httptest.NewRecorder() Query.RESTQueryHandler(cliContext).ServeHTTP(responseRecorder, testRequest1) require.Equal(t, responseRecorder.Code, http.StatusInternalServerError) diff --git a/schema/helpers/base/transaction.go b/schema/helpers/base/transaction.go index 33e35f119..fff0891d8 100644 --- a/schema/helpers/base/transaction.go +++ b/schema/helpers/base/transaction.go @@ -1,25 +1,34 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base import ( + "bufio" "encoding/json" - "github.com/cosmos/cosmos-sdk/client" + "log" + "net/http" + "reflect" + "strings" + + errorConstants "github.com/AssetMantle/modules/schema/errors/constants" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - sdkModule "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/cosmos/cosmos-sdk/x/auth" + authClient "github.com/cosmos/cosmos-sdk/x/auth/client/utils" + "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/spf13/cobra" "github.com/spf13/viper" - "net/http" - "reflect" + + "github.com/AssetMantle/modules/schema/helpers" + "github.com/AssetMantle/modules/utilities/random" + "github.com/AssetMantle/modules/utilities/rest/queuing" ) type transaction struct { @@ -34,28 +43,31 @@ type transaction struct { var _ helpers.Transaction = (*transaction)(nil) func (transaction transaction) GetName() string { return transaction.name } -func (transaction transaction) Command() *cobra.Command { +func (transaction transaction) Command(codec *codec.Codec) *cobra.Command { runE := func(command *cobra.Command, args []string) error { - cliContext, Error := client.GetClientTxContext(command) - if Error != nil { - return Error - } + bufioReader := bufio.NewReader(command.InOrStdin()) + transactionBuilder := auth.NewTxBuilderFromCLI(bufioReader).WithTxEncoder(authClient.GetTxEncoder(codec)) + cliContext := context.NewCLIContextWithInput(bufioReader).WithCodec(codec) - transactionRequest, Error := transaction.requestPrototype().FromCLI(transaction.cliCommand, cliContext) - if Error != nil { - return Error + transactionRequest, err := transaction.requestPrototype().FromCLI(transaction.cliCommand, cliContext) + if err != nil { + return err } - msg, Error := transactionRequest.MakeMsg() - if Error != nil { - return Error + var msg sdkTypes.Msg + if er := transactionRequest.Validate(); er != nil { + return errorConstants.IncorrectFormat + } + msg, err = transactionRequest.MakeMsg() + if err != nil { + return err } - if Error := msg.ValidateBasic(); Error != nil { - return Error + if err = msg.ValidateBasic(); err != nil { + return err } - return tx.GenerateOrBroadcastTxCLI(cliContext, transaction.Command().Flags(), msg) + return authClient.GenerateOrBroadcastMsgs(cliContext, transactionBuilder, []sdkTypes.Msg{msg}) } return transaction.cliCommand.CreateCommand(runE) @@ -69,70 +81,173 @@ func (transaction transaction) HandleMessage(context sdkTypes.Context, message s context.EventManager().EmitEvent( sdkTypes.NewEvent( sdkTypes.EventTypeMessage, - sdkTypes.NewAttribute(sdkTypes.AttributeKeyModule, transaction.name), + sdkTypes.NewAttribute(sdkTypes.AttributeKeyModule, message.Route()), ), ) - return &sdkTypes.Result{Events: context.EventManager().ABCIEvents()}, nil + return &sdkTypes.Result{Events: context.EventManager().Events()}, nil } -func (transaction transaction) RESTRequestHandler(cliContext client.Context) http.HandlerFunc { +func (transaction transaction) RESTRequestHandler(cliContext context.CLIContext) http.HandlerFunc { return func(responseWriter http.ResponseWriter, httpRequest *http.Request) { transactionRequest := transaction.requestPrototype() - if !rest.ReadRESTReq(responseWriter, httpRequest, cliContext.LegacyAmino, &transactionRequest) { + if !rest.ReadRESTReq(responseWriter, httpRequest, cliContext.Codec, &transactionRequest) { return } else if reflect.TypeOf(transaction.requestPrototype()) != reflect.TypeOf(transactionRequest) { rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, "") return } - Error := transactionRequest.Validate() - if Error != nil { - rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, Error.Error()) + err := transactionRequest.Validate() + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) return } baseReq := transactionRequest.GetBaseReq() - msg, Error := transactionRequest.MakeMsg() - // TODO write one method - if Error != nil { - rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, Error.Error()) - return - } - baseReq = baseReq.Sanitize() if !baseReq.ValidateBasic(responseWriter) { rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, "") return } - if Error := msg.ValidateBasic(); Error != nil { - rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, Error.Error()) + var msg sdkTypes.Msg + msg, err = transactionRequest.MakeMsg() + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) + return + } + + if err = msg.ValidateBasic(); err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) return } if viper.GetBool(flags.FlagGenerateOnly) { - tx.WriteGeneratedTxResponse(cliContext, responseWriter, baseReq, msg) + authClient.WriteGenerateStdTxResponse(responseWriter, cliContext, baseReq, []sdkTypes.Msg{msg}) + return + } + + gasAdj, ok := rest.ParseFloat64OrReturnBadRequest(responseWriter, baseReq.GasAdjustment, flags.DefaultGasAdjustment) + if !ok { return } + + var simAndExec bool + var gas uint64 + + simAndExec, gas, err = flags.ParseGas(baseReq.Gas) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) + return + } + + txBuilder := types.NewTxBuilder( + authClient.GetTxEncoder(cliContext.Codec), baseReq.AccountNumber, baseReq.Sequence, gas, gasAdj, + baseReq.Simulate, baseReq.ChainID, baseReq.Memo, baseReq.Fees, baseReq.GasPrices, + ) + msgList := []sdkTypes.Msg{msg} + + if baseReq.Simulate || simAndExec { + if gasAdj < 0 { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, errors.ErrOutOfGas.Error()) + return + } + + txBuilder, err = authClient.EnrichWithGas(txBuilder, cliContext, msgList) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) + return + } + + if baseReq.Simulate { + rest.WriteSimulationResponse(responseWriter, cliContext.Codec, txBuilder.Gas()) + return + } + } + + var fromAddress sdkTypes.AccAddress + var fromName string + + fromAddress, fromName, err = context.GetFromFields(strings.NewReader(keys.DefaultKeyPass), baseReq.From, viper.GetBool(flags.FlagGenerateOnly)) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) + return + } + + cliContext = cliContext.WithFromAddress(fromAddress) + cliContext = cliContext.WithFromName(fromName) + cliContext = cliContext.WithBroadcastMode(viper.GetString(flags.FlagBroadcastMode)) + + if queuing.KafkaState.IsEnabled { + responseWriter.WriteHeader(http.StatusAccepted) + + output := queuing.SendToKafka(queuing.NewKafkaMsgFromRest( + msg, + queuing.TicketID(random.GenerateUniqueIdentifier(transaction.name)), + baseReq, + cliContext), + cliContext.Codec, + ) + + if _, err = responseWriter.Write(output); err != nil { + log.Printf("could not write response: %v", err) + } + } else { + var accountNumber uint64 + var sequence uint64 + + accountNumber, sequence, err = types.NewAccountRetriever(cliContext).GetAccountNumberSequence(fromAddress) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) + return + } + + txBuilder = txBuilder.WithAccountNumber(accountNumber) + txBuilder = txBuilder.WithSequence(sequence) + + var stdMsg []byte + + stdMsg, err = txBuilder.BuildAndSign(fromName, keys.DefaultKeyPass, msgList) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) + return + } + + // broadcast to a node + var response sdkTypes.TxResponse + + response, err = cliContext.BroadcastTx(stdMsg) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) + return + } + + var output []byte + + output, err = cliContext.Codec.MarshalJSON(response) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) + return + } + + responseWriter.Header().Set("Content-Type", "application/json") + if _, err = responseWriter.Write(output); err != nil { + log.Printf("could not write response: %v", err) + } + } } } -func (transaction transaction) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - transaction.messagePrototype().RegisterLegacyAminoCodec(codec) - transaction.requestPrototype().RegisterLegacyAminoCodec(codec) -} -func (transaction transaction) RegisterInterface(registry codecTypes.InterfaceRegistry) { - transaction.messagePrototype().RegisterInterface(registry) -} -func (transaction transaction) RegisterService(configurator sdkModule.Configurator) { - transaction.keeperPrototype().RegisterService(configurator) +func (transaction transaction) RegisterCodec(codec *codec.Codec) { + transaction.messagePrototype().RegisterCodec(codec) + transaction.requestPrototype().RegisterCodec(codec) } func (transaction transaction) DecodeTransactionRequest(rawMessage json.RawMessage) (sdkTypes.Msg, error) { - transactionRequest, Error := transaction.requestPrototype().FromJSON(rawMessage) - if Error != nil { - return nil, Error + transactionRequest, err := transaction.requestPrototype().FromJSON(rawMessage) + if err != nil { + return nil, err } return transactionRequest.MakeMsg() diff --git a/schema/helpers/base/transaction_test.go b/schema/helpers/base/transaction_test.go index 764f7f892..32ef3a9bf 100644 --- a/schema/helpers/base/transaction_test.go +++ b/schema/helpers/base/transaction_test.go @@ -1,23 +1,23 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base import ( "bytes" "encoding/json" - clientContext "github.com/cosmos/cosmos-sdk/client" + "net/http" + "net/http/httptest" + "testing" + + clientContext "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/flags" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/utilities/test/schema/helpers/base" "github.com/spf13/viper" "github.com/stretchr/testify/require" - "net/http" - "net/http/httptest" - "testing" + + "github.com/AssetMantle/modules/utilities/test/schema/helpers/base" ) func TestTransaction(t *testing.T) { @@ -34,77 +34,79 @@ func TestTransaction(t *testing.T) { require.Equal(t, "test", Transaction.GetName()) // DecodeTransactionRequest - message, Error := Transaction.DecodeTransactionRequest(json.RawMessage(`{"BaseReq":{"from":"addr"},"ID":"id"}`)) - require.Equal(t, nil, Error) + message, err := Transaction.DecodeTransactionRequest(json.RawMessage(`{"BaseReq":{"from":"addr"},"ID":"id"}`)) + require.Equal(t, nil, err) require.Equal(t, sdkTypes.AccAddress("addr"), message.GetSigners()[0]) - // RegisterLegacyAminoCodec : No Panics - require.NotPanics(t, func() { Transaction.RegisterLegacyAminoCodec(codec) }) + // RegisterCodec : No Panics + require.NotPanics(t, func() { Transaction.RegisterCodec(codec) }) // Command : No Panics command := Transaction.Command(codec) + err = command.ParseFlags([]string{"--node", "tcp://localhost:26657"}) + require.Nil(t, err) require.Equal(t, `ABCIQuery: Post failed: Post "http://localhost:26657": dial tcp 127.0.0.1:26657: connect: connection refused`, command.ExecuteContext(context.Context()).Error()) - // HandleMessageByLegacyAmino - _, Error = Transaction.HandleMessage(context, message) - require.Nil(t, Error) + // HandleMessage + _, err = Transaction.HandleMessage(context, message) + require.Nil(t, err) // RESTRequestHandler : No Panics cliContext := clientContext.NewCLIContext().WithCodec(codec).WithChainID("test") - //RPC ERROR + // RPC ERROR request1 := codec.MustMarshalJSON(base.TransactionRequest{ BaseReq: rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test"}, ID: "ID", }) - testRequest1, Error := http.NewRequest("GET", "/test", bytes.NewBuffer(request1)) - require.Nil(t, Error) + testRequest1, err := http.NewRequest("GET", "/test", bytes.NewBuffer(request1)) + require.Nil(t, err) responseRecorder := httptest.NewRecorder() Transaction.RESTRequestHandler(cliContext).ServeHTTP(responseRecorder, testRequest1) - require.Equal(t, `{"error":"The specified item could not be found in the keyring"}`, responseRecorder.Body.String()) + require.Equal(t, `{"error":"ABCIQuery: Post failed: Post \"http://localhost:26657\": dial tcp 127.0.0.1:26657: connect: connection refused"}`, responseRecorder.Body.String()) require.Equal(t, http.StatusBadRequest, responseRecorder.Code) - //invalid request + // invalid request request2 := codec.MustMarshalJSON(struct{}{}) - testRequest2, Error := http.NewRequest("GET", "/test", bytes.NewBuffer(request2)) - require.Nil(t, Error) + testRequest2, err := http.NewRequest("GET", "/test", bytes.NewBuffer(request2)) + require.Nil(t, err) responseRecorder = httptest.NewRecorder() Transaction.RESTRequestHandler(cliContext).ServeHTTP(responseRecorder, testRequest2) require.Equal(t, `{"error":"failed to decode JSON payload: JSON encoding of interfaces require non-empty type field."}`, responseRecorder.Body.String()) require.Equal(t, http.StatusBadRequest, responseRecorder.Code) - //validate fail + // validate fail request3 := codec.MustMarshalJSON(base.TransactionRequest{ BaseReq: rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c"}, ID: "ID", }) - testRequest3, Error := http.NewRequest("GET", "/test", bytes.NewBuffer(request3)) - require.Nil(t, Error) + testRequest3, err := http.NewRequest("GET", "/test", bytes.NewBuffer(request3)) + require.Nil(t, err) responseRecorder = httptest.NewRecorder() Transaction.RESTRequestHandler(cliContext).ServeHTTP(responseRecorder, testRequest3) require.Equal(t, `{"error":"chain-id required but not specified"}{"error":""}`, responseRecorder.Body.String()) require.Equal(t, http.StatusUnauthorized, responseRecorder.Code) - //Simulate RPC error + // Simulate RPC error request4 := codec.MustMarshalJSON(base.TransactionRequest{ BaseReq: rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test", Simulate: true}, ID: "ID", }) - testRequest4, Error := http.NewRequest("GET", "/test", bytes.NewBuffer(request4)) - require.Nil(t, Error) + testRequest4, err := http.NewRequest("GET", "/test", bytes.NewBuffer(request4)) + require.Nil(t, err) responseRecorder = httptest.NewRecorder() Transaction.RESTRequestHandler(cliContext).ServeHTTP(responseRecorder, testRequest4) require.Equal(t, `{"error":"ABCIQuery: Post failed: Post \"http://localhost:26657\": dial tcp 127.0.0.1:26657: connect: connection refused"}`, responseRecorder.Body.String()) require.Equal(t, http.StatusBadRequest, responseRecorder.Code) viper.Set(flags.FlagGenerateOnly, true) - //Generate Only + // Generate Only request5 := codec.MustMarshalJSON(base.TransactionRequest{ BaseReq: rest.BaseReq{From: "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c", ChainID: "test"}, ID: "ID", }) - testRequest5, Error := http.NewRequest("GET", "/test", bytes.NewBuffer(request5)) - require.Nil(t, Error) + testRequest5, err := http.NewRequest("GET", "/test", bytes.NewBuffer(request5)) + require.Nil(t, err) responseRecorder = httptest.NewRecorder() Transaction.RESTRequestHandler(cliContext).ServeHTTP(responseRecorder, testRequest5) require.Equal(t, http.StatusOK, responseRecorder.Code) diff --git a/schema/helpers/base/transactions_test.go b/schema/helpers/base/transactions_test.go new file mode 100644 index 000000000..120748317 --- /dev/null +++ b/schema/helpers/base/transactions_test.go @@ -0,0 +1,25 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/helpers" +) + +func TestNewTransactions(t *testing.T) { + Transactions1 := NewTransactions() + Transactions2 := NewTransactions(transaction{}) + + // GetName + require.Equal(t, nil, Transactions1.Get("")) + require.Equal(t, "", Transactions2.Get("").GetName()) + + // Get + require.Equal(t, []helpers.Transaction(nil), Transactions1.GetList()) + require.Equal(t, []helpers.Transaction{transaction{}}, Transactions2.GetList()) +} diff --git a/schema/helpers/base/wasmMessage_test.go b/schema/helpers/base/wasmMessage_test.go new file mode 100644 index 000000000..668d3af73 --- /dev/null +++ b/schema/helpers/base/wasmMessage_test.go @@ -0,0 +1,27 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestWasmMessage(t *testing.T) { + WasmMessage := wasmMessage{ + Type: "testMsg", + RawMessage: json.RawMessage(`{from:tester}`), + } + + // Type + require.Equal(t, "testMsg", WasmMessage.GetType()) + + // GetRawMessage + require.Equal(t, json.RawMessage(`{from:tester}`), WasmMessage.GetRawMessage()) + + // Prototype + require.Equal(t, wasmMessage{}, WasmMessagePrototype()) +} diff --git a/schema/helpers/block.go b/schema/helpers/block.go index ed7030dfe..453e25e13 100644 --- a/schema/helpers/block.go +++ b/schema/helpers/block.go @@ -10,6 +10,6 @@ import ( type Block interface { Begin(sdkTypes.Context, abciTypes.RequestBeginBlock) - End(sdkTypes.Context, abciTypes.RequestEndBlock) []abciTypes.ValidatorUpdate + End(sdkTypes.Context, abciTypes.RequestEndBlock) Initialize(Mapper, Parameters, ...interface{}) Block } diff --git a/schema/helpers/cliCommand.go b/schema/helpers/cliCommand.go index 145fb0053..740efc813 100644 --- a/schema/helpers/cliCommand.go +++ b/schema/helpers/cliCommand.go @@ -4,7 +4,7 @@ package helpers import ( - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/spf13/cobra" ) @@ -14,8 +14,7 @@ type CLICommand interface { ReadInt(CLIFlag) int ReadBool(CLIFlag) bool ReadString(CLIFlag) string - ReadBaseReq(client.Context) rest.BaseReq + ReadBaseReq(context.CLIContext) rest.BaseReq CreateCommand(func(command *cobra.Command, args []string) error) *cobra.Command - CreateQueryCommand() *cobra.Command } diff --git a/schema/helpers/codec.go b/schema/helpers/codec.go index 7b180fd60..ed9e872b4 100644 --- a/schema/helpers/codec.go +++ b/schema/helpers/codec.go @@ -4,7 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { +func RegisterCodec(codec *codec.Codec) { codec.RegisterInterface((*Mappable)(nil), nil) codec.RegisterInterface((*QueryResponse)(nil), nil) codec.RegisterInterface((*QueryRequest)(nil), nil) diff --git a/schema/helpers/codec_test.go b/schema/helpers/codec_test.go new file mode 100644 index 000000000..88c65bea3 --- /dev/null +++ b/schema/helpers/codec_test.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package helpers + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + + {"+ve", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/helpers/genesis.go b/schema/helpers/genesis.go index d296f2234..8954aecf5 100644 --- a/schema/helpers/genesis.go +++ b/schema/helpers/genesis.go @@ -4,23 +4,19 @@ package helpers import ( - "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/gogo/protobuf/proto" "github.com/AssetMantle/modules/schema/parameters" ) type Genesis interface { - proto.Message - Default() Genesis Validate() error Import(sdkTypes.Context, Mapper, Parameters) Export(sdkTypes.Context, Mapper, Parameters) Genesis - Encode(codec.JSONCodec) []byte - Decode(codec.JSONCodec, []byte) Genesis + Encode() []byte + Decode([]byte) Genesis Initialize([]Mappable, []parameters.Parameter) Genesis diff --git a/schema/helpers/grpcConfigurator.go b/schema/helpers/grpcConfigurator.go deleted file mode 100644 index 6f1d3a203..000000000 --- a/schema/helpers/grpcConfigurator.go +++ /dev/null @@ -1,12 +0,0 @@ -package helpers - -import ( - "github.com/cosmos/cosmos-sdk/client" - sdkModuleTypes "github.com/cosmos/cosmos-sdk/types/module" - "github.com/grpc-ecosystem/grpc-gateway/runtime" -) - -type GRPCConfigurator interface { - ConfigureGRPCServer(cfg sdkModuleTypes.Configurator) - ConfigureGRPCGatewayHandler(clientCtx client.Context, mux *runtime.ServeMux) -} diff --git a/schema/helpers/invariants.go b/schema/helpers/invariants.go deleted file mode 100644 index 6b8fd6dde..000000000 --- a/schema/helpers/invariants.go +++ /dev/null @@ -1,9 +0,0 @@ -package helpers - -import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" -) - -type Invariants interface { - RegisterInvariants(sdkTypes.InvariantRegistry) -} diff --git a/schema/helpers/key.go b/schema/helpers/key.go index 5ed13ae38..8066a2a80 100644 --- a/schema/helpers/key.go +++ b/schema/helpers/key.go @@ -1,16 +1,17 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package helpers import "github.com/cosmos/cosmos-sdk/codec" +// Key SHOULD be derivable from the object it is referencing and SHOULD not be totally arbitrary or sequential type Key interface { + String() string GenerateStoreKeyBytes() []byte - RegisterLegacyAminoCodec(amino *codec.LegacyAmino) + // TODO Check is register codec is still required + RegisterCodec(*codec.Codec) IsPartial() bool + // TODO ** check all key impls Equals(Key) bool - GetStructReference() codec.ProtoMarshaler } diff --git a/schema/helpers/mappable.go b/schema/helpers/mappable.go index 67581cf24..4201da02b 100644 --- a/schema/helpers/mappable.go +++ b/schema/helpers/mappable.go @@ -1,25 +1,13 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package helpers import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/schema/types" ) type Mappable interface { GetKey() Key - RegisterLegacyAminoCodec(amino *codec.LegacyAmino) - - types.Proto - Reset() - String() string - ProtoMessage() - Marshal() ([]byte, error) - MarshalToSizedBuffer([]byte) (int, error) - - GetStructReference() codec.ProtoMarshaler + RegisterCodec(*codec.Codec) } diff --git a/schema/helpers/mapper.go b/schema/helpers/mapper.go index b37628c26..d72b7abdb 100644 --- a/schema/helpers/mapper.go +++ b/schema/helpers/mapper.go @@ -4,8 +4,9 @@ package helpers import ( + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/kv" + "github.com/tendermint/tendermint/libs/kv" ) type Mapper interface { @@ -18,7 +19,7 @@ type Mapper interface { Iterate(sdkTypes.Context, Key, func(Mappable) bool) ReverseIterate(sdkTypes.Context, Key, func(Mappable) bool) - StoreDecoder(kv.Pair, kv.Pair) string + StoreDecoder(*codec.Codec, kv.Pair, kv.Pair) string Initialize(*sdkTypes.KVStoreKey) Mapper } diff --git a/schema/helpers/message.go b/schema/helpers/message.go index ba94919a3..ea5087982 100644 --- a/schema/helpers/message.go +++ b/schema/helpers/message.go @@ -1,19 +1,15 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package helpers import ( "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" ) type Message interface { // TODO check if register message code is required - RegisterLegacyAminoCodec(*codec.LegacyAmino) - RegisterInterface(registry codecTypes.InterfaceRegistry) + RegisterCodec(*codec.Codec) sdkTypes.Msg } diff --git a/schema/helpers/migrations.go b/schema/helpers/migrations.go deleted file mode 100644 index b62655c43..000000000 --- a/schema/helpers/migrations.go +++ /dev/null @@ -1,4 +0,0 @@ -package helpers - -type Migrations interface { -} diff --git a/schema/helpers/module.go b/schema/helpers/module.go index 17910dd07..c2e85ad49 100644 --- a/schema/helpers/module.go +++ b/schema/helpers/module.go @@ -8,17 +8,17 @@ import ( sdkTypes "github.com/cosmos/cosmos-sdk/types" sdkTypesModule "github.com/cosmos/cosmos-sdk/types/module" - paramTypes "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/cosmos/cosmos-sdk/x/params" ) type Module interface { - sdkTypesModule.EndBlockAppModule - sdkTypesModule.BeginBlockAppModule + sdkTypesModule.AppModuleBasic + sdkTypesModule.AppModule sdkTypesModule.AppModuleSimulation GetAuxiliary(string) Auxiliary DecodeModuleTransactionRequest(string, json.RawMessage) (sdkTypes.Msg, error) - Initialize(*sdkTypes.KVStoreKey, paramTypes.Subspace, ...interface{}) Module + Initialize(*sdkTypes.KVStoreKey, params.Subspace, ...interface{}) Module } diff --git a/schema/helpers/parameters.go b/schema/helpers/parameters.go index 3a23697d6..36247c95e 100644 --- a/schema/helpers/parameters.go +++ b/schema/helpers/parameters.go @@ -1,14 +1,15 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package helpers import ( sdkTypes "github.com/cosmos/cosmos-sdk/types" - paramTypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/persistenceOne/persistenceSDK/schema/types" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/params/subspace" + + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/parameters" ) type Parameters interface { @@ -17,14 +18,14 @@ type Parameters interface { Validate() error Equal(Parameters) bool - Get(types.ID) types.Parameter - GetList() []types.Parameter + Get(ids.ID) parameters.Parameter + GetList() []parameters.Parameter - Fetch(sdkTypes.Context, types.ID) Parameters - Mutate(sdkTypes.Context, types.Parameter) Parameters + Fetch(sdkTypes.Context, ids.ID) Parameters + Mutate(sdkTypes.Context, parameters.Parameter) Parameters - GetKeyTable() paramTypes.KeyTable - paramTypes.ParamSet + GetKeyTable() subspace.KeyTable + subspace.ParamSet - Initialize(paramTypes.Subspace) Parameters + Initialize(params.Subspace) Parameters } diff --git a/schema/helpers/query.go b/schema/helpers/query.go index 085563f3e..decc03d21 100644 --- a/schema/helpers/query.go +++ b/schema/helpers/query.go @@ -1,16 +1,13 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package helpers import ( - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/grpc-ecosystem/grpc-gateway/runtime" "net/http" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/spf13/cobra" abciTypes "github.com/tendermint/tendermint/abci/types" @@ -18,10 +15,8 @@ import ( type Query interface { GetName() string - Command() *cobra.Command + Command(*codec.Codec) *cobra.Command HandleMessage(sdkTypes.Context, abciTypes.RequestQuery) ([]byte, error) - RESTQueryHandler(client.Context) http.HandlerFunc + RESTQueryHandler(context.CLIContext) http.HandlerFunc Initialize(Mapper, Parameters, ...interface{}) Query - RegisterGRPCGatewayRoute(client.Context, *runtime.ServeMux) - RegisterService(module.Configurator) } diff --git a/schema/helpers/queryKeeper.go b/schema/helpers/queryKeeper.go index 15aca4a7b..f9487ee47 100644 --- a/schema/helpers/queryKeeper.go +++ b/schema/helpers/queryKeeper.go @@ -4,17 +4,10 @@ package helpers import ( - "encoding/json" - "github.com/cosmos/cosmos-sdk/client" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/grpc-ecosystem/grpc-gateway/runtime" ) type QueryKeeper interface { - QueryInKeeper(sdkTypes.Context, QueryRequest) (json.RawMessage, error) - LegacyEnquire(sdkTypes.Context, QueryRequest) QueryResponse - RegisterGRPCGatewayRoute(client.Context, *runtime.ServeMux) - RegisterService(module.Configurator) + Enquire(sdkTypes.Context, QueryRequest) QueryResponse Keeper } diff --git a/schema/helpers/queryRequest.go b/schema/helpers/queryRequest.go index b83afbde0..7834c1771 100644 --- a/schema/helpers/queryRequest.go +++ b/schema/helpers/queryRequest.go @@ -1,21 +1,16 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package helpers import ( - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/client/context" ) type QueryRequest interface { Request - FromCLI(CLICommand, client.Context) QueryRequest - FromMap(map[string]string) QueryRequest - LegacyAminoEncode() ([]byte, error) - LegacyAminoDecode([]byte) (QueryRequest, error) - Encode(codec.JSONMarshaler) ([]byte, error) - Decode(codec.JSONMarshaler, []byte) (QueryRequest, error) + FromCLI(CLICommand, context.CLIContext) (QueryRequest, error) + FromMap(map[string]string) (QueryRequest, error) + Encode() ([]byte, error) + Decode([]byte) (QueryRequest, error) } diff --git a/schema/helpers/queryResponse.go b/schema/helpers/queryResponse.go index b43acc9f2..ff4fc65ba 100644 --- a/schema/helpers/queryResponse.go +++ b/schema/helpers/queryResponse.go @@ -3,19 +3,8 @@ package helpers -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/persistenceOne/persistenceSDK/schema/types" -) - type QueryResponse interface { Response - LegacyAminoEncode() ([]byte, error) - LegacyAminoDecode([]byte) (QueryResponse, error) - Encode(codec.JSONMarshaler) ([]byte, error) - Decode(codec.JSONMarshaler, []byte) (QueryResponse, error) - types.Proto - Reset() - String() string - ProtoMessage() + Encode() ([]byte, error) + Decode([]byte) (QueryResponse, error) } diff --git a/schema/helpers/response.go b/schema/helpers/response.go index 1fe7b9e22..299fa8c7d 100644 --- a/schema/helpers/response.go +++ b/schema/helpers/response.go @@ -3,12 +3,7 @@ package helpers -import ( - "github.com/gogo/protobuf/proto" -) - type Response interface { - proto.Message IsSuccessful() bool - GetError() string + GetError() error } diff --git a/schema/helpers/simulator.go b/schema/helpers/simulator.go index fd561c654..d63444082 100644 --- a/schema/helpers/simulator.go +++ b/schema/helpers/simulator.go @@ -1,22 +1,19 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package helpers import ( - "github.com/cosmos/cosmos-sdk/types/simulation" "math/rand" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/types/module" - simTypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" ) type Simulator interface { RandomizedGenesisState(*module.SimulationState) - WeightedOperations(simTypes.AppParams, codec.JSONMarshaler) simulation.WeightedOperation - WeightedProposalContentList() []simTypes.WeightedProposalContent - ParamChangeList(*rand.Rand) []simTypes.ParamChange + WeightedOperations(simulation.AppParams, *codec.Codec) simulation.WeightedOperations + WeightedProposalContentList() []simulation.WeightedProposalContent + ParamChangeList(*rand.Rand) []simulation.ParamChange } diff --git a/schema/helpers/transaction.go b/schema/helpers/transaction.go index 52c058d19..d75c9dafb 100644 --- a/schema/helpers/transaction.go +++ b/schema/helpers/transaction.go @@ -1,29 +1,24 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package helpers import ( "encoding/json" - "github.com/cosmos/cosmos-sdk/client" + "net/http" + + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" - codecTypes "github.com/cosmos/cosmos-sdk/codec/types" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" "github.com/spf13/cobra" - "net/http" ) type Transaction interface { GetName() string - Command() *cobra.Command + Command(*codec.Codec) *cobra.Command HandleMessage(sdkTypes.Context, sdkTypes.Msg) (*sdkTypes.Result, error) - RESTRequestHandler(client.Context) http.HandlerFunc - RegisterLegacyAminoCodec(*codec.LegacyAmino) - RegisterInterface(registry codecTypes.InterfaceRegistry) + RESTRequestHandler(context.CLIContext) http.HandlerFunc + RegisterCodec(*codec.Codec) DecodeTransactionRequest(json.RawMessage) (sdkTypes.Msg, error) InitializeKeeper(Mapper, Parameters, ...interface{}) Transaction - RegisterService(module.Configurator) } diff --git a/schema/helpers/transactionKeeper.go b/schema/helpers/transactionKeeper.go index f1c8b610c..6fd067326 100644 --- a/schema/helpers/transactionKeeper.go +++ b/schema/helpers/transactionKeeper.go @@ -3,13 +3,9 @@ package helpers -import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - sdkModule "github.com/cosmos/cosmos-sdk/types/module" -) +import sdkTypes "github.com/cosmos/cosmos-sdk/types" type TransactionKeeper interface { Transact(sdkTypes.Context, sdkTypes.Msg) TransactionResponse - RegisterService(sdkModule.Configurator) Keeper } diff --git a/schema/helpers/transactionRequest.go b/schema/helpers/transactionRequest.go index 87f1514cf..3bb3767d7 100644 --- a/schema/helpers/transactionRequest.go +++ b/schema/helpers/transactionRequest.go @@ -1,14 +1,12 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package helpers import ( "encoding/json" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" @@ -17,9 +15,9 @@ import ( type TransactionRequest interface { GetBaseReq() rest.BaseReq - FromCLI(CLICommand, client.Context) (TransactionRequest, error) + FromCLI(CLICommand, context.CLIContext) (TransactionRequest, error) FromJSON(json.RawMessage) (TransactionRequest, error) MakeMsg() (sdkTypes.Msg, error) - RegisterLegacyAminoCodec(*codec.LegacyAmino) + RegisterCodec(*codec.Codec) Request } diff --git a/schema/ids/base/assetID.go b/schema/ids/base/assetID.go index 9c8545004..0577eac78 100644 --- a/schema/ids/base/assetID.go +++ b/schema/ids/base/assetID.go @@ -8,50 +8,52 @@ import ( errorConstants "github.com/AssetMantle/modules/schema/errors/constants" "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/qualified" "github.com/AssetMantle/modules/schema/traits" ) -var _ ids.AssetID = (*ID_AssetID)(nil) - -func (assetID *ID_AssetID) String() string { - return assetID.AssetID.String() +type assetID struct { + ids.HashID } -func (assetID *ID_AssetID) Compare(listable traits.Listable) int { - return bytes.Compare(assetID.Bytes(), idFromInterface(listable).Bytes()) -} -func (assetID *ID_AssetID) IsOwnableID() {} -func (assetID *ID_AssetID) IsAssetID() {} -func (assetID *ID_AssetID) Bytes() []byte { - return assetID.AssetID.HashId.IdBytes -} +var _ ids.AssetID = (*assetID)(nil) -func NewAssetID(hashID ids.ID) ids.ID { - if hashID.(*ID).GetHashID() == nil { +func (assetID assetID) IsOwnableID() {} +func (assetID assetID) IsAssetID() {} +func (assetID assetID) Compare(listable traits.Listable) int { + // TODO devise a better strategy to compare assetID and ownableID + return bytes.Compare(assetID.Bytes(), ownableIDFromInterface(listable).Bytes()) +} +func assetIDFromInterface(i interface{}) assetID { + switch value := i.(type) { + case assetID: + return value + default: panic(errorConstants.MetaDataError) } - - return &ID{ - Impl: &ID_AssetID{ - AssetID: &AssetID{ - HashId: hashID.(*ID).GetHashID(), - }, - }, +} +func NewAssetID(classificationID ids.ClassificationID, immutables qualified.Immutables) ids.AssetID { + return assetID{ + HashID: GenerateHashID(classificationID.Bytes(), immutables.GenerateHashID().Bytes()), } } -func PrototypeAssetID() ids.ID { - return NewAssetID(PrototypeHashID()) +func PrototypeAssetID() ids.AssetID { + return assetID{ + HashID: PrototypeHashID(), + } } -func ReadAssetID(assetIDString string) (ids.ID, error) { +func ReadAssetID(assetIDString string) (ids.AssetID, error) { if hashID, err := ReadHashID(assetIDString); err == nil { - return NewAssetID(hashID), nil + return assetID{ + HashID: hashID, + }, nil } if assetIDString == "" { return PrototypeAssetID(), nil } - return PrototypeAssetID(), errorConstants.MetaDataError + return assetID{}, errorConstants.MetaDataError } diff --git a/schema/ids/base/assetID.pb.go b/schema/ids/base/assetID.pb.go deleted file mode 100644 index 67e866f32..000000000 --- a/schema/ids/base/assetID.pb.go +++ /dev/null @@ -1,327 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/ids/base/assetID.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type AssetID struct { - HashId *HashID `protobuf:"bytes,1,opt,name=hash_id,json=hashId,proto3" json:"hash_id,omitempty"` -} - -func (m *AssetID) Reset() { *m = AssetID{} } -func (m *AssetID) String() string { return proto.CompactTextString(m) } -func (*AssetID) ProtoMessage() {} -func (*AssetID) Descriptor() ([]byte, []int) { - return fileDescriptor_a0af5def2c9908f6, []int{0} -} -func (m *AssetID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AssetID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AssetID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *AssetID) XXX_Merge(src proto.Message) { - xxx_messageInfo_AssetID.Merge(m, src) -} -func (m *AssetID) XXX_Size() int { - return m.Size() -} -func (m *AssetID) XXX_DiscardUnknown() { - xxx_messageInfo_AssetID.DiscardUnknown(m) -} - -var xxx_messageInfo_AssetID proto.InternalMessageInfo - -func (m *AssetID) GetHashId() *HashID { - if m != nil { - return m.HashId - } - return nil -} - -func init() { - proto.RegisterType((*AssetID)(nil), "base.AssetID") -} - -func init() { proto.RegisterFile("schema/ids/base/assetID.proto", fileDescriptor_a0af5def2c9908f6) } - -var fileDescriptor_a0af5def2c9908f6 = []byte{ - // 223 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2d, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0xcf, 0x4c, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x4f, 0x2c, 0x2e, 0x4e, - 0x2d, 0xf1, 0x74, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x89, 0x49, 0xc9, 0xa0, - 0x2b, 0xca, 0x48, 0x2c, 0xce, 0x80, 0xa9, 0x51, 0x32, 0xe0, 0x62, 0x77, 0x84, 0x68, 0x12, 0x52, - 0xe5, 0x62, 0x07, 0x49, 0xc5, 0x67, 0xa6, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x1b, 0xf1, 0xe8, - 0x81, 0xd4, 0xeb, 0x79, 0x80, 0xd5, 0x07, 0xb1, 0x81, 0xf5, 0xa5, 0x38, 0x4d, 0x60, 0x3c, 0xf1, - 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, - 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x06, 0x2e, 0x8e, 0xe4, 0xfc, 0x5c, 0xb0, 0x1e, 0x27, - 0x1e, 0xa8, 0xa1, 0x01, 0x20, 0x4b, 0x02, 0x18, 0xa3, 0xf4, 0xd2, 0x33, 0x4b, 0x32, 0x4a, 0x93, - 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0xc1, 0x52, 0xbe, 0x89, 0x79, 0x25, 0x39, 0xa9, 0xfa, 0xb9, 0xf9, - 0x29, 0xa5, 0x39, 0xa9, 0xc5, 0xfa, 0x68, 0x6e, 0x5c, 0xc4, 0xc4, 0xec, 0x14, 0x11, 0xb1, 0x8a, - 0x89, 0xc5, 0x29, 0xb1, 0x38, 0xf5, 0x14, 0x84, 0x7a, 0xc4, 0x24, 0x00, 0xa2, 0x62, 0xdc, 0x03, - 0x9c, 0x7c, 0x53, 0x4b, 0x12, 0x53, 0x12, 0x4b, 0x12, 0x5f, 0x41, 0x64, 0x92, 0xd8, 0xc0, 0x7e, - 0x31, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x16, 0x0c, 0xb9, 0x81, 0x10, 0x01, 0x00, 0x00, -} - -func (m *AssetID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AssetID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AssetID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.HashId != nil { - { - size, err := m.HashId.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAssetID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintAssetID(dAtA []byte, offset int, v uint64) int { - offset -= sovAssetID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *AssetID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.HashId != nil { - l = m.HashId.Size() - n += 1 + l + sovAssetID(uint64(l)) - } - return n -} - -func sovAssetID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozAssetID(x uint64) (n int) { - return sovAssetID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *AssetID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAssetID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AssetID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AssetID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HashId", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAssetID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAssetID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAssetID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.HashId == nil { - m.HashId = &HashID{} - } - if err := m.HashId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAssetID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAssetID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipAssetID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAssetID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAssetID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAssetID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthAssetID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupAssetID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthAssetID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthAssetID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowAssetID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupAssetID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/ids/base/assetID.proto b/schema/ids/base/assetID.proto deleted file mode 100644 index dcfd007f5..000000000 --- a/schema/ids/base/assetID.proto +++ /dev/null @@ -1,7 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/ids/base/hashID.proto"; -message AssetID{ - base.HashID hash_id = 1; -} \ No newline at end of file diff --git a/schema/ids/base/classificationID.pb.go b/schema/ids/base/classificationID.pb.go deleted file mode 100644 index a71b9bb96..000000000 --- a/schema/ids/base/classificationID.pb.go +++ /dev/null @@ -1,330 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/ids/base/classificationID.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type ClassificationID struct { - HashId *HashID `protobuf:"bytes,1,opt,name=hash_id,json=hashId,proto3" json:"hash_id,omitempty"` -} - -func (m *ClassificationID) Reset() { *m = ClassificationID{} } -func (m *ClassificationID) String() string { return proto.CompactTextString(m) } -func (*ClassificationID) ProtoMessage() {} -func (*ClassificationID) Descriptor() ([]byte, []int) { - return fileDescriptor_ba3a2d33b92d6743, []int{0} -} -func (m *ClassificationID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ClassificationID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ClassificationID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *ClassificationID) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClassificationID.Merge(m, src) -} -func (m *ClassificationID) XXX_Size() int { - return m.Size() -} -func (m *ClassificationID) XXX_DiscardUnknown() { - xxx_messageInfo_ClassificationID.DiscardUnknown(m) -} - -var xxx_messageInfo_ClassificationID proto.InternalMessageInfo - -func (m *ClassificationID) GetHashId() *HashID { - if m != nil { - return m.HashId - } - return nil -} - -func init() { - proto.RegisterType((*ClassificationID)(nil), "base.ClassificationID") -} - -func init() { - proto.RegisterFile("schema/ids/base/classificationID.proto", fileDescriptor_ba3a2d33b92d6743) -} - -var fileDescriptor_ba3a2d33b92d6743 = []byte{ - // 236 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2b, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0xcf, 0x4c, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x4f, 0xce, 0x49, 0x2c, - 0x2e, 0xce, 0x4c, 0xcb, 0x4c, 0x4e, 0x2c, 0xc9, 0xcc, 0xcf, 0xf3, 0x74, 0xd1, 0x2b, 0x28, 0xca, - 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x49, 0x4a, 0xc9, 0xa0, 0xab, 0xce, 0x48, 0x2c, 0xce, 0x80, 0xa9, - 0x51, 0xb2, 0xe4, 0x12, 0x70, 0x46, 0xd3, 0x2d, 0xa4, 0xca, 0xc5, 0x0e, 0x52, 0x13, 0x9f, 0x99, - 0x22, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0x6d, 0xc4, 0xa3, 0x07, 0xd2, 0xa8, 0xe7, 0x01, 0xd6, 0x18, - 0xc4, 0x06, 0x36, 0x20, 0xc5, 0x69, 0x26, 0xe3, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, 0x31, - 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, 0xcb, - 0x31, 0x70, 0x71, 0x24, 0xe7, 0xe7, 0x82, 0xf5, 0x38, 0x89, 0xa2, 0x9b, 0x1e, 0x00, 0xb2, 0x36, - 0x80, 0x31, 0x4a, 0x2f, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0xdf, 0xb1, - 0xb8, 0x38, 0xb5, 0xc4, 0x37, 0x31, 0xaf, 0x24, 0x27, 0x55, 0x3f, 0x37, 0x3f, 0xa5, 0x34, 0x27, - 0xb5, 0x58, 0x1f, 0xcd, 0xd5, 0x8b, 0x98, 0x98, 0x9d, 0x22, 0x22, 0x56, 0x31, 0xb1, 0x38, 0x25, - 0x16, 0xa7, 0x9e, 0x82, 0x50, 0x8f, 0x98, 0x04, 0x40, 0x54, 0x8c, 0x7b, 0x80, 0x93, 0x6f, 0x6a, - 0x49, 0x62, 0x4a, 0x62, 0x49, 0xe2, 0x2b, 0x88, 0x4c, 0x12, 0x1b, 0xd8, 0x77, 0xc6, 0x80, 0x00, - 0x00, 0x00, 0xff, 0xff, 0x13, 0xdd, 0x68, 0x27, 0x2b, 0x01, 0x00, 0x00, -} - -func (m *ClassificationID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ClassificationID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ClassificationID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.HashId != nil { - { - size, err := m.HashId.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintClassificationID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintClassificationID(dAtA []byte, offset int, v uint64) int { - offset -= sovClassificationID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *ClassificationID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.HashId != nil { - l = m.HashId.Size() - n += 1 + l + sovClassificationID(uint64(l)) - } - return n -} - -func sovClassificationID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozClassificationID(x uint64) (n int) { - return sovClassificationID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *ClassificationID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClassificationID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ClassificationID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ClassificationID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HashId", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowClassificationID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthClassificationID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthClassificationID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.HashId == nil { - m.HashId = &HashID{} - } - if err := m.HashId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipClassificationID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthClassificationID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipClassificationID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowClassificationID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowClassificationID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowClassificationID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthClassificationID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupClassificationID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthClassificationID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthClassificationID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowClassificationID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupClassificationID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/ids/base/classificationID.proto b/schema/ids/base/classificationID.proto deleted file mode 100644 index 7362abfba..000000000 --- a/schema/ids/base/classificationID.proto +++ /dev/null @@ -1,8 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/ids/base/hashID.proto"; - -message ClassificationID { - base.HashID hash_id = 1; -} \ No newline at end of file diff --git a/schema/ids/base/codec.go b/schema/ids/base/codec.go index 922c322e2..95ef433e4 100644 --- a/schema/ids/base/codec.go +++ b/schema/ids/base/codec.go @@ -6,19 +6,19 @@ package base import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/AssetMantle/modules/schema" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { - schema.RegisterModuleConcrete(codec, AssetID{}) - schema.RegisterModuleConcrete(codec, ClassificationID{}) - schema.RegisterModuleConcrete(codec, DataID{}) - schema.RegisterModuleConcrete(codec, HashID{}) - schema.RegisterModuleConcrete(codec, IdentityID{}) - schema.RegisterModuleConcrete(codec, MaintainerID{}) - schema.RegisterModuleConcrete(codec, OrderID{}) - schema.RegisterModuleConcrete(codec, OwnableID{}) - schema.RegisterModuleConcrete(codec, PropertyID{}) - schema.RegisterModuleConcrete(codec, SplitID{}) - schema.RegisterModuleConcrete(codec, StringID{}) +func RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, assetID{}) + codecUtilities.RegisterModuleConcrete(codec, classificationID{}) + codecUtilities.RegisterModuleConcrete(codec, dataID{}) + codecUtilities.RegisterModuleConcrete(codec, hashID{}) + codecUtilities.RegisterModuleConcrete(codec, identityID{}) + codecUtilities.RegisterModuleConcrete(codec, maintainerID{}) + codecUtilities.RegisterModuleConcrete(codec, orderID{}) + codecUtilities.RegisterModuleConcrete(codec, ownableID{}) + codecUtilities.RegisterModuleConcrete(codec, propertyID{}) + codecUtilities.RegisterModuleConcrete(codec, splitID{}) + codecUtilities.RegisterModuleConcrete(codec, stringID{}) } diff --git a/schema/ids/base/codec_test.go b/schema/ids/base/codec_test.go new file mode 100644 index 000000000..f8fde6322 --- /dev/null +++ b/schema/ids/base/codec_test.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + + {"+ve", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/ids/base/dataID.go b/schema/ids/base/dataID.go index f212b2b72..9b1da6c01 100644 --- a/schema/ids/base/dataID.go +++ b/schema/ids/base/dataID.go @@ -13,52 +13,66 @@ import ( "github.com/AssetMantle/modules/schema/traits" ) -var _ ids.DataID = (*ID_DataID)(nil) +type dataID struct { + Type ids.StringID + ids.HashID +} + +var _ ids.DataID = (*dataID)(nil) -func (dataID *ID_DataID) IsDataID() { +func (dataID dataID) IsDataID() { } -func (dataID *ID_DataID) String() string { - return stringUtilities.JoinIDStrings(dataID.DataID.Type.String(), dataID.DataID.HashId.String()) +func (dataID dataID) String() string { + return stringUtilities.JoinIDStrings(dataID.Type.String(), dataID.HashID.String()) } -func (dataID *ID_DataID) Bytes() []byte { - return append([]byte(dataID.DataID.Type.IdString), dataID.DataID.HashId.IdBytes...) +func (dataID dataID) Bytes() []byte { + var Bytes []byte + Bytes = append(Bytes, dataID.Type.Bytes()...) + Bytes = append(Bytes, dataID.HashID.Bytes()...) + + return Bytes } -func (dataID *ID_DataID) Compare(listable traits.Listable) int { - return bytes.Compare(dataID.Bytes(), idFromInterface(listable).Bytes()) +func (dataID dataID) Compare(listable traits.Listable) int { + return bytes.Compare(dataID.Bytes(), dataIDFromInterface(listable).Bytes()) } -func (dataID *ID_DataID) GetHashID() ids.ID { - return &ID{Impl: &ID_HashID{HashID: dataID.DataID.HashId}} +func (dataID dataID) GetHashID() ids.HashID { + return dataID.HashID } - -func GenerateDataID(data data.Data) ids.ID { - if data == nil { +func dataIDFromInterface(i interface{}) dataID { + switch value := i.(type) { + case dataID: + return value + default: panic(errorConstants.MetaDataError) } - return NewDataID(data.GetType(), data.GenerateHashID()) } -func NewDataID(Type ids.ID, hashID ids.ID) ids.ID { - if Type.(*ID).GetStringID() == nil || hashID.(*ID).GetHashID() == nil { + +func NewDataID(data data.Data) ids.DataID { + if data == nil { panic(errorConstants.MetaDataError) } - return &ID{ - Impl: &ID_DataID{ - DataID: &DataID{ - Type: Type.(*ID).GetStringID(), - HashId: hashID.(*ID).GetHashID(), - }, - }, + + return dataID{ + Type: data.GetType(), + HashID: data.GenerateHashID(), } } -func PrototypeDataID() ids.ID { - return NewDataID(PrototypeStringID(), PrototypeHashID()) +func PrototypeDataID() ids.DataID { + return dataID{ + Type: PrototypeStringID(), + HashID: PrototypeHashID(), + } } -func ReadDataID(dataIDString string) (ids.ID, error) { +func ReadDataID(dataIDString string) (ids.DataID, error) { if typeAndHashIDString := stringUtilities.SplitCompositeIDString(dataIDString); len(typeAndHashIDString) == 2 { Type := NewStringID(typeAndHashIDString[0]) if hashID, err := ReadHashID(typeAndHashIDString[1]); err == nil { - return NewDataID(Type, hashID), nil + return dataID{ + Type: Type, + HashID: hashID, + }, nil } } @@ -66,5 +80,5 @@ func ReadDataID(dataIDString string) (ids.ID, error) { return PrototypeDataID(), nil } - return PrototypeDataID(), errorConstants.MetaDataError + return dataID{}, errorConstants.MetaDataError } diff --git a/schema/ids/base/dataID.pb.go b/schema/ids/base/dataID.pb.go deleted file mode 100644 index bd5fa3002..000000000 --- a/schema/ids/base/dataID.pb.go +++ /dev/null @@ -1,389 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/ids/base/dataID.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type DataID struct { - Type *StringID `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` - HashId *HashID `protobuf:"bytes,2,opt,name=hash_id,json=hashId,proto3" json:"hash_id,omitempty"` -} - -func (m *DataID) Reset() { *m = DataID{} } -func (m *DataID) String() string { return proto.CompactTextString(m) } -func (*DataID) ProtoMessage() {} -func (*DataID) Descriptor() ([]byte, []int) { - return fileDescriptor_b4e894a7250baa7c, []int{0} -} -func (m *DataID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DataID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DataID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DataID) XXX_Merge(src proto.Message) { - xxx_messageInfo_DataID.Merge(m, src) -} -func (m *DataID) XXX_Size() int { - return m.Size() -} -func (m *DataID) XXX_DiscardUnknown() { - xxx_messageInfo_DataID.DiscardUnknown(m) -} - -var xxx_messageInfo_DataID proto.InternalMessageInfo - -func (m *DataID) GetType() *StringID { - if m != nil { - return m.Type - } - return nil -} - -func (m *DataID) GetHashId() *HashID { - if m != nil { - return m.HashId - } - return nil -} - -func init() { - proto.RegisterType((*DataID)(nil), "base.DataID") -} - -func init() { proto.RegisterFile("schema/ids/base/dataID.proto", fileDescriptor_b4e894a7250baa7c) } - -var fileDescriptor_b4e894a7250baa7c = []byte{ - // 256 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x29, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0xcf, 0x4c, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x4f, 0x49, 0x2c, 0x49, - 0xf4, 0x74, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x09, 0x49, 0x61, 0xa8, 0xc9, - 0x48, 0x2c, 0xce, 0x80, 0xa9, 0x91, 0x92, 0x43, 0x97, 0x2d, 0x2e, 0x29, 0xca, 0xcc, 0x4b, 0x87, - 0xc9, 0x2b, 0x05, 0x73, 0xb1, 0xb9, 0x80, 0xcd, 0x14, 0x52, 0xe2, 0x62, 0x29, 0xa9, 0x2c, 0x48, - 0x95, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x36, 0xe2, 0xd3, 0x03, 0xa9, 0xd6, 0x0b, 0x86, 0xaa, 0x0e, - 0x02, 0xcb, 0x09, 0xa9, 0x72, 0xb1, 0x83, 0x4c, 0x8f, 0xcf, 0x4c, 0x91, 0x60, 0x02, 0x2b, 0xe3, - 0x81, 0x28, 0xf3, 0x00, 0x5b, 0x19, 0xc4, 0x06, 0xb6, 0x3a, 0xc5, 0xa9, 0x9f, 0xf1, 0xc4, 0x23, - 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, - 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xb8, 0x38, 0x92, 0xf3, 0x73, 0xc1, 0x7a, 0x9c, 0xb8, - 0x21, 0xf6, 0x06, 0x80, 0x9c, 0x11, 0xc0, 0x18, 0xa5, 0x97, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, - 0x97, 0x9c, 0x9f, 0xab, 0xef, 0x58, 0x5c, 0x9c, 0x5a, 0xe2, 0x9b, 0x98, 0x57, 0x92, 0x93, 0xaa, - 0x9f, 0x9b, 0x9f, 0x52, 0x9a, 0x93, 0x5a, 0xac, 0x8f, 0xe6, 0x8f, 0x45, 0x4c, 0xcc, 0x4e, 0x11, - 0x11, 0xab, 0x98, 0x58, 0x9c, 0x12, 0x8b, 0x53, 0x4f, 0x41, 0xa8, 0x47, 0x4c, 0x02, 0x20, 0x2a, - 0xc6, 0x3d, 0xc0, 0xc9, 0x37, 0xb5, 0x24, 0x11, 0x14, 0x56, 0xaf, 0x20, 0x32, 0x49, 0x6c, 0x60, - 0xdf, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xc6, 0xe7, 0x9d, 0xfd, 0x51, 0x01, 0x00, 0x00, -} - -func (m *DataID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DataID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DataID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.HashId != nil { - { - size, err := m.HashId.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintDataID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if m.Type != nil { - { - size, err := m.Type.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintDataID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintDataID(dAtA []byte, offset int, v uint64) int { - offset -= sovDataID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *DataID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Type != nil { - l = m.Type.Size() - n += 1 + l + sovDataID(uint64(l)) - } - if m.HashId != nil { - l = m.HashId.Size() - n += 1 + l + sovDataID(uint64(l)) - } - return n -} - -func sovDataID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozDataID(x uint64) (n int) { - return sovDataID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *DataID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDataID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DataID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DataID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDataID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthDataID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthDataID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Type == nil { - m.Type = &StringID{} - } - if err := m.Type.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HashId", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDataID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthDataID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthDataID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.HashId == nil { - m.HashId = &HashID{} - } - if err := m.HashId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipDataID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDataID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipDataID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowDataID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowDataID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowDataID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthDataID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupDataID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthDataID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthDataID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowDataID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupDataID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/ids/base/dataID.proto b/schema/ids/base/dataID.proto deleted file mode 100644 index 6ec5aa045..000000000 --- a/schema/ids/base/dataID.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/ids/base/hashID.proto"; -import "schema/ids/base/stringID.proto"; - -message DataID { - base.StringID type = 1; - base.HashID hash_id = 2; -} \ No newline at end of file diff --git a/schema/ids/base/dataID_test.go b/schema/ids/base/dataID_test.go index ea9cfef36..5802f50fa 100644 --- a/schema/ids/base/dataID_test.go +++ b/schema/ids/base/dataID_test.go @@ -4,12 +4,13 @@ package base import ( - "github.com/AssetMantle/modules/schema/errors/constants" - stringUtilities "github.com/AssetMantle/modules/schema/ids/utilities" "reflect" "strconv" "testing" + "github.com/AssetMantle/modules/schema/errors/constants" + stringUtilities "github.com/AssetMantle/modules/schema/ids/utilities" + "github.com/AssetMantle/modules/schema/data" "github.com/AssetMantle/modules/schema/traits" diff --git a/schema/ids/base/hashID.go b/schema/ids/base/hashID.go index 6e23fcf2b..98a16324b 100644 --- a/schema/ids/base/hashID.go +++ b/schema/ids/base/hashID.go @@ -11,23 +11,35 @@ import ( "github.com/AssetMantle/modules/schema/traits" ) -var _ ids.HashID = (*ID_HashID)(nil) - -func (hashID *ID_HashID) String() string { - return (hashID).String() +type hashID struct { + HashBytes []byte } -func (hashID *ID_HashID) IsHashID() {} +var _ ids.HashID = (*hashID)(nil) + +func (hashID hashID) IsHashID() {} -func (hashID *ID_HashID) Bytes() []byte { - return hashID.HashID.IdBytes +// TODO test if nil and empty result in "" +func (hashID hashID) String() string { + return base64.URLEncoding.EncodeToString(hashID.HashBytes) +} +func (hashID hashID) Bytes() []byte { + return hashID.HashBytes +} +func (hashID hashID) Compare(listable traits.Listable) int { + return bytes.Compare(hashID.Bytes(), hashIDFromInterface(listable).Bytes()) } -func (hashID *ID_HashID) Compare(listable traits.Listable) int { - return bytes.Compare(hashID.Bytes(), idFromInterface(listable).Bytes()) +func hashIDFromInterface(i interface{}) hashID { + switch value := i.(type) { + case hashID: + return value + default: + panic(constants.MetaDataError) + } } // TODO test -func GenerateHashID(toHashList ...[]byte) ids.ID { +func GenerateHashID(toHashList ...[]byte) ids.HashID { var nonEmptyByteList [][]byte for _, value := range toHashList { @@ -37,7 +49,7 @@ func GenerateHashID(toHashList ...[]byte) ids.ID { } if len(nonEmptyByteList) == 0 { - return NewHashID(nil) + return hashID{HashBytes: nil} } sort.Slice(nonEmptyByteList, func(i, j int) bool { return bytes.Compare(nonEmptyByteList[i], nonEmptyByteList[j]) == -1 }) @@ -49,29 +61,21 @@ func GenerateHashID(toHashList ...[]byte) ids.ID { panic(err) } - return NewHashID(hash.Sum(nil)) -} -func NewHashID(idBytes []byte) ids.ID { - return &ID{ - Impl: &ID_HashID{ - HashID: &HashID{ - IdBytes: idBytes, - }, - }, - } + return hashID{HashBytes: hash.Sum(nil)} } -func PrototypeHashID() ids.ID { + +func PrototypeHashID() ids.HashID { return GenerateHashID() } -func ReadHashID(hashIDString string) (ids.ID, error) { +func ReadHashID(hashIDString string) (ids.HashID, error) { if hashBytes, err := base64.URLEncoding.DecodeString(hashIDString); err == nil { - return NewHashID(hashBytes), nil + return hashID{HashBytes: hashBytes}, nil } if hashIDString == "" { return nil, nil } - return PrototypeHashID(), constants.IncorrectFormat + return hashID{}, constants.IncorrectFormat } diff --git a/schema/ids/base/hashID.pb.go b/schema/ids/base/hashID.pb.go deleted file mode 100644 index 63e81fdcb..000000000 --- a/schema/ids/base/hashID.pb.go +++ /dev/null @@ -1,320 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/ids/base/hashID.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type HashID struct { - IdBytes []byte `protobuf:"bytes,1,opt,name=id_bytes,json=idBytes,proto3" json:"id_bytes,omitempty"` -} - -func (m *HashID) Reset() { *m = HashID{} } -func (m *HashID) String() string { return proto.CompactTextString(m) } -func (*HashID) ProtoMessage() {} -func (*HashID) Descriptor() ([]byte, []int) { - return fileDescriptor_b5b26fb89c75ae02, []int{0} -} -func (m *HashID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *HashID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_HashID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *HashID) XXX_Merge(src proto.Message) { - xxx_messageInfo_HashID.Merge(m, src) -} -func (m *HashID) XXX_Size() int { - return m.Size() -} -func (m *HashID) XXX_DiscardUnknown() { - xxx_messageInfo_HashID.DiscardUnknown(m) -} - -var xxx_messageInfo_HashID proto.InternalMessageInfo - -func (m *HashID) GetIdBytes() []byte { - if m != nil { - return m.IdBytes - } - return nil -} - -func init() { - proto.RegisterType((*HashID)(nil), "base.HashID") -} - -func init() { proto.RegisterFile("schema/ids/base/hashID.proto", fileDescriptor_b5b26fb89c75ae02) } - -var fileDescriptor_b5b26fb89c75ae02 = []byte{ - // 212 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x29, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0xcf, 0x4c, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x48, 0x2c, 0xce, - 0xf0, 0x74, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x09, 0x29, 0x29, 0x73, 0xb1, - 0x79, 0x80, 0x45, 0x85, 0x24, 0xb9, 0x38, 0x32, 0x53, 0xe2, 0x93, 0x2a, 0x4b, 0x52, 0x8b, 0x25, - 0x18, 0x15, 0x18, 0x35, 0x78, 0x82, 0xd8, 0x33, 0x53, 0x9c, 0x40, 0x5c, 0xa7, 0x7e, 0xc6, 0x13, - 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, - 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0xe0, 0xe2, 0x48, 0xce, 0xcf, 0xd5, 0x03, 0x99, - 0xe4, 0xc4, 0x0d, 0x31, 0x27, 0x00, 0x64, 0x78, 0x00, 0x63, 0x94, 0x5e, 0x7a, 0x66, 0x49, 0x46, - 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0xbe, 0x63, 0x71, 0x71, 0x6a, 0x89, 0x6f, 0x62, 0x5e, 0x49, - 0x4e, 0xaa, 0x7e, 0x6e, 0x7e, 0x4a, 0x69, 0x4e, 0x6a, 0xb1, 0x3e, 0x9a, 0xdb, 0x16, 0x31, 0x31, - 0x3b, 0x45, 0x44, 0xac, 0x62, 0x62, 0x71, 0x4a, 0x2c, 0x4e, 0x3d, 0x05, 0xa1, 0x1e, 0x31, 0x09, - 0x80, 0xa8, 0x18, 0xf7, 0x00, 0x27, 0xdf, 0xd4, 0x92, 0xc4, 0x94, 0xc4, 0x92, 0xc4, 0x57, 0x10, - 0x99, 0x24, 0x36, 0xb0, 0x1f, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x13, 0x76, 0x5a, 0x91, - 0xe3, 0x00, 0x00, 0x00, -} - -func (m *HashID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *HashID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *HashID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.IdBytes) > 0 { - i -= len(m.IdBytes) - copy(dAtA[i:], m.IdBytes) - i = encodeVarintHashID(dAtA, i, uint64(len(m.IdBytes))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintHashID(dAtA []byte, offset int, v uint64) int { - offset -= sovHashID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *HashID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.IdBytes) - if l > 0 { - n += 1 + l + sovHashID(uint64(l)) - } - return n -} - -func sovHashID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozHashID(x uint64) (n int) { - return sovHashID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *HashID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHashID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: HashID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: HashID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IdBytes", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHashID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthHashID - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthHashID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IdBytes = append(m.IdBytes[:0], dAtA[iNdEx:postIndex]...) - if m.IdBytes == nil { - m.IdBytes = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHashID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHashID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipHashID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHashID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHashID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHashID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthHashID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupHashID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthHashID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthHashID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowHashID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupHashID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/ids/base/hashID.proto b/schema/ids/base/hashID.proto deleted file mode 100644 index ccb4f7033..000000000 --- a/schema/ids/base/hashID.proto +++ /dev/null @@ -1,8 +0,0 @@ -syntax = "proto3"; -package base; - - -message HashID { - bytes id_bytes = 1; -} - diff --git a/schema/ids/base/hashID_test.go b/schema/ids/base/hashID_test.go new file mode 100644 index 000000000..279fc9493 --- /dev/null +++ b/schema/ids/base/hashID_test.go @@ -0,0 +1,34 @@ +package base + +import ( + "reflect" + "testing" + + "github.com/AssetMantle/modules/schema/ids" +) + +func TestReadHashID(t *testing.T) { + type args struct { + hashIDString string + } + tests := []struct { + name string + args args + want ids.HashID + wantErr bool + }{ + {name: "empty string", args: args{""}, want: hashID{[]uint8{}}, wantErr: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := ReadHashID(tt.args.hashIDString) + if (err != nil) != tt.wantErr { + t.Errorf("ReadHashID() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("ReadHashID() got = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/schema/ids/base/id.go b/schema/ids/base/id.go deleted file mode 100644 index 3a1cf1845..000000000 --- a/schema/ids/base/id.go +++ /dev/null @@ -1,25 +0,0 @@ -package base - -import ( - "github.com/AssetMantle/modules/schema/errors/constants" - "github.com/AssetMantle/modules/schema/ids" - "github.com/AssetMantle/modules/schema/traits" -) - -var _ ids.ID = (*ID)(nil) - -func (id *ID) Compare(listable traits.Listable) int { - return id.Impl.(ids.ID).Compare(listable) -} -func (id *ID) Bytes() []byte { - return id.Impl.(ids.ID).Bytes() -} - -func idFromInterface(i interface{}) ids.ID { - switch value := i.(type) { - case ids.ID: - return value - default: - panic(constants.MetaDataError) - } -} diff --git a/schema/ids/base/id.pb.go b/schema/ids/base/id.pb.go deleted file mode 100644 index 931f3b67a..000000000 --- a/schema/ids/base/id.pb.go +++ /dev/null @@ -1,1212 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/ids/base/id.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type ID struct { - // Types that are valid to be assigned to Impl: - // *ID_AssetID - // *ID_ClassificationID - // *ID_DataID - // *ID_HashID - // *ID_IdentityID - // *ID_MaintainerID - // *ID_OrderID - // *ID_OwnableID - // *ID_PropertyID - // *ID_SplitID - // *ID_StringID - Impl isID_Impl `protobuf_oneof:"impl"` -} - -func (m *ID) Reset() { *m = ID{} } -func (m *ID) String() string { return proto.CompactTextString(m) } -func (*ID) ProtoMessage() {} -func (*ID) Descriptor() ([]byte, []int) { - return fileDescriptor_bc51a45246f20284, []int{0} -} -func (m *ID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *ID) XXX_Merge(src proto.Message) { - xxx_messageInfo_ID.Merge(m, src) -} -func (m *ID) XXX_Size() int { - return m.Size() -} -func (m *ID) XXX_DiscardUnknown() { - xxx_messageInfo_ID.DiscardUnknown(m) -} - -var xxx_messageInfo_ID proto.InternalMessageInfo - -type isID_Impl interface { - isID_Impl() - MarshalTo([]byte) (int, error) - Size() int -} - -type ID_AssetID struct { - AssetID *AssetID `protobuf:"bytes,1,opt,name=AssetID,proto3,oneof" json:"AssetID,omitempty"` -} -type ID_ClassificationID struct { - ClassificationID *ClassificationID `protobuf:"bytes,2,opt,name=ClassificationID,proto3,oneof" json:"ClassificationID,omitempty"` -} -type ID_DataID struct { - DataID *DataID `protobuf:"bytes,3,opt,name=DataID,proto3,oneof" json:"DataID,omitempty"` -} -type ID_HashID struct { - HashID *HashID `protobuf:"bytes,4,opt,name=HashID,proto3,oneof" json:"HashID,omitempty"` -} -type ID_IdentityID struct { - IdentityID *IdentityID `protobuf:"bytes,5,opt,name=IdentityID,proto3,oneof" json:"IdentityID,omitempty"` -} -type ID_MaintainerID struct { - MaintainerID *MaintainerID `protobuf:"bytes,6,opt,name=MaintainerID,proto3,oneof" json:"MaintainerID,omitempty"` -} -type ID_OrderID struct { - OrderID *OrderID `protobuf:"bytes,7,opt,name=OrderID,proto3,oneof" json:"OrderID,omitempty"` -} -type ID_OwnableID struct { - OwnableID *OwnableID `protobuf:"bytes,8,opt,name=OwnableID,proto3,oneof" json:"OwnableID,omitempty"` -} -type ID_PropertyID struct { - PropertyID *PropertyID `protobuf:"bytes,9,opt,name=PropertyID,proto3,oneof" json:"PropertyID,omitempty"` -} -type ID_SplitID struct { - SplitID *SplitID `protobuf:"bytes,10,opt,name=SplitID,proto3,oneof" json:"SplitID,omitempty"` -} -type ID_StringID struct { - StringID *StringID `protobuf:"bytes,11,opt,name=StringID,proto3,oneof" json:"StringID,omitempty"` -} - -func (*ID_AssetID) isID_Impl() {} -func (*ID_ClassificationID) isID_Impl() {} -func (*ID_DataID) isID_Impl() {} -func (*ID_HashID) isID_Impl() {} -func (*ID_IdentityID) isID_Impl() {} -func (*ID_MaintainerID) isID_Impl() {} -func (*ID_OrderID) isID_Impl() {} -func (*ID_OwnableID) isID_Impl() {} -func (*ID_PropertyID) isID_Impl() {} -func (*ID_SplitID) isID_Impl() {} -func (*ID_StringID) isID_Impl() {} - -func (m *ID) GetImpl() isID_Impl { - if m != nil { - return m.Impl - } - return nil -} - -func (m *ID) GetAssetID() *AssetID { - if x, ok := m.GetImpl().(*ID_AssetID); ok { - return x.AssetID - } - return nil -} - -func (m *ID) GetClassificationID() *ClassificationID { - if x, ok := m.GetImpl().(*ID_ClassificationID); ok { - return x.ClassificationID - } - return nil -} - -func (m *ID) GetDataID() *DataID { - if x, ok := m.GetImpl().(*ID_DataID); ok { - return x.DataID - } - return nil -} - -func (m *ID) GetHashID() *HashID { - if x, ok := m.GetImpl().(*ID_HashID); ok { - return x.HashID - } - return nil -} - -func (m *ID) GetIdentityID() *IdentityID { - if x, ok := m.GetImpl().(*ID_IdentityID); ok { - return x.IdentityID - } - return nil -} - -func (m *ID) GetMaintainerID() *MaintainerID { - if x, ok := m.GetImpl().(*ID_MaintainerID); ok { - return x.MaintainerID - } - return nil -} - -func (m *ID) GetOrderID() *OrderID { - if x, ok := m.GetImpl().(*ID_OrderID); ok { - return x.OrderID - } - return nil -} - -func (m *ID) GetOwnableID() *OwnableID { - if x, ok := m.GetImpl().(*ID_OwnableID); ok { - return x.OwnableID - } - return nil -} - -func (m *ID) GetPropertyID() *PropertyID { - if x, ok := m.GetImpl().(*ID_PropertyID); ok { - return x.PropertyID - } - return nil -} - -func (m *ID) GetSplitID() *SplitID { - if x, ok := m.GetImpl().(*ID_SplitID); ok { - return x.SplitID - } - return nil -} - -func (m *ID) GetStringID() *StringID { - if x, ok := m.GetImpl().(*ID_StringID); ok { - return x.StringID - } - return nil -} - -// XXX_OneofWrappers is for the internal use of the proto package. -func (*ID) XXX_OneofWrappers() []interface{} { - return []interface{}{ - (*ID_AssetID)(nil), - (*ID_ClassificationID)(nil), - (*ID_DataID)(nil), - (*ID_HashID)(nil), - (*ID_IdentityID)(nil), - (*ID_MaintainerID)(nil), - (*ID_OrderID)(nil), - (*ID_OwnableID)(nil), - (*ID_PropertyID)(nil), - (*ID_SplitID)(nil), - (*ID_StringID)(nil), - } -} - -func init() { - proto.RegisterType((*ID)(nil), "ids.ID") -} - -func init() { proto.RegisterFile("schema/ids/base/id.proto", fileDescriptor_bc51a45246f20284) } - -var fileDescriptor_bc51a45246f20284 = []byte{ - // 501 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x93, 0xcd, 0x6e, 0xd3, 0x40, - 0x14, 0x85, 0xc7, 0x4e, 0x48, 0xda, 0x69, 0xa1, 0xd5, 0x2c, 0xd0, 0xa8, 0x02, 0x53, 0x75, 0x51, - 0x81, 0x84, 0x6c, 0xa9, 0x6c, 0xd8, 0x12, 0x22, 0x61, 0x2f, 0xa2, 0x46, 0xee, 0xa6, 0x42, 0x6c, - 0x26, 0x9e, 0xa1, 0x19, 0xc9, 0x7f, 0xf2, 0x4c, 0x85, 0x78, 0x01, 0xd6, 0x3c, 0x03, 0x62, 0xc5, - 0x93, 0x20, 0x56, 0x5d, 0xb2, 0x44, 0xc9, 0x8e, 0xa7, 0x40, 0xf3, 0x13, 0x7b, 0xb0, 0xd5, 0x4d, - 0x34, 0x39, 0xe7, 0xbb, 0xca, 0xbd, 0xf7, 0xdc, 0x40, 0x2c, 0xb2, 0x35, 0x2b, 0x48, 0xc4, 0xa9, - 0x88, 0x56, 0x44, 0xb0, 0x88, 0xd3, 0xb0, 0x6e, 0x2a, 0x59, 0xa1, 0x11, 0xa7, 0xe2, 0xe4, 0x69, - 0xdf, 0x26, 0x42, 0x30, 0x99, 0xcc, 0x0d, 0x73, 0x72, 0xde, 0xb7, 0xb3, 0x9c, 0x08, 0xc1, 0x3f, - 0xf2, 0x8c, 0x48, 0x5e, 0x95, 0x2d, 0xf7, 0xa4, 0xcf, 0x51, 0x22, 0xc9, 0xfd, 0xee, 0x9a, 0x88, - 0x75, 0xeb, 0x9e, 0x0e, 0x3b, 0x64, 0xa5, 0xe4, 0xf2, 0x73, 0x4b, 0x9c, 0xf5, 0x89, 0x82, 0xf0, - 0x52, 0x12, 0x5e, 0xb2, 0xa6, 0x65, 0x06, 0x83, 0x54, 0x0d, 0x75, 0xec, 0x67, 0x03, 0xfb, 0x53, - 0x49, 0x56, 0x39, 0xbb, 0xbf, 0x8b, 0xba, 0xa9, 0x6a, 0xd6, 0x38, 0x5d, 0x0c, 0x7e, 0x41, 0xd4, - 0x39, 0xef, 0x56, 0x15, 0x0c, 0x6c, 0xd9, 0xf0, 0xf2, 0x66, 0xe7, 0x9f, 0x7d, 0x1f, 0x43, 0x3f, - 0x99, 0xa3, 0x17, 0x70, 0xfa, 0xc6, 0xac, 0x18, 0x7b, 0xa7, 0xde, 0xf3, 0x83, 0x8b, 0x87, 0xa1, - 0xa2, 0x43, 0x2b, 0xc6, 0x20, 0xdd, 0xf9, 0x68, 0x0e, 0x8f, 0xdf, 0xf6, 0xd6, 0x8d, 0x7d, 0x5d, - 0xf3, 0xd8, 0xd4, 0xf4, 0xdd, 0x18, 0xa4, 0x83, 0x0a, 0x74, 0x0e, 0x27, 0x73, 0x1d, 0x06, 0x1e, - 0xe9, 0xda, 0x43, 0x53, 0x6b, 0xb4, 0x18, 0xa4, 0xd6, 0x55, 0x5c, 0xac, 0x63, 0xc1, 0x63, 0x97, - 0x33, 0x9a, 0xe2, 0xcc, 0x0b, 0x5d, 0x40, 0x98, 0xb4, 0x01, 0xe1, 0x07, 0x9a, 0x3d, 0x36, 0x6c, - 0xa7, 0xc7, 0x20, 0x75, 0x28, 0xf4, 0x1a, 0x1e, 0x2e, 0x9c, 0xc8, 0xf0, 0x44, 0x57, 0x21, 0x53, - 0xe5, 0x3a, 0x31, 0x48, 0xff, 0x23, 0xd5, 0xba, 0x2e, 0x4d, 0x90, 0x78, 0xea, 0xae, 0xcb, 0x8a, - 0x6a, 0x5d, 0xf6, 0x89, 0x22, 0xb8, 0x7f, 0xb9, 0x0b, 0x15, 0xef, 0x69, 0xf8, 0xc8, 0xc2, 0x3b, - 0x39, 0x06, 0x69, 0xc7, 0xa8, 0x49, 0x96, 0x6d, 0xc8, 0x78, 0xdf, 0x9d, 0xa4, 0xd3, 0xd5, 0x24, - 0xdd, 0x37, 0xd5, 0xcf, 0x95, 0x89, 0x1d, 0x43, 0xb7, 0x1f, 0x2b, 0xaa, 0x7e, 0xec, 0x13, 0xbd, - 0x84, 0x7b, 0x57, 0xf6, 0x04, 0xf0, 0x81, 0x66, 0x1f, 0x59, 0xd6, 0xaa, 0x31, 0x48, 0x5b, 0x62, - 0x36, 0x81, 0x63, 0x5e, 0xd4, 0xf9, 0xec, 0x8b, 0xf7, 0x73, 0x13, 0x78, 0x77, 0x9b, 0xc0, 0xfb, - 0xb3, 0x09, 0xbc, 0xaf, 0xdb, 0x00, 0xdc, 0x6d, 0x03, 0xf0, 0x7b, 0x1b, 0x00, 0x38, 0xcd, 0xaa, - 0x22, 0xe4, 0x54, 0xcc, 0xa6, 0x09, 0x5d, 0xaa, 0x9b, 0x5a, 0x7a, 0xef, 0xc3, 0x1b, 0x2e, 0xd7, - 0xb7, 0xab, 0x30, 0xab, 0x8a, 0x48, 0xdf, 0xcd, 0x82, 0x94, 0x32, 0x67, 0x51, 0x51, 0xd1, 0xdb, - 0x9c, 0x89, 0xa8, 0x77, 0x94, 0xdf, 0xfc, 0x51, 0x72, 0x7d, 0xfd, 0xc3, 0x1f, 0x25, 0x54, 0xfc, - 0xd2, 0x9f, 0x1b, 0xff, 0x28, 0xa1, 0xe2, 0xc3, 0xbb, 0xe5, 0x6c, 0xc1, 0x24, 0x51, 0x7f, 0xdb, - 0xbf, 0x5a, 0x5f, 0x4d, 0xf4, 0xd9, 0xbe, 0xfa, 0x17, 0x00, 0x00, 0xff, 0xff, 0x92, 0xa4, 0x13, - 0x47, 0x41, 0x04, 0x00, 0x00, -} - -func (m *ID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Impl != nil { - { - size := m.Impl.Size() - i -= size - if _, err := m.Impl.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - } - } - return len(dAtA) - i, nil -} - -func (m *ID_AssetID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ID_AssetID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.AssetID != nil { - { - size, err := m.AssetID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintId(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} -func (m *ID_ClassificationID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ID_ClassificationID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.ClassificationID != nil { - { - size, err := m.ClassificationID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintId(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - return len(dAtA) - i, nil -} -func (m *ID_DataID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ID_DataID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.DataID != nil { - { - size, err := m.DataID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintId(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - return len(dAtA) - i, nil -} -func (m *ID_HashID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ID_HashID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.HashID != nil { - { - size, err := m.HashID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintId(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - return len(dAtA) - i, nil -} -func (m *ID_IdentityID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ID_IdentityID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.IdentityID != nil { - { - size, err := m.IdentityID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintId(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - return len(dAtA) - i, nil -} -func (m *ID_MaintainerID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ID_MaintainerID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.MaintainerID != nil { - { - size, err := m.MaintainerID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintId(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - return len(dAtA) - i, nil -} -func (m *ID_OrderID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ID_OrderID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.OrderID != nil { - { - size, err := m.OrderID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintId(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - return len(dAtA) - i, nil -} -func (m *ID_OwnableID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ID_OwnableID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.OwnableID != nil { - { - size, err := m.OwnableID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintId(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - return len(dAtA) - i, nil -} -func (m *ID_PropertyID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ID_PropertyID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.PropertyID != nil { - { - size, err := m.PropertyID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintId(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - } - return len(dAtA) - i, nil -} -func (m *ID_SplitID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ID_SplitID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.SplitID != nil { - { - size, err := m.SplitID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintId(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - } - return len(dAtA) - i, nil -} -func (m *ID_StringID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ID_StringID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.StringID != nil { - { - size, err := m.StringID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintId(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x5a - } - return len(dAtA) - i, nil -} -func encodeVarintId(dAtA []byte, offset int, v uint64) int { - offset -= sovId(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *ID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Impl != nil { - n += m.Impl.Size() - } - return n -} - -func (m *ID_AssetID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.AssetID != nil { - l = m.AssetID.Size() - n += 1 + l + sovId(uint64(l)) - } - return n -} -func (m *ID_ClassificationID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.ClassificationID != nil { - l = m.ClassificationID.Size() - n += 1 + l + sovId(uint64(l)) - } - return n -} -func (m *ID_DataID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.DataID != nil { - l = m.DataID.Size() - n += 1 + l + sovId(uint64(l)) - } - return n -} -func (m *ID_HashID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.HashID != nil { - l = m.HashID.Size() - n += 1 + l + sovId(uint64(l)) - } - return n -} -func (m *ID_IdentityID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.IdentityID != nil { - l = m.IdentityID.Size() - n += 1 + l + sovId(uint64(l)) - } - return n -} -func (m *ID_MaintainerID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.MaintainerID != nil { - l = m.MaintainerID.Size() - n += 1 + l + sovId(uint64(l)) - } - return n -} -func (m *ID_OrderID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.OrderID != nil { - l = m.OrderID.Size() - n += 1 + l + sovId(uint64(l)) - } - return n -} -func (m *ID_OwnableID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.OwnableID != nil { - l = m.OwnableID.Size() - n += 1 + l + sovId(uint64(l)) - } - return n -} -func (m *ID_PropertyID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PropertyID != nil { - l = m.PropertyID.Size() - n += 1 + l + sovId(uint64(l)) - } - return n -} -func (m *ID_SplitID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.SplitID != nil { - l = m.SplitID.Size() - n += 1 + l + sovId(uint64(l)) - } - return n -} -func (m *ID_StringID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.StringID != nil { - l = m.StringID.Size() - n += 1 + l + sovId(uint64(l)) - } - return n -} - -func sovId(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozId(x uint64) (n int) { - return sovId(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *ID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AssetID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthId - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthId - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &AssetID{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &ID_AssetID{v} - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClassificationID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthId - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthId - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &ClassificationID{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &ID_ClassificationID{v} - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DataID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthId - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthId - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &DataID{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &ID_DataID{v} - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HashID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthId - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthId - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &HashID{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &ID_HashID{v} - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IdentityID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthId - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthId - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &IdentityID{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &ID_IdentityID{v} - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MaintainerID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthId - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthId - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &MaintainerID{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &ID_MaintainerID{v} - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OrderID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthId - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthId - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &OrderID{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &ID_OrderID{v} - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OwnableID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthId - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthId - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &OwnableID{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &ID_OwnableID{v} - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PropertyID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthId - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthId - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &PropertyID{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &ID_PropertyID{v} - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SplitID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthId - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthId - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &SplitID{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &ID_SplitID{v} - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StringID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthId - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthId - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &StringID{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &ID_StringID{v} - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipId(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthId - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipId(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowId - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowId - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowId - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthId - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupId - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthId - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthId = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowId = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupId = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/ids/base/id.proto b/schema/ids/base/id.proto deleted file mode 100644 index ff2ad327c..000000000 --- a/schema/ids/base/id.proto +++ /dev/null @@ -1,30 +0,0 @@ -syntax = "proto3"; -package ids; - -import "schema/ids/base/assetID.proto"; -import "schema/ids/base/classificationID.proto"; -import "schema/ids/base/dataID.proto"; -import "schema/ids/base/hashID.proto"; -import "schema/ids/base/identityID.proto"; -import "schema/ids/base/maintainerID.proto"; -import "schema/ids/base/orderID.proto"; -import "schema/ids/base/ownableID.proto"; -import "schema/ids/base/propertyID.proto"; -import "schema/ids/base/splitID.proto"; -import "schema/ids/base/stringID.proto"; - -message ID { - oneof impl { - base.AssetID AssetID = 1; - base.ClassificationID ClassificationID = 2; - base.DataID DataID = 3; - base.HashID HashID = 4; - base.IdentityID IdentityID = 5; - base.MaintainerID MaintainerID = 6; - base.OrderID OrderID = 7; - base.OwnableID OwnableID = 8; - base.PropertyID PropertyID = 9; - base.SplitID SplitID = 10; - base.StringID StringID = 11; - } -} \ No newline at end of file diff --git a/schema/ids/base/identityID.go b/schema/ids/base/identityID.go index 1d1a74181..ca46a7195 100644 --- a/schema/ids/base/identityID.go +++ b/schema/ids/base/identityID.go @@ -1,54 +1,60 @@ package base import ( - "bytes" - errorConstants "github.com/AssetMantle/modules/schema/errors/constants" "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/qualified" "github.com/AssetMantle/modules/schema/traits" ) -var _ ids.IdentityID = (*ID_IdentityID)(nil) - -func (identityID *ID_IdentityID) String() string { - return identityID.IdentityID.HashId.String() +type identityID struct { + ids.HashID } -// TODO deprecate -func (identityID *ID_IdentityID) IsIdentityID() {} +var _ ids.IdentityID = (*identityID)(nil) -func (identityID *ID_IdentityID) Bytes() []byte { - return identityID.IdentityID.HashId.IdBytes +// TODO deprecate +func (identityID identityID) IsIdentityID() {} +func (identityID identityID) String() string { + return identityID.HashID.String() } -func (identityID *ID_IdentityID) Compare(listable traits.Listable) int { - return bytes.Compare(identityID.Bytes(), idFromInterface(listable).Bytes()) +func (identityID identityID) Bytes() []byte { + return identityID.HashID.Bytes() } -func (identityID *ID_IdentityID) GetHashID() ids.ID { - return &ID{Impl: &ID_HashID{HashID: identityID.IdentityID.HashId}} +func (identityID identityID) Compare(listable traits.Listable) int { + return identityID.HashID.Compare(identityIDFromInterface(listable).HashID) } - -func NewIdentityID(hashID ids.ID) ids.ID { - if hashID.(*ID).GetHashID() == nil { +func (identityID identityID) GetHashID() ids.HashID { + return identityID.HashID +} +func identityIDFromInterface(i interface{}) identityID { + switch value := i.(type) { + case identityID: + return value + default: panic(errorConstants.MetaDataError) } - return &ID{ - Impl: &ID_IdentityID{ - IdentityID: &IdentityID{ - HashId: hashID.(*ID).GetHashID(), - }, - }, +} + +func NewIdentityID(classificationID ids.ClassificationID, immutables qualified.Immutables) ids.IdentityID { + return identityID{ + HashID: GenerateHashID(classificationID.Bytes(), immutables.GenerateHashID().Bytes()), } } -func PrototypeIdentityID() ids.ID { - return NewIdentityID(PrototypeHashID()) +func PrototypeIdentityID() ids.IdentityID { + return identityID{ + HashID: PrototypeHashID(), + } } -func ReadIdentityID(identityIDString string) (ids.ID, error) { +func ReadIdentityID(identityIDString string) (ids.IdentityID, error) { if hashID, err := ReadHashID(identityIDString); err == nil { - return NewIdentityID(hashID), nil + return identityID{ + HashID: hashID, + }, nil } - return PrototypeIdentityID(), errorConstants.IncorrectFormat + return identityID{}, errorConstants.IncorrectFormat } diff --git a/schema/ids/base/identityID.pb.go b/schema/ids/base/identityID.pb.go deleted file mode 100644 index b0c8688be..000000000 --- a/schema/ids/base/identityID.pb.go +++ /dev/null @@ -1,328 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/ids/base/identityID.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type IdentityID struct { - HashId *HashID `protobuf:"bytes,1,opt,name=hash_id,json=hashId,proto3" json:"hash_id,omitempty"` -} - -func (m *IdentityID) Reset() { *m = IdentityID{} } -func (m *IdentityID) String() string { return proto.CompactTextString(m) } -func (*IdentityID) ProtoMessage() {} -func (*IdentityID) Descriptor() ([]byte, []int) { - return fileDescriptor_a48bfddf3d6758a2, []int{0} -} -func (m *IdentityID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *IdentityID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_IdentityID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *IdentityID) XXX_Merge(src proto.Message) { - xxx_messageInfo_IdentityID.Merge(m, src) -} -func (m *IdentityID) XXX_Size() int { - return m.Size() -} -func (m *IdentityID) XXX_DiscardUnknown() { - xxx_messageInfo_IdentityID.DiscardUnknown(m) -} - -var xxx_messageInfo_IdentityID proto.InternalMessageInfo - -func (m *IdentityID) GetHashId() *HashID { - if m != nil { - return m.HashId - } - return nil -} - -func init() { - proto.RegisterType((*IdentityID)(nil), "base.IdentityID") -} - -func init() { proto.RegisterFile("schema/ids/base/identityID.proto", fileDescriptor_a48bfddf3d6758a2) } - -var fileDescriptor_a48bfddf3d6758a2 = []byte{ - // 229 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x28, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0xcf, 0x4c, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x4c, 0x49, 0xcd, - 0x2b, 0xc9, 0x2c, 0xa9, 0xf4, 0x74, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x09, - 0x4b, 0xc9, 0xa0, 0xab, 0xcb, 0x48, 0x2c, 0xce, 0x80, 0xa9, 0x51, 0x32, 0xe6, 0xe2, 0xf2, 0x84, - 0xeb, 0x13, 0x52, 0xe5, 0x62, 0x07, 0xc9, 0xc6, 0x67, 0xa6, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0x70, - 0x1b, 0xf1, 0xe8, 0x81, 0xb4, 0xe8, 0x79, 0x80, 0xb5, 0x04, 0xb1, 0x81, 0xb5, 0xa6, 0x38, 0x4d, - 0x66, 0x3c, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, - 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x06, 0x2e, 0x8e, 0xe4, 0xfc, 0x5c, - 0xb0, 0x1e, 0x27, 0x7e, 0x84, 0xb9, 0x01, 0x20, 0xab, 0x02, 0x18, 0xa3, 0xf4, 0xd2, 0x33, 0x4b, - 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x1d, 0x8b, 0x8b, 0x53, 0x4b, 0x7c, 0x13, 0xf3, - 0x4a, 0x72, 0x52, 0xf5, 0x73, 0xf3, 0x53, 0x4a, 0x73, 0x52, 0x8b, 0xf5, 0xd1, 0x5c, 0xba, 0x88, - 0x89, 0xd9, 0x29, 0x22, 0x62, 0x15, 0x13, 0x8b, 0x53, 0x62, 0x71, 0xea, 0x29, 0x08, 0xf5, 0x88, - 0x49, 0x00, 0x44, 0xc5, 0xb8, 0x07, 0x38, 0xf9, 0xa6, 0x96, 0x24, 0xa6, 0x24, 0x96, 0x24, 0xbe, - 0x82, 0xc8, 0x24, 0xb1, 0x81, 0x7d, 0x64, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x95, 0xc6, 0xad, - 0xb8, 0x19, 0x01, 0x00, 0x00, -} - -func (m *IdentityID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *IdentityID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *IdentityID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.HashId != nil { - { - size, err := m.HashId.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintIdentityID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintIdentityID(dAtA []byte, offset int, v uint64) int { - offset -= sovIdentityID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *IdentityID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.HashId != nil { - l = m.HashId.Size() - n += 1 + l + sovIdentityID(uint64(l)) - } - return n -} - -func sovIdentityID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozIdentityID(x uint64) (n int) { - return sovIdentityID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *IdentityID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIdentityID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: IdentityID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: IdentityID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HashId", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIdentityID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthIdentityID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthIdentityID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.HashId == nil { - m.HashId = &HashID{} - } - if err := m.HashId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipIdentityID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthIdentityID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipIdentityID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdentityID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdentityID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdentityID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthIdentityID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupIdentityID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthIdentityID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthIdentityID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowIdentityID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupIdentityID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/ids/base/identityID.proto b/schema/ids/base/identityID.proto deleted file mode 100644 index 235906b73..000000000 --- a/schema/ids/base/identityID.proto +++ /dev/null @@ -1,8 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/ids/base/hashID.proto"; - -message IdentityID{ - base.HashID hash_id = 1; -} \ No newline at end of file diff --git a/schema/ids/base/maintainerID.go b/schema/ids/base/maintainerID.go index 6f528e52c..18dc90ff6 100644 --- a/schema/ids/base/maintainerID.go +++ b/schema/ids/base/maintainerID.go @@ -1,50 +1,52 @@ package base import ( - "bytes" - errorConstants "github.com/AssetMantle/modules/schema/errors/constants" "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/qualified" "github.com/AssetMantle/modules/schema/traits" ) -var _ ids.MaintainerID = (*ID_MaintainerID)(nil) - -func (maintainerID *ID_MaintainerID) IsMaintainerID() {} -func (maintainerID *ID_MaintainerID) String() string { - return maintainerID.MaintainerID.String() +type maintainerID struct { + ids.HashID } -func (maintainerID *ID_MaintainerID) Bytes() []byte { - return maintainerID.MaintainerID.HashId.IdBytes -} -func (maintainerID *ID_MaintainerID) Compare(listable traits.Listable) int { - return bytes.Compare(maintainerID.Bytes(), idFromInterface(listable).Bytes()) + +var _ ids.MaintainerID = (*maintainerID)(nil) + +func (maintainerID maintainerID) IsMaintainerID() {} +func (maintainerID maintainerID) Compare(listable traits.Listable) int { + return maintainerID.HashID.Compare(maintainerIDFromInterface(listable).HashID) } -func NewMaintainerID(hashID ids.ID) ids.ID { - if hashID.(*ID).GetHashID() == nil { +func maintainerIDFromInterface(i interface{}) maintainerID { + switch value := i.(type) { + case maintainerID: + return value + default: panic(errorConstants.MetaDataError) } - return &ID{ - Impl: &ID_MaintainerID{ - MaintainerID: &MaintainerID{ - HashId: hashID.(*ID).GetHashID(), - }, - }, +} +func NewMaintainerID(classificationID ids.ClassificationID, immutables qualified.Immutables) ids.MaintainerID { + return maintainerID{ + HashID: GenerateHashID(classificationID.Bytes(), immutables.GenerateHashID().Bytes()), } } -func PrototypeMaintainerID() ids.ID { - return NewMaintainerID(PrototypeHashID()) +func PrototypeMaintainerID() ids.MaintainerID { + return maintainerID{ + HashID: PrototypeHashID(), + } } -func ReadMaintainerID(maintainerIDString string) (ids.ID, error) { +func ReadMaintainerID(maintainerIDString string) (ids.MaintainerID, error) { if hashID, err := ReadHashID(maintainerIDString); err == nil { - return NewMaintainerID(hashID), nil + return maintainerID{ + HashID: hashID, + }, nil } if maintainerIDString == "" { return PrototypeMaintainerID(), nil } - return PrototypeMaintainerID(), errorConstants.MetaDataError + return maintainerID{}, errorConstants.MetaDataError } diff --git a/schema/ids/base/maintainerID.pb.go b/schema/ids/base/maintainerID.pb.go deleted file mode 100644 index f0053102c..000000000 --- a/schema/ids/base/maintainerID.pb.go +++ /dev/null @@ -1,330 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/ids/base/maintainerID.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type MaintainerID struct { - HashId *HashID `protobuf:"bytes,1,opt,name=hash_id,json=hashId,proto3" json:"hash_id,omitempty"` -} - -func (m *MaintainerID) Reset() { *m = MaintainerID{} } -func (m *MaintainerID) String() string { return proto.CompactTextString(m) } -func (*MaintainerID) ProtoMessage() {} -func (*MaintainerID) Descriptor() ([]byte, []int) { - return fileDescriptor_4dd25e9eb86d64c3, []int{0} -} -func (m *MaintainerID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MaintainerID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MaintainerID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MaintainerID) XXX_Merge(src proto.Message) { - xxx_messageInfo_MaintainerID.Merge(m, src) -} -func (m *MaintainerID) XXX_Size() int { - return m.Size() -} -func (m *MaintainerID) XXX_DiscardUnknown() { - xxx_messageInfo_MaintainerID.DiscardUnknown(m) -} - -var xxx_messageInfo_MaintainerID proto.InternalMessageInfo - -func (m *MaintainerID) GetHashId() *HashID { - if m != nil { - return m.HashId - } - return nil -} - -func init() { - proto.RegisterType((*MaintainerID)(nil), "base.MaintainerID") -} - -func init() { - proto.RegisterFile("schema/ids/base/maintainerID.proto", fileDescriptor_4dd25e9eb86d64c3) -} - -var fileDescriptor_4dd25e9eb86d64c3 = []byte{ - // 231 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2a, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0xcf, 0x4c, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x4d, 0xcc, 0xcc, - 0x2b, 0x49, 0xcc, 0xcc, 0x4b, 0x2d, 0xf2, 0x74, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, - 0x01, 0x49, 0x48, 0xc9, 0xa0, 0xab, 0xcc, 0x48, 0x2c, 0xce, 0x80, 0xa9, 0x51, 0x32, 0xe5, 0xe2, - 0xf1, 0x45, 0xd2, 0x29, 0xa4, 0xca, 0xc5, 0x0e, 0x92, 0x8f, 0xcf, 0x4c, 0x91, 0x60, 0x54, 0x60, - 0xd4, 0xe0, 0x36, 0xe2, 0xd1, 0x03, 0x69, 0xd2, 0xf3, 0x00, 0x6b, 0x0a, 0x62, 0x03, 0x6b, 0x4e, - 0x71, 0x9a, 0xca, 0x78, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, - 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x5c, 0x1c, 0xc9, - 0xf9, 0xb9, 0x60, 0x3d, 0x4e, 0x82, 0xc8, 0x26, 0x07, 0x80, 0xac, 0x0b, 0x60, 0x8c, 0xd2, 0x4b, - 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x77, 0x2c, 0x2e, 0x4e, 0x2d, 0xf1, - 0x4d, 0xcc, 0x2b, 0xc9, 0x49, 0xd5, 0xcf, 0xcd, 0x4f, 0x29, 0xcd, 0x49, 0x2d, 0xd6, 0x47, 0x73, - 0xed, 0x22, 0x26, 0x66, 0xa7, 0x88, 0x88, 0x55, 0x4c, 0x2c, 0x4e, 0x89, 0xc5, 0xa9, 0xa7, 0x20, - 0xd4, 0x23, 0x26, 0x01, 0x10, 0x15, 0xe3, 0x1e, 0xe0, 0xe4, 0x9b, 0x5a, 0x92, 0x98, 0x92, 0x58, - 0x92, 0xf8, 0x0a, 0x22, 0x93, 0xc4, 0x06, 0xf6, 0x95, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xd6, - 0xbd, 0x3a, 0xff, 0x1f, 0x01, 0x00, 0x00, -} - -func (m *MaintainerID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MaintainerID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MaintainerID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.HashId != nil { - { - size, err := m.HashId.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMaintainerID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintMaintainerID(dAtA []byte, offset int, v uint64) int { - offset -= sovMaintainerID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MaintainerID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.HashId != nil { - l = m.HashId.Size() - n += 1 + l + sovMaintainerID(uint64(l)) - } - return n -} - -func sovMaintainerID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMaintainerID(x uint64) (n int) { - return sovMaintainerID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MaintainerID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMaintainerID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MaintainerID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MaintainerID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HashId", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMaintainerID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMaintainerID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMaintainerID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.HashId == nil { - m.HashId = &HashID{} - } - if err := m.HashId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMaintainerID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMaintainerID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMaintainerID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMaintainerID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMaintainerID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMaintainerID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMaintainerID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMaintainerID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMaintainerID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMaintainerID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMaintainerID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMaintainerID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/ids/base/maintainerID.proto b/schema/ids/base/maintainerID.proto deleted file mode 100644 index 3f12a0d78..000000000 --- a/schema/ids/base/maintainerID.proto +++ /dev/null @@ -1,8 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/ids/base/hashID.proto"; - -message MaintainerID { - base.HashID hash_id = 1; -} \ No newline at end of file diff --git a/schema/ids/base/orderID.go b/schema/ids/base/orderID.go index b46f5d043..7f3436eea 100644 --- a/schema/ids/base/orderID.go +++ b/schema/ids/base/orderID.go @@ -1,51 +1,53 @@ package base import ( - "bytes" - "github.com/AssetMantle/modules/schema/errors/constants" "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/qualified" "github.com/AssetMantle/modules/schema/traits" ) -var _ ids.OrderID = (*ID_OrderID)(nil) - -func (orderID *ID_OrderID) String() string { - return orderID.OrderID.String() -} -func (orderID *ID_OrderID) Compare(listable traits.Listable) int { - return bytes.Compare(orderID.Bytes(), idFromInterface(listable).Bytes()) +type orderID struct { + ids.HashID } -func (orderID *ID_OrderID) Bytes() []byte { - return orderID.OrderID.OrderId.IdBytes -} -func (orderID *ID_OrderID) IsOrderID() {} -func NewOrderID(hashID ids.ID) ids.ID { - if hashID.(*ID).GetHashID() == nil { +var _ ids.OrderID = (*orderID)(nil) + +func (orderID orderID) IsOrderID() {} +func (orderID orderID) Compare(listable traits.Listable) int { + return orderID.HashID.Compare(orderIDFromInterface(listable).HashID) +} +func orderIDFromInterface(i interface{}) orderID { + switch value := i.(type) { + case orderID: + return value + default: panic(constants.MetaDataError) } - return &ID{ - Impl: &ID_OrderID{ - OrderID: &OrderID{ - OrderId: hashID.(*ID).GetHashID(), - }, - }, +} + +func NewOrderID(classificationID ids.ClassificationID, immutables qualified.Immutables) ids.OrderID { + return orderID{ + HashID: GenerateHashID(classificationID.Bytes(), immutables.GenerateHashID().Bytes()), } } -func PrototypeOrderID() ids.ID { - return NewOrderID(PrototypeHashID()) +func PrototypeOrderID() ids.OrderID { + return orderID{ + HashID: PrototypeHashID(), + } } -func ReadOrderID(orderIDString string) (ids.ID, error) { +func ReadOrderID(orderIDString string) (ids.OrderID, error) { if hashID, err := ReadHashID(orderIDString); err == nil { - return NewOrderID(hashID), nil + return orderID{ + HashID: hashID, + }, nil } if orderIDString == "" { return PrototypeOrderID(), nil } - return PrototypeOrderID(), nil + return orderID{}, nil } diff --git a/schema/ids/base/orderID.pb.go b/schema/ids/base/orderID.pb.go deleted file mode 100644 index d50aab4c5..000000000 --- a/schema/ids/base/orderID.pb.go +++ /dev/null @@ -1,328 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/ids/base/orderID.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type OrderID struct { - OrderId *HashID `protobuf:"bytes,1,opt,name=order_id,json=orderId,proto3" json:"order_id,omitempty"` -} - -func (m *OrderID) Reset() { *m = OrderID{} } -func (m *OrderID) String() string { return proto.CompactTextString(m) } -func (*OrderID) ProtoMessage() {} -func (*OrderID) Descriptor() ([]byte, []int) { - return fileDescriptor_cb5b2fe4504d4473, []int{0} -} -func (m *OrderID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *OrderID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_OrderID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *OrderID) XXX_Merge(src proto.Message) { - xxx_messageInfo_OrderID.Merge(m, src) -} -func (m *OrderID) XXX_Size() int { - return m.Size() -} -func (m *OrderID) XXX_DiscardUnknown() { - xxx_messageInfo_OrderID.DiscardUnknown(m) -} - -var xxx_messageInfo_OrderID proto.InternalMessageInfo - -func (m *OrderID) GetOrderId() *HashID { - if m != nil { - return m.OrderId - } - return nil -} - -func init() { - proto.RegisterType((*OrderID)(nil), "base.OrderID") -} - -func init() { proto.RegisterFile("schema/ids/base/orderID.proto", fileDescriptor_cb5b2fe4504d4473) } - -var fileDescriptor_cb5b2fe4504d4473 = []byte{ - // 226 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2d, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0xcf, 0x4c, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x2f, 0x4a, 0x49, - 0x2d, 0xf2, 0x74, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x89, 0x49, 0xc9, 0xa0, - 0x2b, 0xca, 0x48, 0x2c, 0xce, 0x80, 0xa9, 0x51, 0x32, 0xe2, 0x62, 0xf7, 0x87, 0x68, 0x12, 0x52, - 0xe7, 0xe2, 0x00, 0xeb, 0x8f, 0xcf, 0x4c, 0x91, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x36, 0xe2, 0xd1, - 0x03, 0x69, 0xd0, 0xf3, 0x00, 0x6b, 0x08, 0x62, 0x87, 0x98, 0x9e, 0xe2, 0x34, 0x81, 0xf1, 0xc4, - 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, - 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xb8, 0x38, 0x92, 0xf3, 0x73, 0xc1, 0x9a, 0x9c, - 0x78, 0xa0, 0xc6, 0x06, 0x80, 0xac, 0x09, 0x60, 0x8c, 0xd2, 0x4b, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, - 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x77, 0x2c, 0x2e, 0x4e, 0x2d, 0xf1, 0x4d, 0xcc, 0x2b, 0xc9, 0x49, - 0xd5, 0xcf, 0xcd, 0x4f, 0x29, 0xcd, 0x49, 0x2d, 0xd6, 0x47, 0x73, 0xe5, 0x22, 0x26, 0x66, 0xa7, - 0x88, 0x88, 0x55, 0x4c, 0x2c, 0x4e, 0x89, 0xc5, 0xa9, 0xa7, 0x20, 0xd4, 0x23, 0x26, 0x01, 0x10, - 0x15, 0xe3, 0x1e, 0xe0, 0xe4, 0x9b, 0x5a, 0x92, 0x98, 0x92, 0x58, 0x92, 0xf8, 0x0a, 0x22, 0x93, - 0xc4, 0x06, 0xf6, 0x8d, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xce, 0x2f, 0x96, 0xe8, 0x12, 0x01, - 0x00, 0x00, -} - -func (m *OrderID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *OrderID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *OrderID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.OrderId != nil { - { - size, err := m.OrderId.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintOrderID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintOrderID(dAtA []byte, offset int, v uint64) int { - offset -= sovOrderID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *OrderID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.OrderId != nil { - l = m.OrderId.Size() - n += 1 + l + sovOrderID(uint64(l)) - } - return n -} - -func sovOrderID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozOrderID(x uint64) (n int) { - return sovOrderID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *OrderID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrderID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: OrderID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: OrderID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OrderId", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOrderID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthOrderID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthOrderID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.OrderId == nil { - m.OrderId = &HashID{} - } - if err := m.OrderId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipOrderID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthOrderID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipOrderID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOrderID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOrderID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOrderID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthOrderID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupOrderID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthOrderID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthOrderID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowOrderID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupOrderID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/ids/base/orderID.proto b/schema/ids/base/orderID.proto deleted file mode 100644 index defcb632b..000000000 --- a/schema/ids/base/orderID.proto +++ /dev/null @@ -1,8 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/ids/base/hashID.proto"; - -message OrderID { - base.HashID order_id = 1; -} \ No newline at end of file diff --git a/schema/ids/base/ownableID.go b/schema/ids/base/ownableID.go index 49bf75144..aedcd69ba 100644 --- a/schema/ids/base/ownableID.go +++ b/schema/ids/base/ownableID.go @@ -8,16 +8,15 @@ import ( "github.com/AssetMantle/modules/schema/traits" ) -var _ ids.OwnableID = (*ID_OwnableID)(nil) - -func (ownableID *ID_OwnableID) String() string { - return ownableID.OwnableID.StringId.String() -} -func (ownableID *ID_OwnableID) Bytes() []byte { - return []byte(ownableID.OwnableID.StringId.IdString) +// TODO rename to something more appropriate +type ownableID struct { + ids.StringID } -func (ownableID *ID_OwnableID) IsOwnableID() {} -func (ownableID *ID_OwnableID) Compare(listable traits.Listable) int { + +var _ ids.OwnableID = (*ownableID)(nil) + +func (ownableID ownableID) IsOwnableID() {} +func (ownableID ownableID) Compare(listable traits.Listable) int { // TODO devise a better strategy to compare assetID and ownableID return bytes.Compare(ownableID.Bytes(), ownableIDFromInterface(listable).Bytes()) } @@ -29,28 +28,25 @@ func ownableIDFromInterface(i interface{}) ids.OwnableID { panic(constants.MetaDataError) } } -func NewOwnableID(stringID ids.ID) ids.ID { - if stringID.(*ID).GetStringID() == nil { - panic(constants.MetaDataError) - } - return &ID{ - Impl: &ID_OwnableID{ - OwnableID: &OwnableID{ - StringId: stringID.(*ID).GetStringID(), - }, - }, +func NewOwnableID(stringID ids.StringID) ids.OwnableID { + return ownableID{ + StringID: stringID, } } -func PrototypeOwnableID() ids.ID { - return NewOwnableID(PrototypeStringID()) +func PrototypeOwnableID() ids.OwnableID { + return ownableID{ + StringID: PrototypeStringID(), + } } -func ReadOwnableID(ownableIDString string) (ids.ID, error) { - // TODO ***** never allow ownable PropertyID to be valid hash string +func ReadOwnableID(ownableIDString string) (ids.OwnableID, error) { + // TODO ***** never allow ownable ID to be valid hash string if assetID, err := ReadAssetID(ownableIDString); err == nil { return assetID, nil } - return NewOwnableID(NewStringID(ownableIDString)), nil + return ownableID{ + StringID: NewStringID(ownableIDString), + }, nil } diff --git a/schema/ids/base/ownableID.pb.go b/schema/ids/base/ownableID.pb.go deleted file mode 100644 index 77969c85e..000000000 --- a/schema/ids/base/ownableID.pb.go +++ /dev/null @@ -1,328 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/ids/base/ownableID.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type OwnableID struct { - StringId *StringID `protobuf:"bytes,1,opt,name=string_id,json=stringId,proto3" json:"string_id,omitempty"` -} - -func (m *OwnableID) Reset() { *m = OwnableID{} } -func (m *OwnableID) String() string { return proto.CompactTextString(m) } -func (*OwnableID) ProtoMessage() {} -func (*OwnableID) Descriptor() ([]byte, []int) { - return fileDescriptor_47f4833afea02d14, []int{0} -} -func (m *OwnableID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *OwnableID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_OwnableID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *OwnableID) XXX_Merge(src proto.Message) { - xxx_messageInfo_OwnableID.Merge(m, src) -} -func (m *OwnableID) XXX_Size() int { - return m.Size() -} -func (m *OwnableID) XXX_DiscardUnknown() { - xxx_messageInfo_OwnableID.DiscardUnknown(m) -} - -var xxx_messageInfo_OwnableID proto.InternalMessageInfo - -func (m *OwnableID) GetStringId() *StringID { - if m != nil { - return m.StringId - } - return nil -} - -func init() { - proto.RegisterType((*OwnableID)(nil), "base.OwnableID") -} - -func init() { proto.RegisterFile("schema/ids/base/ownableID.proto", fileDescriptor_47f4833afea02d14) } - -var fileDescriptor_47f4833afea02d14 = []byte{ - // 230 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0xcf, 0x4c, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x2f, 0xcf, 0x4b, - 0x4c, 0xca, 0x49, 0xf5, 0x74, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x89, 0x4a, - 0xc9, 0xa1, 0x2b, 0x2b, 0x2e, 0x29, 0xca, 0xcc, 0x4b, 0x87, 0xa9, 0x52, 0xb2, 0xe0, 0xe2, 0xf4, - 0x87, 0x69, 0x14, 0xd2, 0xe6, 0xe2, 0x84, 0x48, 0xc7, 0x67, 0xa6, 0x48, 0x30, 0x2a, 0x30, 0x6a, - 0x70, 0x1b, 0xf1, 0xe9, 0x81, 0x74, 0xe9, 0x05, 0x43, 0x75, 0x05, 0x71, 0x40, 0xf5, 0xa7, 0x38, - 0x4d, 0x62, 0x3c, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, - 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x06, 0x2e, 0x8e, 0xe4, 0xfc, - 0x5c, 0xb0, 0x3e, 0x27, 0x3e, 0xb8, 0xe1, 0x01, 0x20, 0xeb, 0x02, 0x18, 0xa3, 0xf4, 0xd2, 0x33, - 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x1d, 0x8b, 0x8b, 0x53, 0x4b, 0x7c, 0x13, - 0xf3, 0x4a, 0x72, 0x52, 0xf5, 0x73, 0xf3, 0x53, 0x4a, 0x73, 0x52, 0x8b, 0xf5, 0xd1, 0xdc, 0xbb, - 0x88, 0x89, 0xd9, 0x29, 0x22, 0x62, 0x15, 0x13, 0x8b, 0x53, 0x62, 0x71, 0xea, 0x29, 0x08, 0xf5, - 0x88, 0x49, 0x00, 0x44, 0xc5, 0xb8, 0x07, 0x38, 0xf9, 0xa6, 0x96, 0x24, 0xa6, 0x24, 0x96, 0x24, - 0xbe, 0x82, 0xc8, 0x24, 0xb1, 0x81, 0x7d, 0x65, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x35, 0xf4, - 0x5b, 0xae, 0x1e, 0x01, 0x00, 0x00, -} - -func (m *OwnableID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *OwnableID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *OwnableID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.StringId != nil { - { - size, err := m.StringId.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintOwnableID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintOwnableID(dAtA []byte, offset int, v uint64) int { - offset -= sovOwnableID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *OwnableID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.StringId != nil { - l = m.StringId.Size() - n += 1 + l + sovOwnableID(uint64(l)) - } - return n -} - -func sovOwnableID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozOwnableID(x uint64) (n int) { - return sovOwnableID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *OwnableID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOwnableID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: OwnableID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: OwnableID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StringId", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowOwnableID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthOwnableID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthOwnableID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.StringId == nil { - m.StringId = &StringID{} - } - if err := m.StringId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipOwnableID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthOwnableID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipOwnableID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOwnableID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOwnableID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowOwnableID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthOwnableID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupOwnableID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthOwnableID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthOwnableID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowOwnableID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupOwnableID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/ids/base/ownableID.proto b/schema/ids/base/ownableID.proto deleted file mode 100644 index e4504b869..000000000 --- a/schema/ids/base/ownableID.proto +++ /dev/null @@ -1,8 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/ids/base/stringID.proto"; - -message OwnableID{ - base.StringID string_id = 1; -} \ No newline at end of file diff --git a/schema/ids/base/propertyID.go b/schema/ids/base/propertyID.go index 37b71b7e6..ff8738c79 100644 --- a/schema/ids/base/propertyID.go +++ b/schema/ids/base/propertyID.go @@ -8,46 +8,49 @@ import ( errorConstants "github.com/AssetMantle/modules/schema/errors/constants" "github.com/AssetMantle/modules/schema/ids" + stringUtilities "github.com/AssetMantle/modules/schema/ids/utilities" "github.com/AssetMantle/modules/schema/traits" ) -var _ ids.PropertyID = (*ID_PropertyID)(nil) +type propertyID struct { + Key ids.StringID + Type ids.StringID +} + +var _ ids.PropertyID = (*propertyID)(nil) -func (propertyID *ID_PropertyID) String() string { - return propertyID.PropertyID.String() +func (propertyID propertyID) IsPropertyID() {} +func (propertyID propertyID) GetKey() ids.StringID { + return propertyID.Key } -func (propertyID *ID_PropertyID) IsPropertyID() {} -func (propertyID *ID_PropertyID) GetKey() ids.ID { - return &ID{Impl: &ID_StringID{StringID: propertyID.PropertyID.KeyID}} +func (propertyID propertyID) GetType() ids.StringID { + return propertyID.Type } -func (propertyID *ID_PropertyID) GetType() ids.ID { - return &ID{Impl: &ID_StringID{StringID: propertyID.PropertyID.TypeID}} +func (propertyID propertyID) String() string { + return stringUtilities.JoinIDStrings(propertyID.Key.String(), propertyID.Type.String()) } -func (propertyID *ID_PropertyID) Bytes() []byte { +func (propertyID propertyID) Bytes() []byte { var Bytes []byte - Bytes = append(Bytes, propertyID.PropertyID.KeyID.IdString...) - Bytes = append(Bytes, propertyID.PropertyID.TypeID.IdString...) + Bytes = append(Bytes, propertyID.Key.Bytes()...) + Bytes = append(Bytes, propertyID.Type.Bytes()...) return Bytes } -func (propertyID *ID_PropertyID) Compare(listable traits.Listable) int { - return bytes.Compare(propertyID.Bytes(), idFromInterface(listable).Bytes()) -} - -func GeneratePropertyID(key, Type ids.ID) ids.ID { - return NewPropertyID(key, Type) +func (propertyID propertyID) Compare(listable traits.Listable) int { + return bytes.Compare(propertyID.Bytes(), propertyIDFromInterface(listable).Bytes()) } -func NewPropertyID(keyID, typeID ids.ID) ids.ID { - if keyID.(*ID).GetStringID() == nil || typeID.(*ID).GetStringID() == nil { +func propertyIDFromInterface(listable traits.Listable) propertyID { + switch value := listable.(type) { + case propertyID: + return value + default: panic(errorConstants.MetaDataError) } - return &ID{ - Impl: &ID_PropertyID{ - PropertyID: &PropertyID{ - KeyID: keyID.(*ID).GetStringID(), - TypeID: typeID.(*ID).GetStringID(), - }, - }, - } +} +func NewPropertyID(key, Type ids.StringID) ids.PropertyID { + return propertyID{ + Key: key, + Type: Type, + } } diff --git a/schema/ids/base/propertyID.pb.go b/schema/ids/base/propertyID.pb.go deleted file mode 100644 index 0f7d671ef..000000000 --- a/schema/ids/base/propertyID.pb.go +++ /dev/null @@ -1,389 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/ids/base/propertyID.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type PropertyID struct { - KeyID *StringID `protobuf:"bytes,1,opt,name=key_i_d,json=keyID,proto3" json:"key_i_d,omitempty"` - TypeID *StringID `protobuf:"bytes,2,opt,name=type_i_d,json=typeID,proto3" json:"type_i_d,omitempty"` -} - -func (m *PropertyID) Reset() { *m = PropertyID{} } -func (m *PropertyID) String() string { return proto.CompactTextString(m) } -func (*PropertyID) ProtoMessage() {} -func (*PropertyID) Descriptor() ([]byte, []int) { - return fileDescriptor_a6c9912868b1c2ec, []int{0} -} -func (m *PropertyID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PropertyID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PropertyID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *PropertyID) XXX_Merge(src proto.Message) { - xxx_messageInfo_PropertyID.Merge(m, src) -} -func (m *PropertyID) XXX_Size() int { - return m.Size() -} -func (m *PropertyID) XXX_DiscardUnknown() { - xxx_messageInfo_PropertyID.DiscardUnknown(m) -} - -var xxx_messageInfo_PropertyID proto.InternalMessageInfo - -func (m *PropertyID) GetKeyID() *StringID { - if m != nil { - return m.KeyID - } - return nil -} - -func (m *PropertyID) GetTypeID() *StringID { - if m != nil { - return m.TypeID - } - return nil -} - -func init() { - proto.RegisterType((*PropertyID)(nil), "base.PropertyID") -} - -func init() { proto.RegisterFile("schema/ids/base/propertyID.proto", fileDescriptor_a6c9912868b1c2ec) } - -var fileDescriptor_a6c9912868b1c2ec = []byte{ - // 252 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x28, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0xcf, 0x4c, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x2f, 0x28, 0xca, 0x2f, - 0x48, 0x2d, 0x2a, 0xa9, 0xf4, 0x74, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x09, - 0x4b, 0xc9, 0xa1, 0xab, 0x2b, 0x2e, 0x29, 0xca, 0xcc, 0x4b, 0x87, 0xa9, 0x52, 0x8a, 0xe3, 0xe2, - 0x0a, 0x80, 0xeb, 0x14, 0x52, 0xe3, 0x62, 0xcf, 0x4e, 0xad, 0x8c, 0xcf, 0x8c, 0x4f, 0x91, 0x60, - 0x54, 0x60, 0xd4, 0xe0, 0x36, 0xe2, 0xd3, 0x03, 0x69, 0xd2, 0x0b, 0x86, 0x6a, 0x0a, 0x62, 0xcd, - 0x4e, 0x05, 0xa9, 0xd3, 0xe0, 0xe2, 0x28, 0xa9, 0x2c, 0x48, 0x05, 0x2b, 0x64, 0xc2, 0xaa, 0x90, - 0x0d, 0x24, 0xef, 0xe9, 0xe2, 0x34, 0x99, 0xf1, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, - 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, - 0x18, 0xb8, 0x38, 0x92, 0xf3, 0x73, 0xc1, 0xba, 0x9c, 0xf8, 0x11, 0x4e, 0x08, 0x00, 0xb9, 0x2a, - 0x80, 0x31, 0x4a, 0x2f, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0xdf, 0xb1, - 0xb8, 0x38, 0xb5, 0xc4, 0x37, 0x31, 0xaf, 0x24, 0x27, 0x55, 0x3f, 0x37, 0x3f, 0xa5, 0x34, 0x27, - 0xb5, 0x58, 0x1f, 0xcd, 0x5b, 0x8b, 0x98, 0x98, 0x9d, 0x22, 0x22, 0x56, 0x31, 0xb1, 0x38, 0x25, - 0x16, 0xa7, 0x9e, 0x82, 0x50, 0x8f, 0x98, 0x04, 0x40, 0x54, 0x8c, 0x7b, 0x80, 0x93, 0x6f, 0x6a, - 0x49, 0x62, 0x4a, 0x62, 0x49, 0xe2, 0x2b, 0x88, 0x4c, 0x12, 0x1b, 0xd8, 0xf3, 0xc6, 0x80, 0x00, - 0x00, 0x00, 0xff, 0xff, 0x89, 0x7d, 0xa8, 0x0f, 0x46, 0x01, 0x00, 0x00, -} - -func (m *PropertyID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PropertyID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PropertyID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.TypeID != nil { - { - size, err := m.TypeID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintPropertyID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if m.KeyID != nil { - { - size, err := m.KeyID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintPropertyID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintPropertyID(dAtA []byte, offset int, v uint64) int { - offset -= sovPropertyID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *PropertyID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.KeyID != nil { - l = m.KeyID.Size() - n += 1 + l + sovPropertyID(uint64(l)) - } - if m.TypeID != nil { - l = m.TypeID.Size() - n += 1 + l + sovPropertyID(uint64(l)) - } - return n -} - -func sovPropertyID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozPropertyID(x uint64) (n int) { - return sovPropertyID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *PropertyID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPropertyID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PropertyID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PropertyID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field KeyID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPropertyID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthPropertyID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthPropertyID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.KeyID == nil { - m.KeyID = &StringID{} - } - if err := m.KeyID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TypeID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPropertyID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthPropertyID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthPropertyID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.TypeID == nil { - m.TypeID = &StringID{} - } - if err := m.TypeID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipPropertyID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPropertyID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipPropertyID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPropertyID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPropertyID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPropertyID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthPropertyID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupPropertyID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthPropertyID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthPropertyID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowPropertyID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupPropertyID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/ids/base/propertyID.proto b/schema/ids/base/propertyID.proto deleted file mode 100644 index 897601e72..000000000 --- a/schema/ids/base/propertyID.proto +++ /dev/null @@ -1,9 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/ids/base/stringID.proto"; - -message PropertyID{ - base.StringID key_i_d = 1; - base.StringID type_i_d = 2; -} \ No newline at end of file diff --git a/schema/ids/base/propertyID_test.go b/schema/ids/base/propertyID_test.go new file mode 100644 index 000000000..a2ad520f6 --- /dev/null +++ b/schema/ids/base/propertyID_test.go @@ -0,0 +1,206 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "reflect" + "strings" + "testing" + + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/traits" +) + +func createTestInputForPropertyID() (ids.StringID, ids.StringID, ids.PropertyID) { + testKey := NewStringID("ID") + testType := NewStringID("ID2") + testPropertyID := NewPropertyID(testKey, testType) + return testKey, testType, testPropertyID +} + +func TestNewPropertyID(t *testing.T) { + type args struct { + key ids.StringID + Type ids.StringID + } + tests := []struct { + name string + args args + want ids.PropertyID + }{ + + {"+ve", args{NewStringID("ID"), NewStringID("ID2")}, propertyID{NewStringID("ID"), NewStringID("ID2")}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewPropertyID(tt.args.key, tt.args.Type); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewPropertyID() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_propertyIDFromInterface(t *testing.T) { + testKey, testType, testPropertyID := createTestInputForPropertyID() + type args struct { + listable traits.Listable + } + tests := []struct { + name string + args args + want propertyID + wantErr bool + }{ + + {"+ve", args{testPropertyID}, propertyID{testKey, testType}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := propertyIDFromInterface(tt.args.listable) + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("propertyIDFromInterface() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_propertyID_Bytes(t *testing.T) { + testKey, testType, _ := createTestInputForPropertyID() + type fields struct { + Key ids.StringID + Type ids.StringID + } + tests := []struct { + name string + fields fields + want []byte + }{ + + {"+ve", fields{testKey, testType}, append([]byte(testKey.String()), []byte(testType.String())...)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + propertyID := propertyID{ + Key: tt.fields.Key, + Type: tt.fields.Type, + } + if got := propertyID.Bytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Bytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_propertyID_Compare(t *testing.T) { + testKey, testType, testPropertyID := createTestInputForPropertyID() + type fields struct { + Key ids.StringID + Type ids.StringID + } + type args struct { + listable traits.Listable + } + tests := []struct { + name string + fields fields + args args + want int + }{ + + {"+ve", fields{testKey, testType}, args{testPropertyID}, 0}, + {"-ve", fields{testType, testType}, args{testPropertyID}, -1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + propertyID := propertyID{ + Key: tt.fields.Key, + Type: tt.fields.Type, + } + if got := propertyID.Compare(tt.args.listable); got != tt.want { + t.Errorf("Compare() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_propertyID_GetKey(t *testing.T) { + testKey, testType, _ := createTestInputForPropertyID() + type fields struct { + Key ids.StringID + Type ids.StringID + } + tests := []struct { + name string + fields fields + want ids.StringID + }{ + + {"+ve", fields{testKey, testType}, testKey}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + propertyID := propertyID{ + Key: tt.fields.Key, + Type: tt.fields.Type, + } + if got := propertyID.GetKey(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetKey() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_propertyID_GetType(t *testing.T) { + testKey, testType, _ := createTestInputForPropertyID() + type fields struct { + Key ids.StringID + Type ids.StringID + } + tests := []struct { + name string + fields fields + want ids.StringID + }{ + + {"+ve", fields{testKey, testType}, testType}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + propertyID := propertyID{ + Key: tt.fields.Key, + Type: tt.fields.Type, + } + if got := propertyID.GetType(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetType() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_propertyID_String(t *testing.T) { + testKey, testType, _ := createTestInputForPropertyID() + type fields struct { + Key ids.StringID + Type ids.StringID + } + tests := []struct { + name string + fields fields + want string + }{ + + {"+ve", fields{testKey, testType}, strings.Join([]string{testKey.String(), testType.String()}, ".")}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + propertyID := propertyID{ + Key: tt.fields.Key, + Type: tt.fields.Type, + } + if got := propertyID.String(); got != tt.want { + t.Errorf("String() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/schema/ids/base/splitID.go b/schema/ids/base/splitID.go index 9bf2d4401..454438200 100644 --- a/schema/ids/base/splitID.go +++ b/schema/ids/base/splitID.go @@ -7,52 +7,61 @@ import ( "github.com/AssetMantle/modules/schema/ids" stringUtilities "github.com/AssetMantle/modules/schema/ids/utilities" "github.com/AssetMantle/modules/schema/traits" - "github.com/AssetMantle/modules/schema/types" ) -var _ ids.SplitID = (*ID_SplitID)(nil) - -func (splitID *ID_SplitID) String() string { - return splitID.SplitID.String() +type splitID struct { + OwnerID ids.IdentityID + OwnableID ids.OwnableID } -func (splitID *ID_SplitID) IsSplitID() {} -func (splitID *ID_SplitID) Bytes() []byte { + +var _ ids.SplitID = (*splitID)(nil) + +func (splitID splitID) IsSplitID() {} +func (splitID splitID) Bytes() []byte { return append( - splitID.SplitID.OwnerId.HashId.IdBytes, - splitID.SplitID.OwnableId.StringId.IdString...) + splitID.OwnerID.Bytes(), + splitID.OwnableID.Bytes()...) } -func (splitID *ID_SplitID) Compare(listable traits.Listable) int { - return bytes.Compare(splitID.Bytes(), idFromInterface(listable).Bytes()) +func (splitID splitID) String() string { + return stringUtilities.JoinIDStrings(splitID.OwnerID.String(), splitID.OwnableID.String()) } -func (splitID *ID_SplitID) GetOwnableID() ids.ID { - return &ID{Impl: &ID_OwnableID{OwnableID: splitID.SplitID.OwnableId}} +func (splitID splitID) Compare(listable traits.Listable) int { + return bytes.Compare(splitID.Bytes(), splitIDFromInterface(listable).Bytes()) } - -func GenerateSplitID(split types.Split) ids.ID { - return NewSplitID(split.GetOwnerID(), split.GetOwnableID()) +func (splitID splitID) GetOwnableID() ids.ID { + return splitID.OwnableID } -func NewSplitID(ownerID ids.ID, ownableID ids.ID) ids.ID { - if ownerID.(*ID).GetIdentityID() == nil || ownableID.(*ID).GetOwnableID() == nil { - panic(constants.MetaDataError) +func splitIDFromInterface(i interface{}) splitID { + switch value := i.(type) { + case splitID: + return value + default: + panic(i) } - return &ID{ - Impl: &ID_SplitID{ - SplitID: &SplitID{ - OwnerId: ownerID.(*ID).GetIdentityID(), - OwnableId: ownableID.(*ID).GetOwnableID(), - }, - }, +} + +func NewSplitID(ownerID ids.IdentityID, ownableID ids.OwnableID) ids.SplitID { + return splitID{ + OwnerID: ownerID, + OwnableID: ownableID, } } -func PrototypeSplitID() ids.ID { - return NewSplitID(PrototypeIdentityID(), PrototypeOwnableID()) + +func PrototypeSplitID() ids.SplitID { + return splitID{ + OwnerID: PrototypeIdentityID(), + OwnableID: PrototypeOwnableID(), + } } -func ReadSplitID(splitIDString string) (ids.ID, error) { +func ReadSplitID(splitIDString string) (ids.SplitID, error) { if splitIDStringSplit := stringUtilities.SplitCompositeIDString(splitIDString); len(splitIDStringSplit) == 2 { if ownerID, err := ReadIdentityID(splitIDStringSplit[0]); err == nil { if ownableID, err := ReadOwnableID(splitIDStringSplit[1]); err == nil { - return NewSplitID(ownerID, ownableID), nil + return splitID{ + OwnerID: ownerID, + OwnableID: ownableID, + }, nil } } } @@ -61,5 +70,5 @@ func ReadSplitID(splitIDString string) (ids.ID, error) { return PrototypeSplitID(), nil } - return PrototypeSplitID(), constants.MetaDataError + return splitID{}, constants.MetaDataError } diff --git a/schema/ids/base/splitID.pb.go b/schema/ids/base/splitID.pb.go deleted file mode 100644 index eb5098f01..000000000 --- a/schema/ids/base/splitID.pb.go +++ /dev/null @@ -1,390 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/ids/base/splitID.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type SplitID struct { - OwnerId *IdentityID `protobuf:"bytes,1,opt,name=owner_id,json=ownerId,proto3" json:"owner_id,omitempty"` - OwnableId *OwnableID `protobuf:"bytes,2,opt,name=ownable_id,json=ownableId,proto3" json:"ownable_id,omitempty"` -} - -func (m *SplitID) Reset() { *m = SplitID{} } -func (m *SplitID) String() string { return proto.CompactTextString(m) } -func (*SplitID) ProtoMessage() {} -func (*SplitID) Descriptor() ([]byte, []int) { - return fileDescriptor_fe8594a36c5a7a51, []int{0} -} -func (m *SplitID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *SplitID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SplitID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *SplitID) XXX_Merge(src proto.Message) { - xxx_messageInfo_SplitID.Merge(m, src) -} -func (m *SplitID) XXX_Size() int { - return m.Size() -} -func (m *SplitID) XXX_DiscardUnknown() { - xxx_messageInfo_SplitID.DiscardUnknown(m) -} - -var xxx_messageInfo_SplitID proto.InternalMessageInfo - -func (m *SplitID) GetOwnerId() *IdentityID { - if m != nil { - return m.OwnerId - } - return nil -} - -func (m *SplitID) GetOwnableId() *OwnableID { - if m != nil { - return m.OwnableId - } - return nil -} - -func init() { - proto.RegisterType((*SplitID)(nil), "base.SplitID") -} - -func init() { proto.RegisterFile("schema/ids/base/splitID.proto", fileDescriptor_fe8594a36c5a7a51) } - -var fileDescriptor_fe8594a36c5a7a51 = []byte{ - // 270 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2d, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0xcf, 0x4c, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x2f, 0x2e, 0xc8, 0xc9, - 0x2c, 0xf1, 0x74, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x89, 0x49, 0x29, 0xa0, - 0x2b, 0xca, 0x4c, 0x49, 0xcd, 0x2b, 0xc9, 0x2c, 0xa9, 0x84, 0xa9, 0x93, 0x92, 0x47, 0x57, 0x91, - 0x5f, 0x9e, 0x97, 0x98, 0x94, 0x93, 0x0a, 0x53, 0xa0, 0x94, 0xc6, 0xc5, 0x1e, 0x0c, 0x31, 0x59, - 0x48, 0x9b, 0x8b, 0x23, 0xbf, 0x3c, 0x2f, 0xb5, 0x28, 0x3e, 0x33, 0x45, 0x82, 0x51, 0x81, 0x51, - 0x83, 0xdb, 0x48, 0x40, 0x0f, 0xa4, 0x47, 0xcf, 0x13, 0x6e, 0x6a, 0x10, 0x3b, 0x58, 0x85, 0x67, - 0x8a, 0x90, 0x1e, 0x17, 0x17, 0xd4, 0x28, 0x90, 0x72, 0x26, 0xb0, 0x72, 0x7e, 0x88, 0x72, 0x7f, - 0x98, 0x15, 0x41, 0x9c, 0x30, 0xdb, 0x52, 0x9c, 0x26, 0x30, 0x9e, 0x78, 0x24, 0xc7, 0x78, 0xe1, - 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, 0x78, 0x2c, 0xc7, 0x70, - 0xe3, 0xb1, 0x1c, 0x03, 0x17, 0x47, 0x72, 0x7e, 0x2e, 0x58, 0xa7, 0x13, 0x0f, 0xd4, 0x29, 0x01, - 0x20, 0xa7, 0x05, 0x30, 0x46, 0xe9, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, - 0xea, 0x3b, 0x16, 0x17, 0xa7, 0x96, 0xf8, 0x26, 0xe6, 0x95, 0xe4, 0xa4, 0xea, 0xe7, 0xe6, 0xa7, - 0x94, 0xe6, 0xa4, 0x16, 0xeb, 0xa3, 0x79, 0x6e, 0x11, 0x13, 0xb3, 0x53, 0x44, 0xc4, 0x2a, 0x26, - 0x16, 0xa7, 0xc4, 0xe2, 0xd4, 0x53, 0x10, 0xea, 0x11, 0x93, 0x00, 0x88, 0x8a, 0x71, 0x0f, 0x70, - 0xf2, 0x4d, 0x2d, 0x49, 0x4c, 0x49, 0x2c, 0x49, 0x7c, 0x05, 0x91, 0x49, 0x62, 0x03, 0x87, 0x80, - 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x5e, 0x34, 0xda, 0x2a, 0x6b, 0x01, 0x00, 0x00, -} - -func (m *SplitID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *SplitID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SplitID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.OwnableId != nil { - { - size, err := m.OwnableId.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSplitID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if m.OwnerId != nil { - { - size, err := m.OwnerId.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSplitID(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintSplitID(dAtA []byte, offset int, v uint64) int { - offset -= sovSplitID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *SplitID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.OwnerId != nil { - l = m.OwnerId.Size() - n += 1 + l + sovSplitID(uint64(l)) - } - if m.OwnableId != nil { - l = m.OwnableId.Size() - n += 1 + l + sovSplitID(uint64(l)) - } - return n -} - -func sovSplitID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozSplitID(x uint64) (n int) { - return sovSplitID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *SplitID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSplitID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: SplitID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SplitID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OwnerId", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSplitID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSplitID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSplitID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.OwnerId == nil { - m.OwnerId = &IdentityID{} - } - if err := m.OwnerId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OwnableId", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSplitID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSplitID - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSplitID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.OwnableId == nil { - m.OwnableId = &OwnableID{} - } - if err := m.OwnableId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSplitID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSplitID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipSplitID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSplitID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSplitID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSplitID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthSplitID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupSplitID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthSplitID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthSplitID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowSplitID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupSplitID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/ids/base/splitID.proto b/schema/ids/base/splitID.proto deleted file mode 100644 index 8447144c7..000000000 --- a/schema/ids/base/splitID.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/ids/base/identityID.proto"; -import "schema/ids/base/ownableID.proto"; - -message SplitID { - base.IdentityID owner_id = 1; - base.OwnableID ownable_id = 2; -} \ No newline at end of file diff --git a/schema/ids/base/stringID.go b/schema/ids/base/stringID.go index fef8a7760..995abaf4b 100644 --- a/schema/ids/base/stringID.go +++ b/schema/ids/base/stringID.go @@ -6,33 +6,42 @@ package base import ( "strings" + "github.com/AssetMantle/modules/schema/errors/constants" "github.com/AssetMantle/modules/schema/ids" "github.com/AssetMantle/modules/schema/traits" ) -var _ ids.StringID = (*ID_StringID)(nil) +type stringID struct { + IDString string `json:"idString"` +} + +var _ ids.StringID = (*stringID)(nil) -func (stringID *ID_StringID) String() string { - return stringID.StringID.IdString +func (stringID stringID) IsStringID() {} +func (stringID stringID) String() string { + return stringID.IDString } -func (stringID *ID_StringID) IsStringID() {} -func (stringID *ID_StringID) Bytes() []byte { - return []byte(stringID.String()) +func (stringID stringID) Bytes() []byte { + return []byte(stringID.IDString) } -func (stringID *ID_StringID) Compare(listable traits.Listable) int { - return strings.Compare(stringID.String(), idFromInterface(listable).String()) +func (stringID stringID) Compare(listable traits.Listable) int { + return strings.Compare(stringID.String(), stringIDFromInterface(listable).String()) } - -func NewStringID(idString string) ids.ID { - return &ID{ - Impl: &ID_StringID{ - StringID: &StringID{ - IdString: idString, - }, - }, +func stringIDFromInterface(i interface{}) stringID { + switch value := i.(type) { + case stringID: + return value + default: + panic(constants.MetaDataError) } } -func PrototypeStringID() ids.ID { - return NewStringID("") +func NewStringID(idString string) ids.StringID { + return stringID{IDString: idString} +} + +func PrototypeStringID() ids.StringID { + return stringID{ + IDString: "", + } } diff --git a/schema/ids/base/stringID.pb.go b/schema/ids/base/stringID.pb.go deleted file mode 100644 index 6eb44886e..000000000 --- a/schema/ids/base/stringID.pb.go +++ /dev/null @@ -1,318 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/ids/base/stringID.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type StringID struct { - IdString string `protobuf:"bytes,1,opt,name=id_string,json=idString,proto3" json:"id_string,omitempty"` -} - -func (m *StringID) Reset() { *m = StringID{} } -func (m *StringID) String() string { return proto.CompactTextString(m) } -func (*StringID) ProtoMessage() {} -func (*StringID) Descriptor() ([]byte, []int) { - return fileDescriptor_ca70a5dc5a72ef3c, []int{0} -} -func (m *StringID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *StringID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_StringID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *StringID) XXX_Merge(src proto.Message) { - xxx_messageInfo_StringID.Merge(m, src) -} -func (m *StringID) XXX_Size() int { - return m.Size() -} -func (m *StringID) XXX_DiscardUnknown() { - xxx_messageInfo_StringID.DiscardUnknown(m) -} - -var xxx_messageInfo_StringID proto.InternalMessageInfo - -func (m *StringID) GetIdString() string { - if m != nil { - return m.IdString - } - return "" -} - -func init() { - proto.RegisterType((*StringID)(nil), "base.StringID") -} - -func init() { proto.RegisterFile("schema/ids/base/stringID.proto", fileDescriptor_ca70a5dc5a72ef3c) } - -var fileDescriptor_ca70a5dc5a72ef3c = []byte{ - // 210 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2b, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0xcf, 0x4c, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x2f, 0x2e, 0x29, 0xca, - 0xcc, 0x4b, 0xf7, 0x74, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x09, 0x2a, 0xa9, - 0x73, 0x71, 0x04, 0x43, 0xc5, 0x85, 0xa4, 0xb9, 0x38, 0x33, 0x53, 0xe2, 0x21, 0xca, 0x24, 0x18, - 0x15, 0x18, 0x35, 0x38, 0x83, 0x38, 0x32, 0x53, 0x20, 0xd2, 0x4e, 0x13, 0x19, 0x4f, 0x3c, 0x92, - 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, - 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x81, 0x8b, 0x23, 0x39, 0x3f, 0x57, 0x0f, 0x64, 0x9a, 0x13, - 0x2f, 0xcc, 0xac, 0x00, 0x90, 0x15, 0x01, 0x8c, 0x51, 0x7a, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, - 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x8e, 0xc5, 0xc5, 0xa9, 0x25, 0xbe, 0x89, 0x79, 0x25, 0x39, 0xa9, - 0xfa, 0xb9, 0xf9, 0x29, 0xa5, 0x39, 0xa9, 0xc5, 0xfa, 0x68, 0x6e, 0x5c, 0xc4, 0xc4, 0xec, 0x14, - 0x11, 0xb1, 0x8a, 0x89, 0xc5, 0x29, 0xb1, 0x38, 0xf5, 0x14, 0x84, 0x7a, 0xc4, 0x24, 0x00, 0xa2, - 0x62, 0xdc, 0x03, 0x9c, 0x7c, 0x53, 0x4b, 0x12, 0x53, 0x12, 0x4b, 0x12, 0x5f, 0x41, 0x64, 0x92, - 0xd8, 0xc0, 0x3e, 0x31, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x99, 0x8f, 0xed, 0x8a, 0xeb, 0x00, - 0x00, 0x00, -} - -func (m *StringID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *StringID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *StringID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.IdString) > 0 { - i -= len(m.IdString) - copy(dAtA[i:], m.IdString) - i = encodeVarintStringID(dAtA, i, uint64(len(m.IdString))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintStringID(dAtA []byte, offset int, v uint64) int { - offset -= sovStringID(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *StringID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.IdString) - if l > 0 { - n += 1 + l + sovStringID(uint64(l)) - } - return n -} - -func sovStringID(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozStringID(x uint64) (n int) { - return sovStringID(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *StringID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStringID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: StringID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: StringID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IdString", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStringID - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthStringID - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStringID - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IdString = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipStringID(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthStringID - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipStringID(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStringID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStringID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStringID - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthStringID - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupStringID - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthStringID - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthStringID = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowStringID = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupStringID = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/ids/base/stringID.proto b/schema/ids/base/stringID.proto deleted file mode 100644 index 8f736b4f3..000000000 --- a/schema/ids/base/stringID.proto +++ /dev/null @@ -1,7 +0,0 @@ -syntax="proto3"; -package base; - - -message StringID { - string id_string = 1; -} \ No newline at end of file diff --git a/schema/ids/base/stringID_test.go b/schema/ids/base/stringID_test.go index b6cb75ed2..9b54cc0c4 100644 --- a/schema/ids/base/stringID_test.go +++ b/schema/ids/base/stringID_test.go @@ -21,7 +21,7 @@ func TestNewStringID(t *testing.T) { want ids.StringID }{ {"+ve", args{"ID"}, stringID{"ID"}}, - {"+ve", args{"S|ID"}, stringID{"S|ID"}}, //TODO: It should fail + {"+ve", args{"S|ID"}, stringID{"S|ID"}}, // TODO: It should fail } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/schema/ids/codec.go b/schema/ids/codec.go index 834e154bc..7b2110a97 100644 --- a/schema/ids/codec.go +++ b/schema/ids/codec.go @@ -7,7 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { +func RegisterCodec(codec *codec.Codec) { codec.RegisterInterface((*AssetID)(nil), nil) codec.RegisterInterface((*ClassificationID)(nil), nil) codec.RegisterInterface((*DataID)(nil), nil) diff --git a/schema/ids/codec_test.go b/schema/ids/codec_test.go new file mode 100644 index 000000000..cbf6c636b --- /dev/null +++ b/schema/ids/codec_test.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package ids + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + + {"+ve", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/ids/constansts/classificationID.go b/schema/ids/constansts/classificationID.go index 3064aa5e9..be71cd858 100644 --- a/schema/ids/constansts/classificationID.go +++ b/schema/ids/constansts/classificationID.go @@ -1 +1,9 @@ package constansts + +import ( + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + qualifiedConstants "github.com/AssetMantle/modules/schema/qualified/constants" +) + +var NubClassificationID = baseIDs.NewClassificationID(qualifiedConstants.NubImmutables, qualifiedConstants.NubMutables) +var MaintainerClassificationID = baseIDs.NewClassificationID(qualifiedConstants.MaintainerImmutables, qualifiedConstants.MaintainerMutables) diff --git a/schema/ids/dataID.go b/schema/ids/dataID.go index 9d0325346..c8ff730e7 100644 --- a/schema/ids/dataID.go +++ b/schema/ids/dataID.go @@ -5,6 +5,6 @@ package ids type DataID interface { ID - GetHashID() ID + GetHashID() HashID IsDataID() } diff --git a/schema/ids/identityID.go b/schema/ids/identityID.go index 3a67c907d..a0a4ee2c7 100644 --- a/schema/ids/identityID.go +++ b/schema/ids/identityID.go @@ -2,6 +2,6 @@ package ids type IdentityID interface { ID - GetHashID() ID + GetHashID() HashID IsIdentityID() } diff --git a/schema/ids/propertyID.go b/schema/ids/propertyID.go index fd945fc0b..0d46c9c9e 100644 --- a/schema/ids/propertyID.go +++ b/schema/ids/propertyID.go @@ -4,8 +4,8 @@ package ids type PropertyID interface { - GetKey() ID - GetType() ID + GetKey() StringID + GetType() StringID ID IsPropertyID() } diff --git a/schema/lists/base/codec.go b/schema/lists/base/codec.go new file mode 100644 index 000000000..d0b0363f6 --- /dev/null +++ b/schema/lists/base/codec.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +func RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, dataList{}) + codecUtilities.RegisterModuleConcrete(codec, idList{}) + codecUtilities.RegisterModuleConcrete(codec, list{}) + codecUtilities.RegisterModuleConcrete(codec, propertyList{}) + codecUtilities.RegisterModuleConcrete(codec, signatureList{}) +} diff --git a/schema/lists/base/codec_test.go b/schema/lists/base/codec_test.go new file mode 100644 index 000000000..f8fde6322 --- /dev/null +++ b/schema/lists/base/codec_test.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + + {"+ve", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/lists/base/dataList_test.go b/schema/lists/base/dataList_test.go index ac0f535a2..7c76f0501 100644 --- a/schema/lists/base/dataList_test.go +++ b/schema/lists/base/dataList_test.go @@ -4,6 +4,10 @@ package base import ( + "reflect" + "strings" + "testing" + "github.com/AssetMantle/modules/schema/data" dataConstants "github.com/AssetMantle/modules/schema/data/constants" "github.com/AssetMantle/modules/schema/errors/constants" @@ -11,9 +15,6 @@ import ( baseIDs "github.com/AssetMantle/modules/schema/ids/base" "github.com/AssetMantle/modules/schema/lists" "github.com/AssetMantle/modules/schema/traits" - "reflect" - "strings" - "testing" ) func TestNewDataList(t *testing.T) { @@ -171,7 +172,7 @@ func Test_dataToListables(t *testing.T) { } } -//mocks +// mocks type stringData struct { Value string `json:"value"` } diff --git a/schema/lists/base/idList.go b/schema/lists/base/idList.go new file mode 100644 index 000000000..eb1d1b153 --- /dev/null +++ b/schema/lists/base/idList.go @@ -0,0 +1,49 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/traits" +) + +type idList struct { + lists.List +} + +var _ lists.IDList = (*idList)(nil) + +func (idList idList) GetList() []ids.ID { + returnIDList := make([]ids.ID, idList.List.Size()) + + for i, listable := range idList.List.Get() { + returnIDList[i] = listable.(ids.ID) + } + + return returnIDList +} +func (idList idList) Search(id ids.ID) (index int, found bool) { + return idList.List.Search(id) +} +func (idList idList) Add(ids ...ids.ID) lists.IDList { + idList.List = idList.List.Add(idsToListables(ids...)...) + return idList +} +func (idList idList) Remove(ids ...ids.ID) lists.IDList { + idList.List = idList.List.Remove(idsToListables(ids...)...) + return idList +} +func idsToListables(ids ...ids.ID) []traits.Listable { + listables := make([]traits.Listable, len(ids)) + for i, id := range ids { + listables[i] = id + } + return listables +} +func NewIDList(ids ...ids.ID) lists.IDList { + return &idList{ + List: NewList(idsToListables(ids...)...), + } +} diff --git a/schema/lists/base/idList_test.go b/schema/lists/base/idList_test.go index 72100f68d..82e3820da 100644 --- a/schema/lists/base/idList_test.go +++ b/schema/lists/base/idList_test.go @@ -4,13 +4,14 @@ package base import ( + "reflect" + "strings" + "testing" + "github.com/AssetMantle/modules/schema/errors/constants" "github.com/AssetMantle/modules/schema/ids" "github.com/AssetMantle/modules/schema/lists" "github.com/AssetMantle/modules/schema/traits" - "reflect" - "strings" - "testing" ) func Test_idList_Add(t *testing.T) { diff --git a/schema/lists/base/list.go b/schema/lists/base/list.go new file mode 100644 index 000000000..889e448e4 --- /dev/null +++ b/schema/lists/base/list.go @@ -0,0 +1,82 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "sort" + + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/traits" +) + +// TODO type check that list is same type and test cases +type list []traits.Listable + +var _ lists.List = (*list)(nil) + +func (list list) Get() []traits.Listable { + return list +} +func (list list) Size() int { + return len(list) +} +func (list list) Search(listable traits.Listable) (int, bool) { + index := sort.Search( + len(list), + func(i int) bool { + return list[i].Compare(listable) >= 0 + }, + ) + + if index < len(list) && list[index].Compare(listable) == 0 { + return index, true + } + + return index, false +} +func (list list) Add(listables ...traits.Listable) lists.List { + updatedList := list + + for _, listable := range listables { + if index, found := updatedList.Search(listable); !found { + updatedList = append(updatedList, listable) + copy(updatedList[index+1:], updatedList[index:]) + updatedList[index] = listable + } + } + + return updatedList +} +func (list list) Remove(listables ...traits.Listable) lists.List { + updatedList := list + + for _, listable := range listables { + if index, found := updatedList.Search(listable); found { + updatedList = append(updatedList[:index], updatedList[index+1:]...) + } + } + + return updatedList +} +func (list list) Mutate(listables ...traits.Listable) lists.List { + // TODO write test + updatedList := list + + for _, listable := range listables { + if index, found := updatedList.Search(listable); found { + updatedList[index] = listable + } + } + + return updatedList +} + +func NewList(listables ...traits.Listable) lists.List { + list := list(listables) + sort.Slice(list, func(i, j int) bool { + return list[i].Compare(list[j]) <= 0 + }) + + return list +} diff --git a/schema/lists/base/list_test.go b/schema/lists/base/list_test.go index 6d4cf7dd1..757c0e60c 100644 --- a/schema/lists/base/list_test.go +++ b/schema/lists/base/list_test.go @@ -4,13 +4,15 @@ package base import ( + "reflect" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/AssetMantle/modules/schema/ids/base" "github.com/AssetMantle/modules/schema/lists" baseProperties "github.com/AssetMantle/modules/schema/properties/base" "github.com/AssetMantle/modules/schema/traits" - "github.com/stretchr/testify/assert" - "reflect" - "testing" ) func TestNewList(t *testing.T) { diff --git a/schema/lists/base/propertyList.go b/schema/lists/base/propertyList.go new file mode 100644 index 000000000..9d45a3870 --- /dev/null +++ b/schema/lists/base/propertyList.go @@ -0,0 +1,71 @@ +package base + +import ( + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/properties" + "github.com/AssetMantle/modules/schema/properties/base" + "github.com/AssetMantle/modules/schema/traits" +) + +type propertyList struct { + lists.List +} + +var _ lists.PropertyList = (*propertyList)(nil) + +func (propertyList propertyList) GetProperty(propertyID ids.PropertyID) properties.Property { + if i, found := propertyList.Search(base.NewEmptyMesaPropertyFromID(propertyID)); found { + return propertyList.GetList()[i] + } + + return nil +} +func (propertyList propertyList) GetList() []properties.Property { + Properties := make([]properties.Property, propertyList.List.Size()) + for i, listable := range propertyList.List.Get() { + Properties[i] = listable.(properties.Property) + } + return Properties +} +func (propertyList propertyList) GetPropertyIDList() lists.IDList { + propertyIDList := NewIDList() + for _, property := range propertyList.GetList() { + propertyIDList = propertyIDList.Add(property.GetID()) + } + return propertyIDList +} +func (propertyList propertyList) Add(properties ...properties.Property) lists.PropertyList { + propertyList.List = propertyList.List.Add(propertiesToListables(properties...)...) + return propertyList +} +func (propertyList propertyList) Remove(properties ...properties.Property) lists.PropertyList { + propertyList.List = propertyList.List.Remove(propertiesToListables(properties...)...) + return propertyList +} +func (propertyList propertyList) Mutate(properties ...properties.Property) lists.PropertyList { + propertyList.List = propertyList.List.Mutate(propertiesToListables(properties...)...) + return propertyList +} +func (propertyList propertyList) ScrubData() lists.PropertyList { + newPropertyList := NewPropertyList() + for _, listable := range propertyList.List.Get() { + if property := listable.(properties.Property); property.IsMeta() { + newPropertyList = newPropertyList.Add(property.(properties.MetaProperty).ScrubData()) + } else { + newPropertyList = newPropertyList.Add(property) + } + } + return newPropertyList +} +func propertiesToListables(properties ...properties.Property) []traits.Listable { + listables := make([]traits.Listable, len(properties)) + for i, property := range properties { + listables[i] = property + } + return listables +} + +func NewPropertyList(properties ...properties.Property) lists.PropertyList { + return propertyList{List: NewList(propertiesToListables(properties...)...)} +} diff --git a/schema/lists/base/propertyList_test.go b/schema/lists/base/propertyList_test.go index 1e697bc6a..44b06bfc1 100644 --- a/schema/lists/base/propertyList_test.go +++ b/schema/lists/base/propertyList_test.go @@ -4,19 +4,21 @@ package base import ( + "reflect" + "testing" + "github.com/AssetMantle/modules/schema/data" dataConstants "github.com/AssetMantle/modules/schema/data/constants" "github.com/AssetMantle/modules/schema/errors/constants" baseIDs "github.com/AssetMantle/modules/schema/ids/base" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/AssetMantle/modules/schema/ids" "github.com/AssetMantle/modules/schema/lists" "github.com/AssetMantle/modules/schema/properties" baseProperties "github.com/AssetMantle/modules/schema/properties/base" "github.com/AssetMantle/modules/schema/traits" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "reflect" - "testing" ) func TestNewPropertyList(t *testing.T) { @@ -29,7 +31,7 @@ func TestNewPropertyList(t *testing.T) { want lists.PropertyList }{ {"+ve", args{[]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData")), baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}}, propertyList{List: NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData")), baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}...)...)}}, - {"-ve", args{[]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData")), baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData"))}}, propertyList{List: NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData")), baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData"))}...)...)}}, //TODO: Should fail for duplicate Property + {"-ve", args{[]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData")), baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData"))}}, propertyList{List: NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData")), baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData"))}...)...)}}, // TODO: Should fail for duplicate Property } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -74,8 +76,8 @@ func Test_propertyList_Add(t *testing.T) { want lists.PropertyList }{ {"+ve", fields{NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData"))}...)...)}, args{[]properties.Property{baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}}, NewPropertyList([]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData")), baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}...)}, - {"-ve", fields{NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData"))}...)...)}, args{[]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewDecData(sdkTypes.NewDec(1)))}}, NewPropertyList([]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData")), baseProperties.NewMetaProperty(NewStringID("ID1"), NewDecData(sdkTypes.NewDec(1)))}...)}, //TODO: Should fail as add method should not be able to mutate/add property with existing key - {"+ve with nil", fields{NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData"))}...)...)}, args{nil}, NewPropertyList([]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData"))}...)}, //TODO: Should fail as add method should not be able to mutate/add property with existing key + {"-ve", fields{NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData"))}...)...)}, args{[]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewDecData(sdkTypes.NewDec(1)))}}, NewPropertyList([]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData")), baseProperties.NewMetaProperty(NewStringID("ID1"), NewDecData(sdkTypes.NewDec(1)))}...)}, // TODO: Should fail as add method should not be able to mutate/add property with existing key + {"+ve with nil", fields{NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData"))}...)...)}, args{nil}, NewPropertyList([]properties.Property{baseProperties.NewMetaProperty(NewStringID("ID1"), NewStringData("ImmutableData"))}...)}, // TODO: Should fail as add method should not be able to mutate/add property with existing key } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -127,7 +129,7 @@ func Test_propertyList_GetProperty(t *testing.T) { }{ {"+ve Meta", fields{NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}...)...)}, args{baseIDs.NewPropertyID(NewStringID("supply"), NewStringID("D"))}, baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}, {"+ve Mesa", fields{NewList(propertiesToListables([]properties.Property{baseProperties.NewMesaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}...)...)}, args{baseIDs.NewPropertyID(NewStringID("supply"), NewStringID("D"))}, baseProperties.NewMesaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}, - {"-ve", fields{NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}...)...)}, args{propertyID: nil}, baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}, //TODO: panics if propertyID is nil + {"-ve", fields{NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}...)...)}, args{propertyID: nil}, baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}, // TODO: panics if propertyID is nil {"-ve", fields{NewList(propertiesToListables([]properties.Property{baseProperties.NewEmptyMetaPropertyFromID(baseIDs.NewPropertyID(NewStringID("supply"), NewStringID("D")))}...)...)}, args{baseIDs.NewPropertyID(NewStringID("supply"), NewStringID("D"))}, baseProperties.NewEmptyMetaPropertyFromID(baseIDs.NewPropertyID(NewStringID("supply"), NewStringID("D")))}, } for _, tt := range tests { @@ -179,7 +181,7 @@ func Test_propertyList_Mutate(t *testing.T) { want lists.PropertyList }{ {"+ve", fields{NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}...)...)}, args{[]properties.Property{baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(2)))}}, NewPropertyList([]properties.Property{baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(2)))}...)}, - //{"+ve", fields{NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}...)...)}, args{[]properties.Property{baseProperties.NewMetaProperty(NewStringID("supply"), NewStringData("test"))}}, NewPropertyList([]properties.Property{baseProperties.NewMetaProperty(NewStringID("supply"), NewStringData("test"))}...)}, //TODO: Should handle error if different property data is tried to mutate + // {"+ve", fields{NewList(propertiesToListables([]properties.Property{baseProperties.NewMetaProperty(NewStringID("supply"), NewDecData(sdkTypes.NewDec(1)))}...)...)}, args{[]properties.Property{baseProperties.NewMetaProperty(NewStringID("supply"), NewStringData("test"))}}, NewPropertyList([]properties.Property{baseProperties.NewMetaProperty(NewStringID("supply"), NewStringData("test"))}...)}, //TODO: Should handle error if different property data is tried to mutate } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/schema/lists/base/signatureList.go b/schema/lists/base/signatureList.go new file mode 100644 index 000000000..10453b6f9 --- /dev/null +++ b/schema/lists/base/signatureList.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "github.com/AssetMantle/modules/schema/lists" +) + +type signatureList struct { + lists.List +} + +var _ lists.SignatureList = (*signatureList)(nil) diff --git a/schema/lists/codec.go b/schema/lists/codec.go index 4d7d94bf2..f6b696b31 100644 --- a/schema/lists/codec.go +++ b/schema/lists/codec.go @@ -7,9 +7,10 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { +func RegisterCodec(codec *codec.Codec) { codec.RegisterInterface((*DataList)(nil), nil) codec.RegisterInterface((*IDList)(nil), nil) codec.RegisterInterface((*List)(nil), nil) codec.RegisterInterface((*PropertyList)(nil), nil) + codec.RegisterInterface((*SignatureList)(nil), nil) } diff --git a/schema/lists/codec_test.go b/schema/lists/codec_test.go new file mode 100644 index 000000000..776c9142d --- /dev/null +++ b/schema/lists/codec_test.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package lists + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + + {"+ve", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/lists/constants/string.go b/schema/lists/constants/string.go deleted file mode 100644 index ca52b6c0c..000000000 --- a/schema/lists/constants/string.go +++ /dev/null @@ -1,3 +0,0 @@ -package constants - -const ListStringSeparator = "," diff --git a/schema/lists/idList.go b/schema/lists/idList.go index 5e10cc8fb..15c0d1131 100644 --- a/schema/lists/idList.go +++ b/schema/lists/idList.go @@ -9,7 +9,6 @@ import ( type IDList interface { Size() int - HasRepeats() bool GetList() []ids.ID Search(ids.ID) (index int, found bool) Add(...ids.ID) IDList diff --git a/schema/lists/list.go b/schema/lists/list.go index 92bbdeae3..0dd3ca111 100644 --- a/schema/lists/list.go +++ b/schema/lists/list.go @@ -20,9 +20,8 @@ type List interface { // Search // * returns true and index of element if element is found // * return false and index of insertion if element is not found - Search(traits.Listable) (index int, found bool) // ***** TODO prevent compare panic - HasRepeats() bool - Add(...traits.Listable) List // ***** TODO prevent compare panic - Remove(...traits.Listable) List // ***** TODO prevent compare panic - Mutate(...traits.Listable) List // ***** TODO prevent compare panic + Search(traits.Listable) (index int, found bool) // TODO prevent compare panic + Add(...traits.Listable) List // TODO prevent compare panic + Remove(...traits.Listable) List // TODO prevent compare panic + Mutate(...traits.Listable) List // TODO prevent compare panic } diff --git a/schema/lists/propertyList.go b/schema/lists/propertyList.go index d19f9544d..8ebc1a918 100644 --- a/schema/lists/propertyList.go +++ b/schema/lists/propertyList.go @@ -6,7 +6,6 @@ import ( ) type PropertyList interface { - Size() int GetProperty(ids.PropertyID) properties.Property GetList() []properties.Property GetPropertyIDList() IDList @@ -14,6 +13,6 @@ type PropertyList interface { Add(...properties.Property) PropertyList Remove(...properties.Property) PropertyList Mutate(...properties.Property) PropertyList - HasRepeats() bool + ScrubData() PropertyList } diff --git a/schema/lists/signatureList.go b/schema/lists/signatureList.go new file mode 100644 index 000000000..690c22433 --- /dev/null +++ b/schema/lists/signatureList.go @@ -0,0 +1,7 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package lists + +type SignatureList interface { +} diff --git a/schema/lists/utilities/metaPropertyList.go b/schema/lists/utilities/metaPropertyList.go deleted file mode 100644 index b3bba1ce5..000000000 --- a/schema/lists/utilities/metaPropertyList.go +++ /dev/null @@ -1 +0,0 @@ -package utilities diff --git a/schema/lists/utilities/propertyList.go b/schema/lists/utilities/propertyList.go new file mode 100644 index 000000000..9ccf7b34f --- /dev/null +++ b/schema/lists/utilities/propertyList.go @@ -0,0 +1,27 @@ +package utilities + +import ( + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties" + "github.com/AssetMantle/modules/schema/properties/utilities" + stringUtilities "github.com/AssetMantle/modules/utilities/string" +) + +func ReadMetaPropertyList(metaPropertiesString string) (lists.PropertyList, error) { + var Properties []properties.Property + + metaProperties := stringUtilities.SplitListString(metaPropertiesString) + for _, metaPropertyString := range metaProperties { + if metaPropertyString != "" { + metaProperty, err := utilities.ReadMetaProperty(metaPropertyString) + if err != nil { + return nil, err + } + + Properties = append(Properties, metaProperty) + } + } + + return base.NewPropertyList(Properties...), nil +} diff --git a/schema/parameters/base/codec.go b/schema/parameters/base/codec.go index 890aa3002..b299eb501 100644 --- a/schema/parameters/base/codec.go +++ b/schema/parameters/base/codec.go @@ -3,9 +3,9 @@ package base import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/AssetMantle/modules/schema" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { - schema.RegisterModuleConcrete(codec, parameter{}) +func RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, parameter{}) } diff --git a/schema/parameters/base/codec_test.go b/schema/parameters/base/codec_test.go new file mode 100644 index 000000000..f8fde6322 --- /dev/null +++ b/schema/parameters/base/codec_test.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + + {"+ve", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/parameters/base/parameter.go b/schema/parameters/base/parameter.go index bf6a01fab..c66acf900 100644 --- a/schema/parameters/base/parameter.go +++ b/schema/parameters/base/parameter.go @@ -4,21 +4,28 @@ package base import ( + "encoding/json" + "github.com/AssetMantle/modules/schema/data" "github.com/AssetMantle/modules/schema/ids" "github.com/AssetMantle/modules/schema/parameters" ) type parameter struct { - ID ids.ID `json:"id"` - Data data.Data `json:"data"` + ID ids.StringID `json:"id"` + Data data.Data `json:"data"` validator func(interface{}) error } var _ parameters.Parameter = (*parameter)(nil) func (parameter parameter) String() string { - return parameter.ID.String() + bytes, err := json.Marshal(parameter) + if err != nil { + return err.Error() + } + + return string(bytes) } func (parameter parameter) Equal(compareParameter parameters.Parameter) bool { if compareParameter != nil && parameter.ID.Compare(compareParameter.GetID()) == 0 && parameter.Data.GetType().Compare(compareParameter.GetData().GetType()) == 0 && parameter.Data.Compare(compareParameter.GetData()) == 0 { @@ -44,7 +51,7 @@ func (parameter parameter) Mutate(data data.Data) parameters.Parameter { return parameter } -func NewParameter(id ids.ID, data data.Data, validator func(interface{}) error) parameters.Parameter { +func NewParameter(id ids.StringID, data data.Data, validator func(interface{}) error) parameters.Parameter { return parameter{ ID: id, Data: data, diff --git a/schema/parameters/codec.go b/schema/parameters/codec.go index 35a5a7542..50b9cefa7 100644 --- a/schema/parameters/codec.go +++ b/schema/parameters/codec.go @@ -4,6 +4,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { +func RegisterCodec(codec *codec.Codec) { codec.RegisterInterface((*Parameter)(nil), nil) } diff --git a/schema/parameters/codec_test.go b/schema/parameters/codec_test.go new file mode 100644 index 000000000..de149227e --- /dev/null +++ b/schema/parameters/codec_test.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package parameters + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + + {"+ve", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/properties/base/codec.go b/schema/properties/base/codec.go index 71d6c1572..ccd572e34 100644 --- a/schema/properties/base/codec.go +++ b/schema/properties/base/codec.go @@ -3,10 +3,10 @@ package base import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/AssetMantle/modules/schema" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { - schema.RegisterModuleConcrete(codec, metaProperty{}) - schema.RegisterModuleConcrete(codec, mesaProperty{}) +func RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, metaProperty{}) + codecUtilities.RegisterModuleConcrete(codec, mesaProperty{}) } diff --git a/schema/properties/base/codec_test.go b/schema/properties/base/codec_test.go new file mode 100644 index 000000000..f8fde6322 --- /dev/null +++ b/schema/properties/base/codec_test.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + + {"+ve", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/properties/base/mesaProperty.go b/schema/properties/base/mesaProperty.go index 852399c7f..67bf4eaf4 100644 --- a/schema/properties/base/mesaProperty.go +++ b/schema/properties/base/mesaProperty.go @@ -13,26 +13,26 @@ import ( ) type mesaProperty struct { - PropertyID ids.ID - DataID ids.ID + ID ids.PropertyID + DataID ids.DataID } var _ properties.MesaProperty = (*mesaProperty)(nil) -func (mesaProperty mesaProperty) GetID() ids.ID { - return mesaProperty.PropertyID +func (mesaProperty mesaProperty) GetID() ids.PropertyID { + return mesaProperty.ID } -func (mesaProperty mesaProperty) GetDataID() ids.ID { +func (mesaProperty mesaProperty) GetDataID() ids.DataID { return mesaProperty.DataID } -func (mesaProperty mesaProperty) GetKey() ids.ID { - return baseIDs.NewStringID(mesaProperty.PropertyID.(*baseIDs.ID).GetPropertyID().KeyID.IdString) +func (mesaProperty mesaProperty) GetKey() ids.StringID { + return mesaProperty.ID.GetKey() } -func (mesaProperty mesaProperty) GetType() ids.ID { - return baseIDs.NewStringID(mesaProperty.PropertyID.(*baseIDs.ID).GetPropertyID().TypeID.IdString) +func (mesaProperty mesaProperty) GetType() ids.StringID { + return mesaProperty.ID.GetType() } func (mesaProperty mesaProperty) GetHash() ids.ID { - return baseIDs.NewHashID(mesaProperty.DataID.(*baseIDs.ID).GetDataID().HashId.IdBytes) + return mesaProperty.DataID.GetHashID() } func (mesaProperty mesaProperty) IsMeta() bool { return false @@ -59,12 +59,12 @@ func propertyFromInterface(listable traits.Listable) (properties.Property, error func NewEmptyMesaPropertyFromID(propertyID ids.PropertyID) properties.Property { return mesaProperty{ - PropertyID: propertyID, + ID: propertyID, } } -func NewMesaProperty(key ids.ID, data data.Data) properties.MesaProperty { +func NewMesaProperty(key ids.StringID, data data.Data) properties.MesaProperty { return mesaProperty{ - PropertyID: baseIDs.GeneratePropertyID(key, data.GetType()), - DataID: data.GetID(), + ID: baseIDs.NewPropertyID(key, data.GetType()), + DataID: data.GetID(), } } diff --git a/schema/properties/base/mesaProperty.pb.go b/schema/properties/base/mesaProperty.pb.go deleted file mode 100644 index 3f0952a01..000000000 --- a/schema/properties/base/mesaProperty.pb.go +++ /dev/null @@ -1,394 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/properties/base/mesaProperty.proto - -package base - -import ( - fmt "fmt" - base1 "github.com/AssetMantle/modules/schema/data/base" - base "github.com/AssetMantle/modules/schema/ids/base" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type MesaProperty struct { - PropertyId *base.PropertyID `protobuf:"bytes,1,opt,name=property_id,json=propertyId,proto3" json:"property_id,omitempty"` - Data *base1.Data `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MesaProperty) Reset() { *m = MesaProperty{} } -func (m *MesaProperty) String() string { return proto.CompactTextString(m) } -func (*MesaProperty) ProtoMessage() {} -func (*MesaProperty) Descriptor() ([]byte, []int) { - return fileDescriptor_a18241b6bd5ec330, []int{0} -} -func (m *MesaProperty) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MesaProperty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MesaProperty.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MesaProperty) XXX_Merge(src proto.Message) { - xxx_messageInfo_MesaProperty.Merge(m, src) -} -func (m *MesaProperty) XXX_Size() int { - return m.Size() -} -func (m *MesaProperty) XXX_DiscardUnknown() { - xxx_messageInfo_MesaProperty.DiscardUnknown(m) -} - -var xxx_messageInfo_MesaProperty proto.InternalMessageInfo - -func (m *MesaProperty) GetPropertyId() *base.PropertyID { - if m != nil { - return m.PropertyId - } - return nil -} - -func (m *MesaProperty) GetData() *base1.Data { - if m != nil { - return m.Data - } - return nil -} - -func init() { - proto.RegisterType((*MesaProperty)(nil), "base.MesaProperty") -} - -func init() { - proto.RegisterFile("schema/properties/base/mesaProperty.proto", fileDescriptor_a18241b6bd5ec330) -} - -var fileDescriptor_a18241b6bd5ec330 = []byte{ - // 272 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x2c, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0x28, 0xca, 0x2f, 0x48, 0x2d, 0x2a, 0xc9, 0x4c, 0x2d, 0xd6, 0x4f, 0x4a, - 0x2c, 0x4e, 0xd5, 0xcf, 0x4d, 0x2d, 0x4e, 0x0c, 0x80, 0x88, 0x55, 0xea, 0x15, 0x14, 0xe5, 0x97, - 0xe4, 0x0b, 0xb1, 0x80, 0x24, 0xa4, 0x14, 0xa0, 0x1a, 0x32, 0x53, 0xa0, 0x2a, 0xa1, 0x3a, 0x2b, - 0x3d, 0x5d, 0x20, 0xea, 0xa4, 0xa4, 0xa1, 0x2a, 0x52, 0x12, 0x4b, 0x12, 0x21, 0x4a, 0x40, 0x2c, - 0x88, 0xa4, 0x52, 0x22, 0x17, 0x8f, 0x2f, 0x92, 0xd1, 0x42, 0x86, 0x5c, 0xdc, 0x30, 0x03, 0xe2, - 0x33, 0x53, 0x24, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0x04, 0xf4, 0x40, 0xda, 0xf4, 0x02, 0xe0, - 0x26, 0x07, 0x71, 0xc1, 0x6d, 0x49, 0x11, 0x92, 0xe3, 0x62, 0x01, 0x19, 0x28, 0xc1, 0x04, 0x56, - 0xcb, 0x05, 0x51, 0xeb, 0x92, 0x58, 0x92, 0x18, 0x04, 0x16, 0x77, 0x9a, 0xc3, 0x78, 0xe2, 0x91, - 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, - 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x5c, 0x1c, 0xc9, 0xf9, 0xb9, 0x60, 0xf5, 0x4e, 0x82, - 0xc8, 0xae, 0x08, 0x00, 0x39, 0x2d, 0x80, 0x31, 0xca, 0x34, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, - 0x2f, 0x39, 0x3f, 0x57, 0xdf, 0xb1, 0xb8, 0x38, 0xb5, 0xc4, 0x37, 0x31, 0xaf, 0x24, 0x27, 0x55, - 0x3f, 0x37, 0x3f, 0xa5, 0x34, 0x27, 0xb5, 0x58, 0x1f, 0x7b, 0x58, 0x2d, 0x62, 0x62, 0x76, 0x8a, - 0x88, 0x58, 0xc5, 0xc4, 0xe2, 0x94, 0x58, 0x9c, 0x7a, 0x0a, 0x42, 0x3d, 0x62, 0x12, 0x00, 0x51, - 0x31, 0xee, 0x01, 0x4e, 0xbe, 0xa9, 0x25, 0x89, 0x20, 0x77, 0xbd, 0x82, 0xc8, 0x24, 0xb1, 0x81, - 0x03, 0xc2, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x9b, 0xa8, 0xf9, 0xb9, 0x7a, 0x01, 0x00, 0x00, -} - -func (m *MesaProperty) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MesaProperty) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MesaProperty) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Data != nil { - { - size, err := m.Data.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMesaProperty(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if m.PropertyId != nil { - { - size, err := m.PropertyId.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMesaProperty(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintMesaProperty(dAtA []byte, offset int, v uint64) int { - offset -= sovMesaProperty(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MesaProperty) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PropertyId != nil { - l = m.PropertyId.Size() - n += 1 + l + sovMesaProperty(uint64(l)) - } - if m.Data != nil { - l = m.Data.Size() - n += 1 + l + sovMesaProperty(uint64(l)) - } - return n -} - -func sovMesaProperty(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMesaProperty(x uint64) (n int) { - return sovMesaProperty(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MesaProperty) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMesaProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MesaProperty: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MesaProperty: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PropertyId", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMesaProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMesaProperty - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMesaProperty - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.PropertyId == nil { - m.PropertyId = &base.PropertyID{} - } - if err := m.PropertyId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMesaProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMesaProperty - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMesaProperty - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Data == nil { - m.Data = &base1.Data{} - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMesaProperty(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMesaProperty - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMesaProperty(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMesaProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMesaProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMesaProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMesaProperty - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMesaProperty - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMesaProperty - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMesaProperty = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMesaProperty = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMesaProperty = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/properties/base/mesaProperty.proto b/schema/properties/base/mesaProperty.proto deleted file mode 100644 index 22a033a7f..000000000 --- a/schema/properties/base/mesaProperty.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/ids/base/propertyID.proto"; -import "schema/data/base/data.proto"; - -message MesaProperty{ - PropertyID property_id = 1; - Data data = 2; -} \ No newline at end of file diff --git a/schema/properties/base/mesaProperty_test.go b/schema/properties/base/mesaProperty_test.go index bd3752797..bbb716b66 100644 --- a/schema/properties/base/mesaProperty_test.go +++ b/schema/properties/base/mesaProperty_test.go @@ -4,12 +4,13 @@ package base import ( - dataConstants "github.com/AssetMantle/modules/schema/data/constants" - "github.com/AssetMantle/modules/schema/errors/constants" "reflect" "strings" "testing" + dataConstants "github.com/AssetMantle/modules/schema/data/constants" + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/data" "github.com/AssetMantle/modules/schema/ids" "github.com/AssetMantle/modules/schema/ids/base" diff --git a/schema/properties/base/metaProperty.go b/schema/properties/base/metaProperty.go index 75343b006..a3962b5c3 100644 --- a/schema/properties/base/metaProperty.go +++ b/schema/properties/base/metaProperty.go @@ -13,8 +13,8 @@ import ( ) type metaProperty struct { - PropertyID ids.ID - data.Data + ID ids.PropertyID `json:"id"` + Data data.Data `json:"data"` } var _ properties.MetaProperty = (*metaProperty)(nil) @@ -25,16 +25,16 @@ func (metaProperty metaProperty) GetData() data.Data { func (metaProperty metaProperty) ScrubData() properties.MesaProperty { return NewMesaProperty(metaProperty.GetKey(), metaProperty.GetData()) } -func (metaProperty metaProperty) GetID() ids.ID { - return metaProperty.PropertyID +func (metaProperty metaProperty) GetID() ids.PropertyID { + return metaProperty.ID } -func (metaProperty metaProperty) GetDataID() ids.ID { +func (metaProperty metaProperty) GetDataID() ids.DataID { return metaProperty.Data.GetID() } -func (metaProperty metaProperty) GetKey() ids.ID { - return baseIDs.NewStringID(metaProperty.PropertyID.(*baseIDs.ID).GetPropertyID().KeyID.IdString) +func (metaProperty metaProperty) GetKey() ids.StringID { + return metaProperty.ID.GetKey() } -func (metaProperty metaProperty) GetType() ids.ID { +func (metaProperty metaProperty) GetType() ids.StringID { return metaProperty.Data.GetType() } func (metaProperty metaProperty) IsMeta() bool { @@ -51,15 +51,15 @@ func (metaProperty metaProperty) Compare(listable traits.Listable) int { func NewEmptyMetaPropertyFromID(propertyID ids.PropertyID) properties.MetaProperty { return metaProperty{ - PropertyID: propertyID, + ID: propertyID, } } -func NewMetaProperty(key ids.ID, data data.Data) properties.MetaProperty { +func NewMetaProperty(key ids.StringID, data data.Data) properties.MetaProperty { if data == nil || key == nil { panic(errorConstants.MetaDataError) } return metaProperty{ - PropertyID: baseIDs.GeneratePropertyID(key, data.GetType()), - Data: data, + ID: baseIDs.NewPropertyID(key, data.GetType()), + Data: data, } } diff --git a/schema/properties/base/metaProperty.pb.go b/schema/properties/base/metaProperty.pb.go deleted file mode 100644 index 9e136dcd9..000000000 --- a/schema/properties/base/metaProperty.pb.go +++ /dev/null @@ -1,394 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/properties/base/metaProperty.proto - -package base - -import ( - fmt "fmt" - base1 "github.com/AssetMantle/modules/schema/data/base" - base "github.com/AssetMantle/modules/schema/ids/base" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type MetaProperty struct { - PropertyId *base.PropertyID `protobuf:"bytes,1,opt,name=property_id,json=propertyId,proto3" json:"property_id,omitempty"` - Data *base1.Data `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MetaProperty) Reset() { *m = MetaProperty{} } -func (m *MetaProperty) String() string { return proto.CompactTextString(m) } -func (*MetaProperty) ProtoMessage() {} -func (*MetaProperty) Descriptor() ([]byte, []int) { - return fileDescriptor_1c07e4dee40daa79, []int{0} -} -func (m *MetaProperty) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MetaProperty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MetaProperty.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MetaProperty) XXX_Merge(src proto.Message) { - xxx_messageInfo_MetaProperty.Merge(m, src) -} -func (m *MetaProperty) XXX_Size() int { - return m.Size() -} -func (m *MetaProperty) XXX_DiscardUnknown() { - xxx_messageInfo_MetaProperty.DiscardUnknown(m) -} - -var xxx_messageInfo_MetaProperty proto.InternalMessageInfo - -func (m *MetaProperty) GetPropertyId() *base.PropertyID { - if m != nil { - return m.PropertyId - } - return nil -} - -func (m *MetaProperty) GetData() *base1.Data { - if m != nil { - return m.Data - } - return nil -} - -func init() { - proto.RegisterType((*MetaProperty)(nil), "base.MetaProperty") -} - -func init() { - proto.RegisterFile("schema/properties/base/metaProperty.proto", fileDescriptor_1c07e4dee40daa79) -} - -var fileDescriptor_1c07e4dee40daa79 = []byte{ - // 270 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x2c, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0x28, 0xca, 0x2f, 0x48, 0x2d, 0x2a, 0xc9, 0x4c, 0x2d, 0xd6, 0x4f, 0x4a, - 0x2c, 0x4e, 0xd5, 0xcf, 0x4d, 0x2d, 0x49, 0x0c, 0x80, 0x88, 0x55, 0xea, 0x15, 0x14, 0xe5, 0x97, - 0xe4, 0x0b, 0xb1, 0x80, 0x24, 0xa4, 0x14, 0xa0, 0x1a, 0x32, 0x53, 0xa0, 0x2a, 0xa1, 0x3a, 0x2b, - 0x3d, 0x5d, 0x20, 0xea, 0xa4, 0xa4, 0xa1, 0x2a, 0x52, 0x12, 0x4b, 0x12, 0x21, 0x4a, 0x40, 0x2c, - 0x88, 0xa4, 0x52, 0x22, 0x17, 0x8f, 0x2f, 0x92, 0xd1, 0x42, 0x86, 0x5c, 0xdc, 0x30, 0x03, 0xe2, - 0x33, 0x53, 0x24, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0x04, 0xf4, 0x40, 0xda, 0xf4, 0x02, 0xe0, - 0x26, 0x07, 0x71, 0xc1, 0x6d, 0x49, 0x11, 0x92, 0xe3, 0x62, 0x01, 0x19, 0x28, 0xc1, 0x04, 0x56, - 0xcb, 0x05, 0x51, 0xeb, 0x92, 0x58, 0x92, 0x18, 0x04, 0x16, 0x77, 0x9a, 0xc3, 0x78, 0xe2, 0x91, - 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, - 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x5c, 0x1c, 0xc9, 0xf9, 0xb9, 0x60, 0xf5, 0x4e, 0x82, - 0xc8, 0xae, 0x08, 0x00, 0x39, 0x2d, 0x80, 0x31, 0xca, 0x34, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, - 0x2f, 0x39, 0x3f, 0x57, 0xdf, 0xb1, 0xb8, 0x38, 0xb5, 0xc4, 0x37, 0x31, 0xaf, 0x24, 0x27, 0x55, - 0x3f, 0x37, 0x3f, 0xa5, 0x34, 0x27, 0xb5, 0x58, 0x1f, 0x7b, 0x58, 0x2d, 0x62, 0x62, 0x76, 0x8a, - 0x88, 0x58, 0xc5, 0xc4, 0xe2, 0x94, 0x58, 0x9c, 0x7a, 0x0a, 0x42, 0x3d, 0x62, 0x12, 0x00, 0x51, - 0x31, 0xee, 0x01, 0x4e, 0x20, 0x8b, 0x40, 0xee, 0x7a, 0x05, 0x91, 0x49, 0x62, 0x03, 0x07, 0x84, - 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x05, 0xe7, 0xa2, 0xab, 0x7a, 0x01, 0x00, 0x00, -} - -func (m *MetaProperty) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MetaProperty) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MetaProperty) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Data != nil { - { - size, err := m.Data.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMetaProperty(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if m.PropertyId != nil { - { - size, err := m.PropertyId.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMetaProperty(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintMetaProperty(dAtA []byte, offset int, v uint64) int { - offset -= sovMetaProperty(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MetaProperty) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.PropertyId != nil { - l = m.PropertyId.Size() - n += 1 + l + sovMetaProperty(uint64(l)) - } - if m.Data != nil { - l = m.Data.Size() - n += 1 + l + sovMetaProperty(uint64(l)) - } - return n -} - -func sovMetaProperty(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMetaProperty(x uint64) (n int) { - return sovMetaProperty(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MetaProperty) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MetaProperty: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MetaProperty: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PropertyId", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetaProperty - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetaProperty - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.PropertyId == nil { - m.PropertyId = &base.PropertyID{} - } - if err := m.PropertyId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetaProperty - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetaProperty - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Data == nil { - m.Data = &base1.Data{} - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMetaProperty(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMetaProperty - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMetaProperty(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMetaProperty - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMetaProperty - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMetaProperty - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMetaProperty = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMetaProperty = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMetaProperty = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/properties/base/metaProperty.proto b/schema/properties/base/metaProperty.proto deleted file mode 100644 index f66b67388..000000000 --- a/schema/properties/base/metaProperty.proto +++ /dev/null @@ -1,11 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/ids/base/propertyID.proto"; -import "schema/data/base/data.proto"; - - -message MetaProperty{ - PropertyID property_id = 1; - Data data = 2; -} \ No newline at end of file diff --git a/schema/properties/base/metaProperty_test.go b/schema/properties/base/metaProperty_test.go index ae3760833..72d4ea81a 100644 --- a/schema/properties/base/metaProperty_test.go +++ b/schema/properties/base/metaProperty_test.go @@ -4,14 +4,16 @@ package base import ( + "reflect" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/AssetMantle/modules/schema/data" "github.com/AssetMantle/modules/schema/ids" "github.com/AssetMantle/modules/schema/ids/base" "github.com/AssetMantle/modules/schema/properties" "github.com/AssetMantle/modules/schema/traits" - "github.com/stretchr/testify/assert" - "reflect" - "testing" ) func createTestInput() (ids.StringID, ids.PropertyID, data.Data, properties.MetaProperty) { diff --git a/schema/properties/base/property.pb.go b/schema/properties/base/property.pb.go deleted file mode 100644 index c45c4463c..000000000 --- a/schema/properties/base/property.pb.go +++ /dev/null @@ -1,469 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/properties/base/property.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Property struct { - // Types that are valid to be assigned to Impl: - // *Property_MesaProperty - // *Property_MetaProperty - Impl isProperty_Impl `protobuf_oneof:"impl"` -} - -func (m *Property) Reset() { *m = Property{} } -func (m *Property) String() string { return proto.CompactTextString(m) } -func (*Property) ProtoMessage() {} -func (*Property) Descriptor() ([]byte, []int) { - return fileDescriptor_909d89e9aab7ad23, []int{0} -} -func (m *Property) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Property) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Property.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Property) XXX_Merge(src proto.Message) { - xxx_messageInfo_Property.Merge(m, src) -} -func (m *Property) XXX_Size() int { - return m.Size() -} -func (m *Property) XXX_DiscardUnknown() { - xxx_messageInfo_Property.DiscardUnknown(m) -} - -var xxx_messageInfo_Property proto.InternalMessageInfo - -type isProperty_Impl interface { - isProperty_Impl() - MarshalTo([]byte) (int, error) - Size() int -} - -type Property_MesaProperty struct { - MesaProperty *MesaProperty `protobuf:"bytes,1,opt,name=mesaProperty,proto3,oneof" json:"mesaProperty,omitempty"` -} -type Property_MetaProperty struct { - MetaProperty *MetaProperty `protobuf:"bytes,2,opt,name=metaProperty,proto3,oneof" json:"metaProperty,omitempty"` -} - -func (*Property_MesaProperty) isProperty_Impl() {} -func (*Property_MetaProperty) isProperty_Impl() {} - -func (m *Property) GetImpl() isProperty_Impl { - if m != nil { - return m.Impl - } - return nil -} - -func (m *Property) GetMesaProperty() *MesaProperty { - if x, ok := m.GetImpl().(*Property_MesaProperty); ok { - return x.MesaProperty - } - return nil -} - -func (m *Property) GetMetaProperty() *MetaProperty { - if x, ok := m.GetImpl().(*Property_MetaProperty); ok { - return x.MetaProperty - } - return nil -} - -// XXX_OneofWrappers is for the internal use of the proto package. -func (*Property) XXX_OneofWrappers() []interface{} { - return []interface{}{ - (*Property_MesaProperty)(nil), - (*Property_MetaProperty)(nil), - } -} - -func init() { - proto.RegisterType((*Property)(nil), "base.Property") -} - -func init() { - proto.RegisterFile("schema/properties/base/property.proto", fileDescriptor_909d89e9aab7ad23) -} - -var fileDescriptor_909d89e9aab7ad23 = []byte{ - // 252 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2d, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0x28, 0xca, 0x2f, 0x48, 0x2d, 0x2a, 0xc9, 0x4c, 0x2d, 0xd6, 0x4f, 0x4a, - 0x2c, 0x4e, 0x85, 0xf1, 0x2b, 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x58, 0x40, 0x82, 0x52, - 0x9a, 0x38, 0x14, 0xe7, 0xa6, 0x16, 0x27, 0x06, 0xa0, 0x68, 0xc0, 0xa3, 0xb4, 0x04, 0x4d, 0xa9, - 0x52, 0x1b, 0x23, 0x17, 0x07, 0x4c, 0x48, 0xc8, 0x82, 0x8b, 0x07, 0xd9, 0x34, 0x09, 0x46, 0x05, - 0x46, 0x0d, 0x6e, 0x23, 0x21, 0x3d, 0x90, 0x66, 0x3d, 0x5f, 0x24, 0x19, 0x0f, 0x86, 0x20, 0x14, - 0x95, 0x10, 0x9d, 0x08, 0xc3, 0x25, 0x98, 0x50, 0x75, 0x96, 0xa0, 0xe9, 0x44, 0xf0, 0x9d, 0xd8, - 0xb8, 0x58, 0x32, 0x73, 0x0b, 0x72, 0x9c, 0x66, 0x30, 0x9e, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, - 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, 0x78, 0x2c, 0xc7, 0x70, 0xe3, - 0xb1, 0x1c, 0x03, 0x17, 0x47, 0x72, 0x7e, 0x2e, 0xd8, 0x24, 0x27, 0x5e, 0x98, 0xb6, 0x00, 0x90, - 0xe3, 0x03, 0x18, 0xa3, 0x4c, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, - 0x1d, 0x8b, 0x8b, 0x53, 0x4b, 0x7c, 0x13, 0xf3, 0x4a, 0x72, 0x52, 0xf5, 0x73, 0xf3, 0x53, 0x4a, - 0x73, 0x52, 0x8b, 0xf5, 0xb1, 0x07, 0xc4, 0x22, 0x26, 0x66, 0xa7, 0x88, 0x88, 0x55, 0x4c, 0x2c, - 0x4e, 0x89, 0xc5, 0xa9, 0xa7, 0x20, 0xd4, 0x23, 0x26, 0x01, 0x10, 0x15, 0xe3, 0x1e, 0xe0, 0x04, - 0x72, 0x6f, 0x4a, 0x62, 0x49, 0xe2, 0x2b, 0x88, 0x4c, 0x12, 0x1b, 0x38, 0xa8, 0x8c, 0x01, 0x01, - 0x00, 0x00, 0xff, 0xff, 0xed, 0x0a, 0x36, 0xe0, 0xaf, 0x01, 0x00, 0x00, -} - -func (m *Property) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Property) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Property) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Impl != nil { - { - size := m.Impl.Size() - i -= size - if _, err := m.Impl.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - } - } - return len(dAtA) - i, nil -} - -func (m *Property_MesaProperty) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Property_MesaProperty) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.MesaProperty != nil { - { - size, err := m.MesaProperty.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProperty(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} -func (m *Property_MetaProperty) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Property_MetaProperty) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.MetaProperty != nil { - { - size, err := m.MetaProperty.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProperty(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - return len(dAtA) - i, nil -} -func encodeVarintProperty(dAtA []byte, offset int, v uint64) int { - offset -= sovProperty(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Property) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Impl != nil { - n += m.Impl.Size() - } - return n -} - -func (m *Property_MesaProperty) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.MesaProperty != nil { - l = m.MesaProperty.Size() - n += 1 + l + sovProperty(uint64(l)) - } - return n -} -func (m *Property_MetaProperty) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.MetaProperty != nil { - l = m.MetaProperty.Size() - n += 1 + l + sovProperty(uint64(l)) - } - return n -} - -func sovProperty(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozProperty(x uint64) (n int) { - return sovProperty(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Property) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Property: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Property: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MesaProperty", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProperty - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProperty - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &MesaProperty{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &Property_MesaProperty{v} - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MetaProperty", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProperty - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProperty - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &MetaProperty{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &Property_MetaProperty{v} - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProperty(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProperty - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipProperty(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthProperty - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupProperty - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthProperty - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthProperty = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProperty = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupProperty = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/properties/base/property.proto b/schema/properties/base/property.proto deleted file mode 100644 index b3f805258..000000000 --- a/schema/properties/base/property.proto +++ /dev/null @@ -1,12 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/properties/base/mesaProperty.proto"; -import "schema/properties/base/metaProperty.proto"; - -message Property{ - oneof impl { - MesaProperty mesaProperty = 1; - MetaProperty metaProperty = 2; - } -} \ No newline at end of file diff --git a/schema/properties/base/propertyI.pb.go b/schema/properties/base/propertyI.pb.go deleted file mode 100644 index 54b80317f..000000000 --- a/schema/properties/base/propertyI.pb.go +++ /dev/null @@ -1,387 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/properties/base/propertyI.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type PropertyI struct { - // Types that are valid to be assigned to Impl: - // *PropertyI_Property - Impl isPropertyI_Impl `protobuf_oneof:"impl"` -} - -func (m *PropertyI) Reset() { *m = PropertyI{} } -func (m *PropertyI) String() string { return proto.CompactTextString(m) } -func (*PropertyI) ProtoMessage() {} -func (*PropertyI) Descriptor() ([]byte, []int) { - return fileDescriptor_d454589ca8055838, []int{0} -} -func (m *PropertyI) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PropertyI) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PropertyI.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *PropertyI) XXX_Merge(src proto.Message) { - xxx_messageInfo_PropertyI.Merge(m, src) -} -func (m *PropertyI) XXX_Size() int { - return m.Size() -} -func (m *PropertyI) XXX_DiscardUnknown() { - xxx_messageInfo_PropertyI.DiscardUnknown(m) -} - -var xxx_messageInfo_PropertyI proto.InternalMessageInfo - -type isPropertyI_Impl interface { - isPropertyI_Impl() - MarshalTo([]byte) (int, error) - Size() int -} - -type PropertyI_Property struct { - Property *Property `protobuf:"bytes,1,opt,name=property,proto3,oneof" json:"property,omitempty"` -} - -func (*PropertyI_Property) isPropertyI_Impl() {} - -func (m *PropertyI) GetImpl() isPropertyI_Impl { - if m != nil { - return m.Impl - } - return nil -} - -func (m *PropertyI) GetProperty() *Property { - if x, ok := m.GetImpl().(*PropertyI_Property); ok { - return x.Property - } - return nil -} - -// XXX_OneofWrappers is for the internal use of the proto package. -func (*PropertyI) XXX_OneofWrappers() []interface{} { - return []interface{}{ - (*PropertyI_Property)(nil), - } -} - -func init() { - proto.RegisterType((*PropertyI)(nil), "base.PropertyI") -} - -func init() { - proto.RegisterFile("schema/properties/base/propertyI.proto", fileDescriptor_d454589ca8055838) -} - -var fileDescriptor_d454589ca8055838 = []byte{ - // 229 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2b, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0x28, 0xca, 0x2f, 0x48, 0x2d, 0x2a, 0xc9, 0x4c, 0x2d, 0xd6, 0x4f, 0x4a, - 0x2c, 0x4e, 0x85, 0xf1, 0x2b, 0x3d, 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x58, 0x40, 0xa2, - 0x52, 0xaa, 0x04, 0x54, 0x43, 0x14, 0x2b, 0x39, 0x72, 0x71, 0x06, 0xc0, 0xf4, 0x0b, 0xe9, 0x70, - 0x71, 0xc0, 0xa4, 0x25, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0xf8, 0xf4, 0x40, 0x9a, 0xf4, 0x60, - 0x4a, 0x3c, 0x18, 0x82, 0xe0, 0x2a, 0x9c, 0xd8, 0xb8, 0x58, 0x32, 0x73, 0x0b, 0x72, 0x9c, 0x66, - 0x32, 0x9e, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, - 0xcb, 0x31, 0x5c, 0x78, 0x2c, 0xc7, 0x70, 0xe3, 0xb1, 0x1c, 0x03, 0x17, 0x47, 0x72, 0x7e, 0x2e, - 0xd8, 0x04, 0x27, 0x3e, 0xb8, 0x2d, 0x01, 0x20, 0x7b, 0x03, 0x18, 0xa3, 0x4c, 0xd3, 0x33, 0x4b, - 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x1d, 0x8b, 0x8b, 0x53, 0x4b, 0x7c, 0x13, 0xf3, - 0x4a, 0x72, 0x52, 0xf5, 0x73, 0xf3, 0x53, 0x4a, 0x73, 0x52, 0x8b, 0xf5, 0xb1, 0xbb, 0x7f, 0x11, - 0x13, 0xb3, 0x53, 0x44, 0xc4, 0x2a, 0x26, 0x16, 0xa7, 0xc4, 0xe2, 0xd4, 0x53, 0x10, 0xea, 0x11, - 0x93, 0x00, 0x88, 0x8a, 0x71, 0x0f, 0x70, 0xf2, 0x4d, 0x2d, 0x49, 0x4c, 0x49, 0x2c, 0x49, 0x7c, - 0x05, 0x91, 0x49, 0x62, 0x03, 0xfb, 0xd2, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0x0a, 0x4a, 0x53, - 0xd8, 0x3c, 0x01, 0x00, 0x00, -} - -func (m *PropertyI) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PropertyI) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PropertyI) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Impl != nil { - { - size := m.Impl.Size() - i -= size - if _, err := m.Impl.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - } - } - return len(dAtA) - i, nil -} - -func (m *PropertyI_Property) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PropertyI_Property) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.Property != nil { - { - size, err := m.Property.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintPropertyI(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} -func encodeVarintPropertyI(dAtA []byte, offset int, v uint64) int { - offset -= sovPropertyI(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *PropertyI) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Impl != nil { - n += m.Impl.Size() - } - return n -} - -func (m *PropertyI_Property) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Property != nil { - l = m.Property.Size() - n += 1 + l + sovPropertyI(uint64(l)) - } - return n -} - -func sovPropertyI(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozPropertyI(x uint64) (n int) { - return sovPropertyI(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *PropertyI) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPropertyI - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PropertyI: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PropertyI: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Property", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPropertyI - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthPropertyI - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthPropertyI - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &Property{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Impl = &PropertyI_Property{v} - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipPropertyI(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthPropertyI - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipPropertyI(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPropertyI - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPropertyI - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPropertyI - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthPropertyI - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupPropertyI - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthPropertyI - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthPropertyI = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowPropertyI = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupPropertyI = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/properties/base/propertyI.proto b/schema/properties/base/propertyI.proto deleted file mode 100644 index 3e17661be..000000000 --- a/schema/properties/base/propertyI.proto +++ /dev/null @@ -1,10 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/properties/base/property.proto"; - -message PropertyI{ - oneof impl { - Property property = 1; - } -} \ No newline at end of file diff --git a/schema/properties/codec.go b/schema/properties/codec.go index c094898c8..dcd60a952 100644 --- a/schema/properties/codec.go +++ b/schema/properties/codec.go @@ -4,7 +4,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { +func RegisterCodec(codec *codec.Codec) { codec.RegisterInterface((*MetaProperty)(nil), nil) codec.RegisterInterface((*Property)(nil), nil) } diff --git a/schema/properties/codec_test.go b/schema/properties/codec_test.go new file mode 100644 index 000000000..caa42dd80 --- /dev/null +++ b/schema/properties/codec_test.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package properties + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + + {"+ve", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/properties/constants/properties.go b/schema/properties/constants/properties.go index 8431825a9..23fcd88c8 100644 --- a/schema/properties/constants/properties.go +++ b/schema/properties/constants/properties.go @@ -2,3 +2,39 @@ // SPDX-License-Identifier: Apache-2.0 package constants + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + baseData "github.com/AssetMantle/modules/schema/data/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" +) + +var ( + AuthenticationProperty = base.NewMetaProperty(baseIDs.NewStringID("authentication"), baseData.NewListData(baseLists.NewDataList())) + BurnHeightProperty = base.NewMetaProperty(baseIDs.NewStringID("burnHeight"), baseData.NewHeightData(baseTypes.NewHeight(-1)).ZeroValue()) + // TODO check default value + CreationHeightProperty = base.NewMetaProperty(baseIDs.NewStringID("creationHeight"), baseData.NewHeightData(baseTypes.NewHeight(-1)).ZeroValue()) + // TODO check default value + ExchangeRateProperty = base.NewMetaProperty(baseIDs.NewStringID("exchangeRate"), baseData.NewDecData(sdkTypes.SmallestDec()).ZeroValue()) + ExpiryHeightProperty = base.NewMetaProperty(baseIDs.NewStringID("expiryHeight"), baseData.NewHeightData(baseTypes.NewHeight(-1)).ZeroValue()) + LockProperty = base.NewMetaProperty(baseIDs.NewStringID("lock"), baseData.NewHeightData(baseTypes.NewHeight(-1)).ZeroValue()) + IdentityIDProperty = base.NewMetaProperty(baseIDs.NewStringID("identityID"), baseData.NewIDData(baseIDs.PrototypeIdentityID())) + MaintainedClassificationIDProperty = base.NewMetaProperty(baseIDs.NewStringID("maintainedClassificationID"), baseData.NewIDData(baseIDs.PrototypeClassificationID())) + MaintainedPropertiesProperty = base.NewMetaProperty(baseIDs.NewStringID("maintainedProperties"), baseData.NewListData(baseLists.NewDataList())) + // TODO check default value + MakerIDProperty = base.NewMetaProperty(baseIDs.NewStringID("makerID"), baseData.NewIDData(baseIDs.PrototypeIdentityID())) + // TODO check default value + MakerOwnableIDProperty = base.NewMetaProperty(baseIDs.NewStringID("makerOwnableID"), baseData.NewIDData(baseIDs.PrototypeOwnableID())) + MakerOwnableSplitProperty = base.NewMetaProperty(baseIDs.NewStringID("makerOwnableSplit"), baseData.NewDecData(sdkTypes.SmallestDec())) + // TODO ***** rename to name + NubIDProperty = base.NewMetaProperty(baseIDs.NewStringID("nubID"), baseData.NewIDData(baseIDs.PrototypeStringID())) + PermissionsProperty = base.NewMetaProperty(baseIDs.NewStringID("permissions"), baseData.NewListData(baseLists.NewDataList())) + TakerIDProperty = base.NewMetaProperty(baseIDs.NewStringID("takerID"), baseData.NewIDData(baseIDs.PrototypeStringID())) + // TODO check default value + TakerOwnableIDProperty = base.NewMetaProperty(baseIDs.NewStringID("takerOwnableID"), baseData.NewIDData(baseIDs.PrototypeOwnableID())) + SupplyProperty = base.NewMetaProperty(baseIDs.NewStringID("supply"), baseData.NewDecData(sdkTypes.SmallestDec())) +) diff --git a/schema/properties/property.go b/schema/properties/property.go index 7dd6ba460..e15957be1 100644 --- a/schema/properties/property.go +++ b/schema/properties/property.go @@ -9,10 +9,10 @@ import ( ) type Property interface { - GetID() ids.ID - GetDataID() ids.ID - GetKey() ids.ID - GetType() ids.ID + GetID() ids.PropertyID + GetDataID() ids.DataID + GetKey() ids.StringID + GetType() ids.StringID IsMeta() bool diff --git a/schema/qualified/base/codec.go b/schema/qualified/base/codec.go new file mode 100644 index 000000000..bfdb708c5 --- /dev/null +++ b/schema/qualified/base/codec.go @@ -0,0 +1,15 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + codecUtilities "github.com/AssetMantle/modules/utilities/codec" +) + +func RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, immutables{}) + codecUtilities.RegisterModuleConcrete(codec, mutables{}) +} diff --git a/schema/qualified/base/codec_test.go b/schema/qualified/base/codec_test.go new file mode 100644 index 000000000..c647cf081 --- /dev/null +++ b/schema/qualified/base/codec_test.go @@ -0,0 +1,24 @@ +package base + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + {"Test for Register Codec", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/qualified/base/immutables.go b/schema/qualified/base/immutables.go new file mode 100644 index 000000000..1d73e3768 --- /dev/null +++ b/schema/qualified/base/immutables.go @@ -0,0 +1,42 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/qualified" +) + +type immutables struct { + lists.PropertyList +} + +var _ qualified.Immutables = (*immutables)(nil) + +// TODO write test case +func (immutables immutables) GetImmutablePropertyList() lists.PropertyList { + if immutables.PropertyList.GetList() == nil { + return base.NewPropertyList() + } + + return immutables.PropertyList +} +func (immutables immutables) GenerateHashID() ids.HashID { + metaList := make([][]byte, len(immutables.PropertyList.GetList())) + + for i, immutableProperty := range immutables.PropertyList.GetList() { + metaList[i] = immutableProperty.GetDataID().GetHashID().Bytes() + } + + return baseIDs.GenerateHashID(metaList...) +} + +func NewImmutables(propertyList lists.PropertyList) qualified.Immutables { + return immutables{ + PropertyList: propertyList, + } +} diff --git a/schema/qualified/base/mutables.go b/schema/qualified/base/mutables.go new file mode 100644 index 000000000..12ff747cc --- /dev/null +++ b/schema/qualified/base/mutables.go @@ -0,0 +1,38 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties" + "github.com/AssetMantle/modules/schema/qualified" +) + +type mutables struct { + lists.PropertyList +} + +var _ qualified.Mutables = (*mutables)(nil) + +func (mutables mutables) GetMutablePropertyList() lists.PropertyList { + if mutables.PropertyList == nil { + return baseLists.NewPropertyList() + } + + return mutables.PropertyList +} +func (mutables mutables) Mutate(propertyList ...properties.Property) qualified.Mutables { + for _, property := range propertyList { + mutables.PropertyList = mutables.PropertyList.Mutate(property) + } + + return mutables +} + +func NewMutables(propertyList lists.PropertyList) qualified.Mutables { + return mutables{ + PropertyList: propertyList, + } +} diff --git a/schema/qualified/codec.go b/schema/qualified/codec.go new file mode 100644 index 000000000..25d125ef0 --- /dev/null +++ b/schema/qualified/codec.go @@ -0,0 +1,13 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package qualified + +import ( + "github.com/cosmos/cosmos-sdk/codec" +) + +func RegisterCodec(codec *codec.Codec) { + codec.RegisterInterface((*Immutables)(nil), nil) + codec.RegisterInterface((*Mutables)(nil), nil) +} diff --git a/schema/qualified/codec_test.go b/schema/qualified/codec_test.go new file mode 100644 index 000000000..975175eca --- /dev/null +++ b/schema/qualified/codec_test.go @@ -0,0 +1,24 @@ +package qualified + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + {"Test for Register Codec", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/qualified/constants/immutables.go b/schema/qualified/constants/immutables.go new file mode 100644 index 000000000..09f8f7f35 --- /dev/null +++ b/schema/qualified/constants/immutables.go @@ -0,0 +1,10 @@ +package constants + +import ( + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties/constants" + "github.com/AssetMantle/modules/schema/qualified/base" +) + +var NubImmutables = base.NewImmutables(baseLists.NewPropertyList(constants.NubIDProperty)) +var MaintainerImmutables = base.NewImmutables(baseLists.NewPropertyList(constants.IdentityIDProperty, constants.MaintainedClassificationIDProperty)) diff --git a/schema/qualified/constants/mutables.go b/schema/qualified/constants/mutables.go new file mode 100644 index 000000000..b92b7b4c8 --- /dev/null +++ b/schema/qualified/constants/mutables.go @@ -0,0 +1,10 @@ +package constants + +import ( + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties/constants" + "github.com/AssetMantle/modules/schema/qualified/base" +) + +var NubMutables = base.NewMutables(baseLists.NewPropertyList(constants.AuthenticationProperty)) +var MaintainerMutables = base.NewMutables(baseLists.NewPropertyList(constants.MaintainedPropertiesProperty, constants.PermissionsProperty)) diff --git a/schema/qualified/immutables.go b/schema/qualified/immutables.go new file mode 100644 index 000000000..282d8f904 --- /dev/null +++ b/schema/qualified/immutables.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +/* + * Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +package qualified + +import ( + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/lists" +) + +type Immutables interface { + // GetImmutablePropertyList return the immutable properties object + // does not return nil + GetImmutablePropertyList() lists.PropertyList + + GenerateHashID() ids.HashID +} diff --git a/schema/qualified/mutables.go b/schema/qualified/mutables.go new file mode 100644 index 000000000..4ea1e3c16 --- /dev/null +++ b/schema/qualified/mutables.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +/* + * Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +package qualified + +import ( + "github.com/AssetMantle/modules/schema/lists" + "github.com/AssetMantle/modules/schema/properties" +) + +type Mutables interface { + // GetMutablePropertyList return the mutable properties object + // does not return nil + GetMutablePropertyList() lists.PropertyList + + Mutate(propertyList ...properties.Property) Mutables +} diff --git a/schema/traits/codec.go b/schema/traits/codec.go index 5fea134f2..c23c80844 100644 --- a/schema/traits/codec.go +++ b/schema/traits/codec.go @@ -7,6 +7,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { +func RegisterCodec(codec *codec.Codec) { codec.RegisterInterface((*Listable)(nil), nil) } diff --git a/schema/traits/listable.go b/schema/traits/listable.go index 68e1c2149..b84f109d0 100644 --- a/schema/traits/listable.go +++ b/schema/traits/listable.go @@ -6,14 +6,7 @@ package traits type Listable interface { // Compare // * panic if compared with Listable of different type - // ***** TODO remove panic on compare with different type + // TODO remove panic on compare with different type + // TODO optimize compare for all impls Compare(Listable) int } - -// type listable traits.Listable -// -// var _ Listable = (*listable)(nil) -// -// func (l listable) Compare(l2 Listable) int { -// return l.Impl.(Listable).Compare(l2) -// } diff --git a/schema/traits/qualified/hasImmutables.pb.go b/schema/traits/qualified/hasImmutables.pb.go deleted file mode 100644 index 7fa792b2d..000000000 --- a/schema/traits/qualified/hasImmutables.pb.go +++ /dev/null @@ -1,325 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/traits/base/hasImmutables.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type HasImmutables struct { - Properties base.Properties `protobuf:"bytes,1,opt,name=properties,proto3" json:"properties"` -} - -func (m *HasImmutables) Reset() { *m = HasImmutables{} } -func (m *HasImmutables) String() string { return proto.CompactTextString(m) } -func (*HasImmutables) ProtoMessage() {} -func (*HasImmutables) Descriptor() ([]byte, []int) { - return fileDescriptor_a9f760f194430efc, []int{0} -} -func (m *HasImmutables) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *HasImmutables) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_HasImmutables.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *HasImmutables) XXX_Merge(src proto.Message) { - xxx_messageInfo_HasImmutables.Merge(m, src) -} -func (m *HasImmutables) XXX_Size() int { - return m.Size() -} -func (m *HasImmutables) XXX_DiscardUnknown() { - xxx_messageInfo_HasImmutables.DiscardUnknown(m) -} - -var xxx_messageInfo_HasImmutables proto.InternalMessageInfo - -func (m *HasImmutables) GetProperties() base.Properties { - if m != nil { - return m.Properties - } - return base.Properties{} -} - -func init() { - proto.RegisterType((*HasImmutables)(nil), "persistence_sdk.schema.traits.base.HasImmutables") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/traits/base/hasImmutables.proto", fileDescriptor_a9f760f194430efc) -} - -var fileDescriptor_a9f760f194430efc = []byte{ - // 227 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x2b, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0x29, 0x4a, 0xcc, 0x2c, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, - 0x48, 0x2c, 0xf6, 0xcc, 0xcd, 0x2d, 0x2d, 0x49, 0x4c, 0xca, 0x49, 0x2d, 0xd6, 0x2b, 0x28, 0xca, - 0x2f, 0xc9, 0x17, 0x52, 0x42, 0xd3, 0xa7, 0x07, 0xd1, 0xa7, 0x07, 0xd1, 0xa7, 0x07, 0xd2, 0x27, - 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x56, 0xae, 0x0f, 0x62, 0x41, 0x74, 0x4a, 0x19, 0xe1, 0xb2, - 0xb1, 0xb2, 0x20, 0x15, 0x6a, 0x61, 0x41, 0x51, 0x7e, 0x41, 0x6a, 0x51, 0x49, 0x26, 0xcc, 0x36, - 0xa5, 0x14, 0x2e, 0x5e, 0x0f, 0x64, 0x47, 0x08, 0x05, 0x73, 0x71, 0x21, 0x14, 0x49, 0x30, 0x2a, - 0x30, 0x6a, 0x70, 0x1b, 0xe9, 0xea, 0xe1, 0x72, 0x13, 0xc8, 0x64, 0xb0, 0x93, 0xf4, 0x02, 0xe0, - 0x9a, 0x9c, 0x58, 0x4e, 0xdc, 0x93, 0x67, 0x08, 0x42, 0x32, 0xc6, 0x29, 0xf4, 0xc4, 0x23, 0x39, - 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, - 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0xac, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, - 0xf3, 0x73, 0xf5, 0x91, 0x2c, 0xf1, 0xcf, 0x4b, 0x45, 0xe6, 0x06, 0xbb, 0x78, 0x63, 0x09, 0xbe, - 0x24, 0x36, 0xb0, 0x1f, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xf5, 0x18, 0x2f, 0x29, 0x6b, - 0x01, 0x00, 0x00, -} - -func (m *HasImmutables) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *HasImmutables) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *HasImmutables) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Properties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHasImmutables(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintHasImmutables(dAtA []byte, offset int, v uint64) int { - offset -= sovHasImmutables(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *HasImmutables) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Properties.Size() - n += 1 + l + sovHasImmutables(uint64(l)) - return n -} - -func sovHasImmutables(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozHasImmutables(x uint64) (n int) { - return sovHasImmutables(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *HasImmutables) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHasImmutables - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: HasImmutables: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: HasImmutables: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Properties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHasImmutables - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHasImmutables - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHasImmutables - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Properties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHasImmutables(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHasImmutables - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipHasImmutables(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHasImmutables - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHasImmutables - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHasImmutables - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthHasImmutables - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupHasImmutables - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthHasImmutables - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthHasImmutables = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowHasImmutables = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupHasImmutables = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/traits/qualified/hasMutables.pb.go b/schema/traits/qualified/hasMutables.pb.go deleted file mode 100644 index db5fb7a80..000000000 --- a/schema/traits/qualified/hasMutables.pb.go +++ /dev/null @@ -1,325 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/traits/base/hasMutables.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - base "github.com/persistenceOne/persistenceSDK/schema/types/base" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type HasMutables struct { - Properties base.Properties `protobuf:"bytes,1,opt,name=properties,proto3" json:"properties"` -} - -func (m *HasMutables) Reset() { *m = HasMutables{} } -func (m *HasMutables) String() string { return proto.CompactTextString(m) } -func (*HasMutables) ProtoMessage() {} -func (*HasMutables) Descriptor() ([]byte, []int) { - return fileDescriptor_d231908cd16c0dd7, []int{0} -} -func (m *HasMutables) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *HasMutables) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_HasMutables.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *HasMutables) XXX_Merge(src proto.Message) { - xxx_messageInfo_HasMutables.Merge(m, src) -} -func (m *HasMutables) XXX_Size() int { - return m.Size() -} -func (m *HasMutables) XXX_DiscardUnknown() { - xxx_messageInfo_HasMutables.DiscardUnknown(m) -} - -var xxx_messageInfo_HasMutables proto.InternalMessageInfo - -func (m *HasMutables) GetProperties() base.Properties { - if m != nil { - return m.Properties - } - return base.Properties{} -} - -func init() { - proto.RegisterType((*HasMutables)(nil), "persistence_sdk.schema.traits.base.HasMutables") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/traits/base/hasMutables.proto", fileDescriptor_d231908cd16c0dd7) -} - -var fileDescriptor_d231908cd16c0dd7 = []byte{ - // 225 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x29, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0x29, 0x4a, 0xcc, 0x2c, 0x29, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, - 0x48, 0x2c, 0xf6, 0x2d, 0x2d, 0x49, 0x4c, 0xca, 0x49, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, - 0x17, 0x52, 0x42, 0xd3, 0xa5, 0x07, 0xd1, 0xa5, 0x07, 0xd1, 0xa5, 0x07, 0xd2, 0x25, 0x25, 0x92, - 0x9e, 0x9f, 0x9e, 0x0f, 0x56, 0xae, 0x0f, 0x62, 0x41, 0x74, 0x4a, 0x19, 0xe1, 0xb2, 0xaf, 0xb2, - 0x20, 0x15, 0x6a, 0x5d, 0x41, 0x51, 0x7e, 0x41, 0x6a, 0x51, 0x49, 0x26, 0xcc, 0x36, 0xa5, 0x24, - 0x2e, 0x6e, 0x0f, 0x84, 0x13, 0x84, 0x82, 0xb9, 0xb8, 0x10, 0x4a, 0x24, 0x18, 0x15, 0x18, 0x35, - 0xb8, 0x8d, 0x74, 0xf5, 0x70, 0xb9, 0x08, 0x64, 0x2e, 0xd8, 0x41, 0x7a, 0x01, 0x70, 0x4d, 0x4e, - 0x2c, 0x27, 0xee, 0xc9, 0x33, 0x04, 0x21, 0x19, 0xe3, 0x14, 0x7a, 0xe2, 0x91, 0x1c, 0xe3, 0x85, - 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, - 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0xd6, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, - 0xfa, 0x48, 0x96, 0xf8, 0xe7, 0xa5, 0x22, 0x73, 0x83, 0x5d, 0xbc, 0xb1, 0x04, 0x5d, 0x12, 0x1b, - 0xd8, 0x07, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x55, 0xcc, 0x4b, 0xf6, 0x67, 0x01, 0x00, - 0x00, -} - -func (m *HasMutables) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *HasMutables) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *HasMutables) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Properties.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHasMutables(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintHasMutables(dAtA []byte, offset int, v uint64) int { - offset -= sovHasMutables(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *HasMutables) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Properties.Size() - n += 1 + l + sovHasMutables(uint64(l)) - return n -} - -func sovHasMutables(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozHasMutables(x uint64) (n int) { - return sovHasMutables(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *HasMutables) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHasMutables - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: HasMutables: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: HasMutables: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Properties", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHasMutables - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHasMutables - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHasMutables - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Properties.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHasMutables(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHasMutables - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipHasMutables(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHasMutables - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHasMutables - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHasMutables - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthHasMutables - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupHasMutables - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthHasMutables - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthHasMutables = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowHasMutables = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupHasMutables = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/accAddress.go b/schema/types/base/accAddress.go deleted file mode 100644 index 9fa446c6b..000000000 --- a/schema/types/base/accAddress.go +++ /dev/null @@ -1,31 +0,0 @@ -package base - -import sdkTypes "github.com/cosmos/cosmos-sdk/types" - -func (accAddress AccAddress) String() string { - err := sdkTypes.VerifyAddressFormat(accAddress.GetValue()) - if err != nil { - return "" - } - return sdkTypes.AccAddress(accAddress.GetValue()).String() -} - -func (accAddress AccAddress) GetBytes() []byte { - return accAddress.GetValue() -} - -func (accAddress AccAddress) AsSDKTypesAccAddress() sdkTypes.AccAddress { - return accAddress.GetValue() -} - -func NewAccAddressFromString(address string) AccAddress { - accAddress, err := sdkTypes.AccAddressFromBech32(address) - if err != nil { - return AccAddress{} - } - return AccAddress{Value: accAddress} -} - -func NewAccAddressFromSDKTypesAccAddress(address sdkTypes.AccAddress) AccAddress { - return AccAddress{Value: address} -} diff --git a/schema/types/base/accAddress.pb.go b/schema/types/base/accAddress.pb.go deleted file mode 100644 index a88e5f146..000000000 --- a/schema/types/base/accAddress.pb.go +++ /dev/null @@ -1,320 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/accAddress.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type AccAddress struct { - Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *AccAddress) Reset() { *m = AccAddress{} } -func (*AccAddress) ProtoMessage() {} -func (*AccAddress) Descriptor() ([]byte, []int) { - return fileDescriptor_c2cdcdd6ae370730, []int{0} -} -func (m *AccAddress) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AccAddress) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AccAddress.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *AccAddress) XXX_Merge(src proto.Message) { - xxx_messageInfo_AccAddress.Merge(m, src) -} -func (m *AccAddress) XXX_Size() int { - return m.Size() -} -func (m *AccAddress) XXX_DiscardUnknown() { - xxx_messageInfo_AccAddress.DiscardUnknown(m) -} - -var xxx_messageInfo_AccAddress proto.InternalMessageInfo - -func (m *AccAddress) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -func init() { - proto.RegisterType((*AccAddress)(nil), "persistence_sdk.schema.types.base.AccAddress") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/accAddress.proto", fileDescriptor_c2cdcdd6ae370730) -} - -var fileDescriptor_c2cdcdd6ae370730 = []byte{ - // 191 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x2a, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x4f, 0x4c, - 0x4e, 0x76, 0x4c, 0x49, 0x29, 0x4a, 0x2d, 0x2e, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, - 0x44, 0xd3, 0xa3, 0x07, 0xd1, 0xa3, 0x07, 0xd6, 0xa3, 0x07, 0xd2, 0x23, 0x25, 0x92, 0x9e, 0x9f, - 0x9e, 0x0f, 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, 0x2a, 0x69, 0x70, 0x71, 0x39, 0xc2, 0x0d, 0x13, - 0x12, 0xe1, 0x62, 0x2d, 0x4b, 0xcc, 0x29, 0x4d, 0x95, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x09, 0x82, - 0x70, 0xac, 0x58, 0x66, 0x2c, 0x90, 0x67, 0x70, 0x0a, 0x39, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, - 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, - 0x63, 0x39, 0x86, 0x28, 0xab, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, - 0x24, 0x77, 0xf8, 0xe7, 0xa5, 0x22, 0x73, 0x83, 0x5d, 0xbc, 0x31, 0x7d, 0x92, 0xc4, 0x06, 0x76, - 0x86, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x96, 0xec, 0xa3, 0x27, 0xf5, 0x00, 0x00, 0x00, -} - -func (m *AccAddress) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AccAddress) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AccAddress) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - i -= len(m.Value) - copy(dAtA[i:], m.Value) - i = encodeVarintAccAddress(dAtA, i, uint64(len(m.Value))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintAccAddress(dAtA []byte, offset int, v uint64) int { - offset -= sovAccAddress(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *AccAddress) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Value) - if l > 0 { - n += 1 + l + sovAccAddress(uint64(l)) - } - return n -} - -func sovAccAddress(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozAccAddress(x uint64) (n int) { - return sovAccAddress(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *AccAddress) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAccAddress - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AccAddress: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AccAddress: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAccAddress - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthAccAddress - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthAccAddress - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...) - if m.Value == nil { - m.Value = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAccAddress(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAccAddress - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipAccAddress(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAccAddress - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAccAddress - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAccAddress - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthAccAddress - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupAccAddress - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthAccAddress - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthAccAddress = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowAccAddress = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupAccAddress = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/accAddressData.pb.go b/schema/types/base/accAddressData.pb.go deleted file mode 100644 index f771bd121..000000000 --- a/schema/types/base/accAddressData.pb.go +++ /dev/null @@ -1,322 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/accAddressData.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type AccAddressData struct { - Value AccAddress `protobuf:"bytes,1,opt,name=value,proto3" json:"value"` -} - -func (m *AccAddressData) Reset() { *m = AccAddressData{} } -func (*AccAddressData) ProtoMessage() {} -func (*AccAddressData) Descriptor() ([]byte, []int) { - return fileDescriptor_710446ea140b5242, []int{0} -} -func (m *AccAddressData) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AccAddressData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AccAddressData.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *AccAddressData) XXX_Merge(src proto.Message) { - xxx_messageInfo_AccAddressData.Merge(m, src) -} -func (m *AccAddressData) XXX_Size() int { - return m.Size() -} -func (m *AccAddressData) XXX_DiscardUnknown() { - xxx_messageInfo_AccAddressData.DiscardUnknown(m) -} - -var xxx_messageInfo_AccAddressData proto.InternalMessageInfo - -func (m *AccAddressData) GetValue() AccAddress { - if m != nil { - return m.Value - } - return AccAddress{} -} - -func init() { - proto.RegisterType((*AccAddressData)(nil), "persistence_sdk.schema.types.base.AccAddressData") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/accAddressData.proto", fileDescriptor_710446ea140b5242) -} - -var fileDescriptor_710446ea140b5242 = []byte{ - // 217 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x2b, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x4f, 0x4c, - 0x4e, 0x76, 0x4c, 0x49, 0x29, 0x4a, 0x2d, 0x2e, 0x76, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, - 0x2f, 0xc9, 0x17, 0x52, 0x44, 0xd3, 0xa7, 0x07, 0xd1, 0xa7, 0x07, 0xd6, 0xa7, 0x07, 0xd2, 0x27, - 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, 0x4a, 0x19, 0x91, 0x62, - 0x21, 0x44, 0x8f, 0x52, 0x22, 0x17, 0x9f, 0x23, 0x8a, 0x23, 0x84, 0x3c, 0xb9, 0x58, 0xcb, 0x12, - 0x73, 0x4a, 0x53, 0x25, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0x74, 0xf5, 0x08, 0x3a, 0x47, 0x0f, - 0x61, 0x82, 0x13, 0xcb, 0x89, 0x7b, 0xf2, 0x0c, 0x41, 0x10, 0x13, 0xac, 0x58, 0x66, 0x2c, 0x90, - 0x67, 0x70, 0x0a, 0x39, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, - 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0xab, 0xf4, - 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0x24, 0x5b, 0xfc, 0xf3, 0x52, 0x91, - 0xb9, 0xc1, 0x2e, 0xde, 0x98, 0x3e, 0x49, 0x62, 0x03, 0xbb, 0xdf, 0x18, 0x10, 0x00, 0x00, 0xff, - 0xff, 0x7e, 0x8f, 0xc0, 0x33, 0x66, 0x01, 0x00, 0x00, -} - -func (m *AccAddressData) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AccAddressData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AccAddressData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Value.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAccAddressData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintAccAddressData(dAtA []byte, offset int, v uint64) int { - offset -= sovAccAddressData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *AccAddressData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Value.Size() - n += 1 + l + sovAccAddressData(uint64(l)) - return n -} - -func sovAccAddressData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozAccAddressData(x uint64) (n int) { - return sovAccAddressData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *AccAddressData) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAccAddressData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AccAddressData: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AccAddressData: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAccAddressData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAccAddressData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAccAddressData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAccAddressData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAccAddressData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipAccAddressData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAccAddressData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAccAddressData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowAccAddressData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthAccAddressData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupAccAddressData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthAccAddressData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthAccAddressData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowAccAddressData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupAccAddressData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/accAddress_test.go b/schema/types/base/accAddress_test.go deleted file mode 100644 index 484f41eb1..000000000 --- a/schema/types/base/accAddress_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package base - -import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - "testing" -) - -func TestNewAccAddressFromString(t *testing.T) { - address := "persistence1xfg28czjxsf75x9th4kejrjv3n6t7wfcu6gjpe" - accAddress := NewAccAddressFromString(address) - require.Equal(t, address, sdkTypes.AccAddress(accAddress.GetValue()).String()) -} - -func TestAccAddress_String(t *testing.T) { - address := "persistence1xfg28czjxsf75x9th4kejrjv3n6t7wfcu6gjpe" - accAddress := NewAccAddressFromString(address) - require.Equal(t, address, accAddress.String()) -} - -func TestAccAddress_GetBytes(t *testing.T) { - address := "persistence1xfg28czjxsf75x9th4kejrjv3n6t7wfcu6gjpe" - accAddress := NewAccAddressFromString(address) - require.Equal(t, accAddress.GetBytes(), sdkTypes.AccAddress(accAddress.GetValue()).Bytes()) -} - -func TestAccAddress_AsSDKTypesAccAddress(t *testing.T) { - address := "persistence1xfg28czjxsf75x9th4kejrjv3n6t7wfcu6gjpe" - accAddress := NewAccAddressFromString(address) - require.Equal(t, true, sdkTypes.AccAddress(accAddress.GetValue()).Equals(accAddress.AsSDKTypesAccAddress())) -} - -func TestNewAccAddressFromSDKTypesAccAddress(t *testing.T) { - address := "persistence1xfg28czjxsf75x9th4kejrjv3n6t7wfcu6gjpe" - sdkAddress, _ := sdkTypes.AccAddressFromBech32(address) - accAddress := NewAccAddressFromSDKTypesAccAddress(sdkAddress) - require.Equal(t, true, sdkAddress.Equals(accAddress.AsSDKTypesAccAddress())) -} diff --git a/schema/types/base/codec.go b/schema/types/base/codec.go index 087356600..bd578744d 100644 --- a/schema/types/base/codec.go +++ b/schema/types/base/codec.go @@ -6,11 +6,11 @@ package base import ( "github.com/cosmos/cosmos-sdk/codec" - "github.com/AssetMantle/modules/schema" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { - schema.RegisterModuleConcrete(codec, height{}) - schema.RegisterModuleConcrete(codec, signature{}) - schema.RegisterModuleConcrete(codec, split{}) +func RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, height{}) + codecUtilities.RegisterModuleConcrete(codec, signature{}) + codecUtilities.RegisterModuleConcrete(codec, split{}) } diff --git a/schema/types/base/codec_test.go b/schema/types/base/codec_test.go new file mode 100644 index 000000000..d5252808b --- /dev/null +++ b/schema/types/base/codec_test.go @@ -0,0 +1,25 @@ +package base + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + {"Test for Register Codec", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/types/base/data.go b/schema/types/base/data.go deleted file mode 100644 index a6cb79c34..000000000 --- a/schema/types/base/data.go +++ /dev/null @@ -1,62 +0,0 @@ -package base - -import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ types.Data = &Data{} - -func (m Data) Compare(data types.Data) int { - return m.Data.Compare(data) -} - -func (m Data) GetTypeID() types.ID { - return m.Data.GetTypeID() -} - -func (m Data) ZeroValue() types.Data { - return m.Data.ZeroValue() -} - -func (m Data) GenerateHashID() types.ID { - return m.Data.GenerateHashID() -} - -func (m Data) AsAccAddress() (sdkTypes.AccAddress, error) { - return m.Data.AsAccAddress() -} - -func (m Data) AsListData() (types.ListData, error) { - return m.Data.AsListData() -} - -func (m Data) AsString() (string, error) { - return m.Data.AsString() -} - -func (m Data) AsDec() (sdkTypes.Dec, error) { - return m.Data.AsDec() -} - -func (m Data) AsHeight() (types.Height, error) { - return m.Data.AsHeight() -} - -func (m Data) AsID() (types.ID, error) { - return m.Data.AsID() -} - -func (m Data) Get() interface{} { - return m.Data.Get() -} - -func (m Data) GetOneOfData() types.Data { - return m.Data -} - -func NewData(data types.Data) *Data { - return &Data{ - Data: data, - } -} diff --git a/schema/types/base/data.pb.go b/schema/types/base/data.pb.go deleted file mode 100644 index 3df14a9ab..000000000 --- a/schema/types/base/data.pb.go +++ /dev/null @@ -1,794 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/data.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - "github.com/persistenceOne/persistenceSDK/schema/types" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Data struct { - // Types that are valid to be assigned to Data: - // *Data_DecData - // *Data_HeightData - // *Data_IdData - // *Data_StringData - // *Data_AccAddressData - // *Data_ListData - Data types.Data `protobuf_oneof:"data"` -} - -func (m *Data) Reset() { *m = Data{} } -func (m *Data) String() string { return m.Data.String() } -func (*Data) ProtoMessage() {} -func (*Data) Descriptor() ([]byte, []int) { - return fileDescriptor_9b342118f875caf9, []int{0} -} -func (m *Data) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Data) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Data.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Data) XXX_Merge(src proto.Message) { - xxx_messageInfo_Data.Merge(m, src) -} -func (m *Data) XXX_Size() int { - return m.Size() -} -func (m *Data) XXX_DiscardUnknown() { - xxx_messageInfo_Data.DiscardUnknown(m) -} - -var xxx_messageInfo_Data proto.InternalMessageInfo - -type isData_Data interface { - isData_Data() - MarshalTo([]byte) (int, error) - Size() int -} - -type Data_DecData struct { - DecData *DecData `protobuf:"bytes,1,opt,name=dec_data,json=decData,proto3,oneof" json:"dec_data,omitempty"` -} -type Data_HeightData struct { - HeightData *HeightData `protobuf:"bytes,2,opt,name=height_data,json=heightData,proto3,oneof" json:"height_data,omitempty"` -} -type Data_IdData struct { - IdData *IDData `protobuf:"bytes,3,opt,name=id_data,json=idData,proto3,oneof" json:"id_data,omitempty"` -} -type Data_StringData struct { - StringData *StringData `protobuf:"bytes,4,opt,name=string_data,json=stringData,proto3,oneof" json:"string_data,omitempty"` -} -type Data_AccAddressData struct { - AccAddressData *AccAddressData `protobuf:"bytes,5,opt,name=acc_address_data,json=accAddressData,proto3,oneof" json:"acc_address_data,omitempty"` -} -type Data_ListData struct { - ListData *ListData `protobuf:"bytes,6,opt,name=list_data,json=listData,proto3,oneof,customtype=github.com/persistenceOne/persistenceSDK/schema/types/base.ListData" json:"list_data,omitempty"` -} - -func (*Data_DecData) isData_Data() {} -func (*Data_HeightData) isData_Data() {} -func (*Data_IdData) isData_Data() {} -func (*Data_StringData) isData_Data() {} -func (*Data_AccAddressData) isData_Data() {} -func (*Data_ListData) isData_Data() {} - -func (m *Data) GetData() types.Data { - if m != nil { - return m.Data - } - return nil -} - -func (m *Data) GetDecData() *DecData { - if x, ok := m.GetData().(*Data_DecData); ok { - return x.DecData - } - return nil -} - -func (m *Data) GetHeightData() *HeightData { - if x, ok := m.GetData().(*Data_HeightData); ok { - return x.HeightData - } - return nil -} - -func (m *Data) GetIdData() *IDData { - if x, ok := m.GetData().(*Data_IdData); ok { - return x.IdData - } - return nil -} - -func (m *Data) GetStringData() *StringData { - if x, ok := m.GetData().(*Data_StringData); ok { - return x.StringData - } - return nil -} - -func (m *Data) GetAccAddressData() *AccAddressData { - if x, ok := m.GetData().(*Data_AccAddressData); ok { - return x.AccAddressData - } - return nil -} - -// XXX_OneofWrappers is for the internal use of the proto package. -func (*Data) XXX_OneofWrappers() []interface{} { - return []interface{}{ - (*Data_DecData)(nil), - (*Data_HeightData)(nil), - (*Data_IdData)(nil), - (*Data_StringData)(nil), - (*Data_AccAddressData)(nil), - (*Data_ListData)(nil), - } -} - -func init() { - proto.RegisterType((*Data)(nil), "persistence_sdk.schema.types.base.Data") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/data.proto", fileDescriptor_9b342118f875caf9) -} - -var fileDescriptor_9b342118f875caf9 = []byte{ - // 376 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x92, 0x41, 0x4b, 0xc3, 0x30, - 0x18, 0x86, 0x5b, 0xad, 0xdd, 0x96, 0x81, 0x48, 0xf1, 0x20, 0x3b, 0xd4, 0xe9, 0x69, 0x8a, 0xa6, - 0x38, 0xc1, 0x83, 0xb7, 0xcd, 0xc2, 0x2a, 0x0a, 0xca, 0xe6, 0x49, 0x90, 0x91, 0x25, 0xb1, 0x0d, - 0x6e, 0xeb, 0x68, 0xe2, 0xc1, 0x7f, 0xe0, 0xd1, 0x9f, 0xe5, 0x71, 0x47, 0xf1, 0x20, 0xb2, 0xfd, - 0x11, 0x49, 0x53, 0xd7, 0x4e, 0x0f, 0xad, 0xde, 0x12, 0xf8, 0xde, 0xe7, 0x0d, 0x4f, 0x3e, 0x70, - 0x30, 0xa1, 0x11, 0x67, 0x5c, 0xd0, 0x31, 0xa6, 0x7d, 0x4e, 0x1e, 0x1c, 0x8e, 0x03, 0x3a, 0x42, - 0x8e, 0x78, 0x9a, 0x50, 0xee, 0x0c, 0x10, 0xa7, 0x0e, 0x41, 0x02, 0xc1, 0x49, 0x14, 0x8a, 0xd0, - 0xda, 0xf9, 0x31, 0x0d, 0xd5, 0x34, 0x8c, 0xa7, 0xa1, 0x9c, 0xae, 0x6d, 0xfa, 0xa1, 0x1f, 0xc6, - 0xd3, 0x8e, 0x3c, 0xa9, 0x60, 0xcd, 0x29, 0x50, 0x43, 0xb1, 0xbb, 0x68, 0xaa, 0x35, 0xf3, 0x03, - 0x01, 0x65, 0x7e, 0x20, 0x32, 0x19, 0x98, 0x9f, 0x61, 0xe4, 0x6f, 0x1d, 0x5c, 0x44, 0x6c, 0xec, - 0x67, 0x32, 0x27, 0xf9, 0x19, 0x84, 0x71, 0x8b, 0x90, 0x88, 0x72, 0x9e, 0xe6, 0x76, 0x9f, 0x0d, - 0x60, 0xc8, 0xab, 0xd5, 0x01, 0x65, 0x42, 0x71, 0x5f, 0x4a, 0xdd, 0xd2, 0xeb, 0x7a, 0xa3, 0xda, - 0xdc, 0x87, 0xb9, 0x56, 0xa1, 0xab, 0xe4, 0x78, 0x5a, 0xb7, 0x94, 0x78, 0xb2, 0xae, 0x41, 0x55, - 0x19, 0x50, 0xac, 0x95, 0x98, 0x75, 0x58, 0x80, 0xe5, 0x2d, 0xbc, 0x79, 0x5a, 0x17, 0xa4, 0x16, - 0x2d, 0x17, 0x94, 0x18, 0x51, 0xb4, 0xd5, 0x98, 0xb6, 0x57, 0x80, 0x76, 0xee, 0x26, 0x24, 0x53, - 0xb9, 0x95, 0xef, 0x52, 0xd6, 0x14, 0xc9, 0x28, 0xfc, 0xae, 0xde, 0xc2, 0xb5, 0x7c, 0x57, 0x6a, - 0xde, 0xba, 0x03, 0x1b, 0x08, 0xe3, 0x3e, 0x52, 0x52, 0x15, 0x76, 0x2d, 0xc6, 0x1e, 0x15, 0xc0, - 0xb6, 0x96, 0xbe, 0xc3, 0xd3, 0xba, 0xeb, 0xcb, 0x1f, 0x64, 0xdd, 0x83, 0xca, 0x90, 0xf1, 0x44, - 0xa3, 0x59, 0xd7, 0x1b, 0x95, 0x76, 0xe7, 0xfd, 0x63, 0xfb, 0xcc, 0x67, 0x22, 0x78, 0x1c, 0x40, - 0x1c, 0x8e, 0xb2, 0xdb, 0x7b, 0x35, 0xa6, 0xd9, 0x6b, 0xcf, 0xbd, 0xf8, 0xbd, 0x02, 0xf0, 0x92, - 0xf1, 0x6f, 0xc1, 0xe5, 0x61, 0x72, 0x6e, 0x9b, 0xc0, 0x90, 0x15, 0xed, 0x9b, 0xd7, 0x99, 0xad, - 0x4f, 0x67, 0xb6, 0xfe, 0x39, 0xb3, 0xf5, 0x97, 0xb9, 0xad, 0x4d, 0xe7, 0xb6, 0xf6, 0x36, 0xb7, - 0xb5, 0xdb, 0xd3, 0xff, 0x57, 0x0e, 0xcc, 0x78, 0xcf, 0x8e, 0xbf, 0x02, 0x00, 0x00, 0xff, 0xff, - 0xfc, 0xd5, 0x1c, 0xdb, 0xd1, 0x03, 0x00, 0x00, -} - -func (m *Data) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Data) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Data != nil { - { - size := m.Data.Size() - i -= size - if _, err := m.Data.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - } - } - return len(dAtA) - i, nil -} - -func (m *Data_DecData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data_DecData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.DecData != nil { - { - size, err := m.DecData.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} -func (m *Data_HeightData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data_HeightData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.HeightData != nil { - { - size, err := m.HeightData.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - return len(dAtA) - i, nil -} -func (m *Data_IdData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data_IdData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.IdData != nil { - { - size, err := m.IdData.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - return len(dAtA) - i, nil -} -func (m *Data_StringData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data_StringData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.StringData != nil { - { - size, err := m.StringData.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - return len(dAtA) - i, nil -} -func (m *Data_AccAddressData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data_AccAddressData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - if m.AccAddressData != nil { - { - size, err := m.AccAddressData.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - return len(dAtA) - i, nil -} -func (m *Data_ListData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Data_ListData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - { - size := m.ListData.Size() - i -= size - if _, err := m.ListData.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - return len(dAtA) - i, nil -} -func encodeVarintData(dAtA []byte, offset int, v uint64) int { - offset -= sovData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Data) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Data != nil { - n += m.Data.Size() - } - return n -} - -func (m *Data_DecData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.DecData != nil { - l = m.DecData.Size() - n += 1 + l + sovData(uint64(l)) - } - return n -} -func (m *Data_HeightData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.HeightData != nil { - l = m.HeightData.Size() - n += 1 + l + sovData(uint64(l)) - } - return n -} -func (m *Data_IdData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.IdData != nil { - l = m.IdData.Size() - n += 1 + l + sovData(uint64(l)) - } - return n -} -func (m *Data_StringData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.StringData != nil { - l = m.StringData.Size() - n += 1 + l + sovData(uint64(l)) - } - return n -} -func (m *Data_AccAddressData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.AccAddressData != nil { - l = m.AccAddressData.Size() - n += 1 + l + sovData(uint64(l)) - } - return n -} -func (m *Data_ListData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ListData.Size() - n += 1 + l + sovData(uint64(l)) - return n -} - -func sovData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozData(x uint64) (n int) { - return sovData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Data) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Data: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Data: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DecData", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &DecData{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Data = &Data_DecData{v} - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HeightData", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &HeightData{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Data = &Data_HeightData{v} - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IdData", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &IDData{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Data = &Data_IdData{v} - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StringData", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &StringData{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Data = &Data_StringData{v} - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AccAddressData", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - v := &AccAddressData{} - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Data = &Data_AccAddressData{v} - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ListData", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthData - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var vv ListData - v := &vv - if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - m.Data = &Data_ListData{v} - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/decData.pb.go b/schema/types/base/decData.pb.go deleted file mode 100644 index e9205e25b..000000000 --- a/schema/types/base/decData.pb.go +++ /dev/null @@ -1,316 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/decData.proto - -package base - -import ( - fmt "fmt" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type DecData struct { - Value github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=value,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"value"` -} - -func (m *DecData) Reset() { *m = DecData{} } -func (*DecData) ProtoMessage() {} -func (*DecData) Descriptor() ([]byte, []int) { - return fileDescriptor_8e74a7d2190a2474, []int{0} -} -func (m *DecData) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *DecData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_DecData.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *DecData) XXX_Merge(src proto.Message) { - xxx_messageInfo_DecData.Merge(m, src) -} -func (m *DecData) XXX_Size() int { - return m.Size() -} -func (m *DecData) XXX_DiscardUnknown() { - xxx_messageInfo_DecData.DiscardUnknown(m) -} - -var xxx_messageInfo_DecData proto.InternalMessageInfo - -func init() { - proto.RegisterType((*DecData)(nil), "persistence_sdk.schema.types.base.DecData") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/decData.proto", fileDescriptor_8e74a7d2190a2474) -} - -var fileDescriptor_8e74a7d2190a2474 = []byte{ - // 217 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x2f, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x4f, 0x49, - 0x4d, 0x76, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x44, 0xd3, 0xa0, - 0x07, 0xd1, 0xa0, 0x07, 0xd6, 0xa0, 0x07, 0xd2, 0x20, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x56, - 0xad, 0x0f, 0x62, 0x41, 0x34, 0x2a, 0x85, 0x72, 0xb1, 0xbb, 0x40, 0x4c, 0x12, 0x72, 0xe1, 0x62, - 0x2d, 0x4b, 0xcc, 0x29, 0x4d, 0x95, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x71, 0xd2, 0x3b, 0x71, 0x4f, - 0x9e, 0xe1, 0xd6, 0x3d, 0x79, 0xb5, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, - 0xfd, 0xe4, 0xfc, 0xe2, 0xdc, 0xfc, 0x62, 0x28, 0xa5, 0x0b, 0x72, 0x18, 0xc4, 0x02, 0x97, 0xd4, - 0xe4, 0x20, 0x88, 0x66, 0x2b, 0x96, 0x19, 0x0b, 0xe4, 0x19, 0x9c, 0x42, 0x4e, 0x3c, 0x92, 0x63, - 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, - 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0xca, 0x0a, 0xc9, 0x38, 0x24, 0x47, 0xfb, 0xe7, 0xa5, 0x22, - 0x73, 0x83, 0x5d, 0xbc, 0x31, 0xfd, 0x9c, 0xc4, 0x06, 0x76, 0xb3, 0x31, 0x20, 0x00, 0x00, 0xff, - 0xff, 0x96, 0x69, 0xa3, 0x89, 0x1f, 0x01, 0x00, 0x00, -} - -func (m *DecData) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *DecData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *DecData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size := m.Value.Size() - i -= size - if _, err := m.Value.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintDecData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintDecData(dAtA []byte, offset int, v uint64) int { - offset -= sovDecData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *DecData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Value.Size() - n += 1 + l + sovDecData(uint64(l)) - return n -} - -func sovDecData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozDecData(x uint64) (n int) { - return sovDecData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *DecData) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDecData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: DecData: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: DecData: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowDecData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthDecData - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthDecData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipDecData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthDecData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipDecData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowDecData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowDecData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowDecData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthDecData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupDecData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthDecData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthDecData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowDecData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupDecData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/fact.go b/schema/types/base/fact.go deleted file mode 100644 index 1a7c2916f..000000000 --- a/schema/types/base/fact.go +++ /dev/null @@ -1,59 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "github.com/99designs/keyring" - "github.com/cosmos/cosmos-sdk/client" - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ types.Fact = (*Fact)(nil) - -func (fact Fact) GetHashID() types.ID { return &fact.HashId } -func (fact Fact) GetTypeID() types.ID { return &fact.TypeId } -func (fact Fact) GetSignatures() types.Signatures { return &fact.Signatures } -func (fact Fact) IsMeta() bool { - return false -} -func (fact Fact) Sign(_ keyring.Keyring) types.Fact { - // TODO use keyring to sign - cliContext := client.Context{} - sign, _, _ := cliContext.Keyring.Sign(cliContext.FromName, fact.GetHashID().Bytes()) - Signature := Signature{ - Id: ID{IdString: fact.GetHashID().String()}, - SignatureBytes: sign, - ValidityHeight: Height{cliContext.Height}, - } - fact.GetSignatures().Add(&Signature) - - return &fact -} - -func NewFact(data types.Data) *Fact { - return &Fact{ - HashId: *NewID(data.GenerateHashID().String()), - TypeId: *NewID(data.GetTypeID().String()), - Signatures: Signatures{}, - } -} - -func NewFactProperty(hashID types.ID, typeID types.ID, signatures types.Signatures) *Fact { - return &Fact{ - HashId: *NewID(hashID.String()), - TypeId: *NewID(typeID.String()), - Signatures: *NewSignatures(signatures.GetList()), - } -} - -func ReadFact(metaFactString string) (types.Fact, error) { - metaFact, Error := ReadMetaFact(metaFactString) - if Error != nil { - return nil, Error - } - - return metaFact.RemoveData(), nil -} diff --git a/schema/types/base/fact.pb.go b/schema/types/base/fact.pb.go deleted file mode 100644 index ddcf6a057..000000000 --- a/schema/types/base/fact.pb.go +++ /dev/null @@ -1,411 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/fact.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Fact struct { - HashId ID `protobuf:"bytes,1,opt,name=hash_id,json=hashId,proto3" json:"hash_id"` - TypeId ID `protobuf:"bytes,2,opt,name=type_id,json=typeId,proto3" json:"type_id"` - Signatures Signatures `protobuf:"bytes,3,opt,name=signatures,proto3" json:"signatures"` -} - -func (m *Fact) Reset() { *m = Fact{} } -func (m *Fact) String() string { return proto.CompactTextString(m) } -func (*Fact) ProtoMessage() {} -func (*Fact) Descriptor() ([]byte, []int) { - return fileDescriptor_559a77c85918f977, []int{0} -} -func (m *Fact) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Fact) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Fact.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Fact) XXX_Merge(src proto.Message) { - xxx_messageInfo_Fact.Merge(m, src) -} -func (m *Fact) XXX_Size() int { - return m.Size() -} -func (m *Fact) XXX_DiscardUnknown() { - xxx_messageInfo_Fact.DiscardUnknown(m) -} - -var xxx_messageInfo_Fact proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Fact)(nil), "persistence_sdk.schema.types.base.Fact") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/fact.proto", fileDescriptor_559a77c85918f977) -} - -var fileDescriptor_559a77c85918f977 = []byte{ - // 266 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x29, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x4f, 0x4b, - 0x4c, 0x2e, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x44, 0x53, 0xad, 0x07, 0x51, 0xad, - 0x07, 0x56, 0xad, 0x07, 0x52, 0x2d, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x56, 0xad, 0x0f, 0x62, - 0x41, 0x34, 0x4a, 0x19, 0x11, 0xb6, 0xa6, 0x38, 0x33, 0x3d, 0x2f, 0xb1, 0xa4, 0xb4, 0x28, 0xb5, - 0x18, 0xaa, 0x47, 0x8b, 0xb0, 0x9e, 0xcc, 0x14, 0x88, 0x5a, 0xa5, 0xb7, 0x8c, 0x5c, 0x2c, 0x6e, - 0x89, 0xc9, 0x25, 0x42, 0x2e, 0x5c, 0xec, 0x19, 0x89, 0xc5, 0x19, 0xf1, 0x99, 0x29, 0x12, 0x8c, - 0x0a, 0x8c, 0x1a, 0xdc, 0x46, 0xaa, 0x7a, 0x04, 0xdd, 0xac, 0xe7, 0xe9, 0xe2, 0xc4, 0x72, 0xe2, - 0x9e, 0x3c, 0x43, 0x10, 0x1b, 0x48, 0xaf, 0x67, 0x0a, 0xc8, 0x14, 0x90, 0x34, 0xc8, 0x14, 0x26, - 0x32, 0x4c, 0x01, 0x09, 0x7a, 0xa6, 0x08, 0x05, 0x73, 0x71, 0x21, 0x3c, 0x25, 0xc1, 0x0c, 0x36, - 0x48, 0x97, 0x08, 0x83, 0x82, 0xe1, 0x9a, 0xa0, 0x06, 0x22, 0x19, 0x63, 0xc5, 0xd2, 0xb1, 0x40, - 0x9e, 0xc1, 0x29, 0xe4, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, - 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0xac, 0xd2, - 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x91, 0xac, 0xf2, 0xcf, 0x4b, 0x45, - 0xe6, 0x06, 0xbb, 0x78, 0x63, 0x06, 0x67, 0x12, 0x1b, 0x38, 0x30, 0x8d, 0x01, 0x01, 0x00, 0x00, - 0xff, 0xff, 0x01, 0xff, 0x6e, 0x5d, 0x15, 0x02, 0x00, 0x00, -} - -func (m *Fact) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Fact) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Fact) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Signatures.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintFact(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.TypeId.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintFact(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.HashId.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintFact(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintFact(dAtA []byte, offset int, v uint64) int { - offset -= sovFact(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Fact) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.HashId.Size() - n += 1 + l + sovFact(uint64(l)) - l = m.TypeId.Size() - n += 1 + l + sovFact(uint64(l)) - l = m.Signatures.Size() - n += 1 + l + sovFact(uint64(l)) - return n -} - -func sovFact(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozFact(x uint64) (n int) { - return sovFact(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Fact) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowFact - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Fact: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Fact: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HashId", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowFact - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthFact - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthFact - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.HashId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field TypeId", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowFact - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthFact - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthFact - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.TypeId.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Signatures", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowFact - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthFact - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthFact - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Signatures.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipFact(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthFact - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipFact(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowFact - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowFact - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowFact - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthFact - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupFact - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthFact - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthFact = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowFact = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupFact = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/fact_test.go b/schema/types/base/fact_test.go deleted file mode 100644 index 8083d4b7d..000000000 --- a/schema/types/base/fact_test.go +++ /dev/null @@ -1,56 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "github.com/cosmos/cosmos-sdk/client" - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/stretchr/testify/require" - "testing" -) - -func Test_Fact(t *testing.T) { - - stringData := NewStringData("testString") - decData := NewDecData(sdkTypes.NewDec(12)) - idData := NewIDData(NewID("id")) - heightData := NewHeightData(NewHeight(123)) - - testFact := NewFact(stringData) - require.Equal(t, Fact{HashId: stringData.GenerateHashID(), TypeId: NewID("S"), Signatures: Signatures{}}, testFact) - require.Equal(t, stringData.GenerateHashID(), testFact.GetHashID()) - require.Equal(t, Signatures{}, testFact.GetSignatures()) - require.Equal(t, false, testFact.(Fact).IsMeta()) - require.Equal(t, NewID("S"), testFact.GetTypeID()) - require.Equal(t, NewID("D"), NewFact(decData).GetTypeID()) - require.Equal(t, NewID("I"), NewFact(idData).GetTypeID()) - require.Equal(t, NewID("H"), NewFact(heightData).GetTypeID()) - - readFact, Error := ReadFact("S|testString") - require.Equal(t, testFact, readFact) - require.Nil(t, Error) - require.Panics(t, func() { - require.Equal(t, readFact, readFact.Sign(nil)) - - }) - readFact2, Error := ReadFact("") - require.Equal(t, nil, readFact2) - require.Equal(t, errors.IncorrectFormat, Error) - - cliContext := client.Context{} - require.Panics(t, func() { - sign, _, _ := cliContext.Keyring.Sign(cliContext.FromName, readFact.GetHashID().Bytes()) - Signature := Signature{ - Id: ID{IdString: readFact.GetHashID().String()}, - SignatureBytes: sign, - ValidityHeight: Height{cliContext.Height}, - } - readFact.GetSignatures().Add(Signature) - require.Equal(t, readFact.GetSignatures().Get(readFact.GetHashID()), readFact.GetHashID().String()) - }) - -} diff --git a/schema/types/base/height.pb.go b/schema/types/base/height.pb.go deleted file mode 100644 index 47df73d7e..000000000 --- a/schema/types/base/height.pb.go +++ /dev/null @@ -1,301 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/types/base/height.proto - -package base - -import ( - fmt "fmt" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Height struct { - Value int64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *Height) Reset() { *m = Height{} } -func (m *Height) String() string { return proto.CompactTextString(m) } -func (*Height) ProtoMessage() {} -func (*Height) Descriptor() ([]byte, []int) { - return fileDescriptor_98c5175879c7b486, []int{0} -} -func (m *Height) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Height) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Height.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Height) XXX_Merge(src proto.Message) { - xxx_messageInfo_Height.Merge(m, src) -} -func (m *Height) XXX_Size() int { - return m.Size() -} -func (m *Height) XXX_DiscardUnknown() { - xxx_messageInfo_Height.DiscardUnknown(m) -} - -var xxx_messageInfo_Height proto.InternalMessageInfo - -func (m *Height) GetValue() int64 { - if m != nil { - return m.Value - } - return 0 -} - -func init() { - proto.RegisterType((*Height)(nil), "base.Height") -} - -func init() { proto.RegisterFile("schema/types/base/height.proto", fileDescriptor_98c5175879c7b486) } - -var fileDescriptor_98c5175879c7b486 = []byte{ - // 207 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2b, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x48, - 0xcd, 0x4c, 0xcf, 0x28, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x09, 0x29, 0xc9, - 0x71, 0xb1, 0x79, 0x80, 0x45, 0x85, 0x44, 0xb8, 0x58, 0xcb, 0x12, 0x73, 0x4a, 0x53, 0x25, 0x18, - 0x15, 0x18, 0x35, 0x98, 0x83, 0x20, 0x1c, 0xa7, 0x89, 0x8c, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, - 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, - 0x78, 0x2c, 0xc7, 0xc0, 0xc5, 0x91, 0x9c, 0x9f, 0xab, 0x07, 0x32, 0xc4, 0x89, 0x1b, 0x62, 0x44, - 0x00, 0xc8, 0xdc, 0x00, 0xc6, 0x28, 0x83, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, - 0x5c, 0x7d, 0xc7, 0xe2, 0xe2, 0xd4, 0x12, 0xdf, 0xc4, 0xbc, 0x92, 0x9c, 0x54, 0xfd, 0xdc, 0xfc, - 0x94, 0xd2, 0x9c, 0xd4, 0x62, 0x7d, 0x0c, 0x87, 0x2d, 0x62, 0x62, 0x76, 0x8a, 0x88, 0x58, 0xc5, - 0xc4, 0xe2, 0x94, 0x58, 0x9c, 0x7a, 0x0a, 0x42, 0x3d, 0x62, 0x12, 0x00, 0x51, 0x31, 0xee, 0x01, - 0x4e, 0xbe, 0xa9, 0x25, 0x89, 0x29, 0x89, 0x25, 0x89, 0xaf, 0x20, 0x32, 0x49, 0x6c, 0x60, 0x0f, - 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xbf, 0x6c, 0xc2, 0xbe, 0xe2, 0x00, 0x00, 0x00, -} - -func (m *Height) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Height) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Height) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Value != 0 { - i = encodeVarintHeight(dAtA, i, uint64(m.Value)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintHeight(dAtA []byte, offset int, v uint64) int { - offset -= sovHeight(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Height) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Value != 0 { - n += 1 + sovHeight(uint64(m.Value)) - } - return n -} - -func sovHeight(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozHeight(x uint64) (n int) { - return sovHeight(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Height) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHeight - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Height: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Height: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - m.Value = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHeight - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Value |= int64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipHeight(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHeight - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipHeight(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHeight - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHeight - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHeight - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthHeight - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupHeight - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthHeight - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthHeight = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowHeight = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupHeight = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/height.proto b/schema/types/base/height.proto deleted file mode 100644 index e3192a5ae..000000000 --- a/schema/types/base/height.proto +++ /dev/null @@ -1,6 +0,0 @@ -syntax = "proto3"; -package base; - -message Height{ - int64 value = 1; -} \ No newline at end of file diff --git a/schema/types/base/heightData.pb.go b/schema/types/base/heightData.pb.go deleted file mode 100644 index 7cfdeeebf..000000000 --- a/schema/types/base/heightData.pb.go +++ /dev/null @@ -1,322 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/heightData.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type HeightData struct { - Value Height `protobuf:"bytes,1,opt,name=value,proto3" json:"value"` -} - -func (m *HeightData) Reset() { *m = HeightData{} } -func (*HeightData) ProtoMessage() {} -func (*HeightData) Descriptor() ([]byte, []int) { - return fileDescriptor_c40890281a934e9a, []int{0} -} -func (m *HeightData) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *HeightData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_HeightData.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *HeightData) XXX_Merge(src proto.Message) { - xxx_messageInfo_HeightData.Merge(m, src) -} -func (m *HeightData) XXX_Size() int { - return m.Size() -} -func (m *HeightData) XXX_DiscardUnknown() { - xxx_messageInfo_HeightData.DiscardUnknown(m) -} - -var xxx_messageInfo_HeightData proto.InternalMessageInfo - -func (m *HeightData) GetValue() Height { - if m != nil { - return m.Value - } - return Height{} -} - -func init() { - proto.RegisterType((*HeightData)(nil), "persistence_sdk.schema.types.base.HeightData") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/heightData.proto", fileDescriptor_c40890281a934e9a) -} - -var fileDescriptor_c40890281a934e9a = []byte{ - // 213 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x2a, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x48, - 0xcd, 0x4c, 0xcf, 0x28, 0x71, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, - 0x44, 0xd3, 0xa3, 0x07, 0xd1, 0xa3, 0x07, 0xd6, 0xa3, 0x07, 0xd2, 0x23, 0x25, 0x92, 0x9e, 0x9f, - 0x9e, 0x0f, 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, 0x4a, 0xe9, 0x11, 0x6b, 0x19, 0x44, 0xbd, 0x52, - 0x24, 0x17, 0x97, 0x07, 0xdc, 0x72, 0x21, 0x57, 0x2e, 0xd6, 0xb2, 0xc4, 0x9c, 0xd2, 0x54, 0x09, - 0x46, 0x05, 0x46, 0x0d, 0x6e, 0x23, 0x4d, 0x3d, 0x82, 0xce, 0xd0, 0x83, 0xe8, 0x76, 0x62, 0x39, - 0x71, 0x4f, 0x9e, 0x21, 0x08, 0xa2, 0xdb, 0x8a, 0x65, 0xc6, 0x02, 0x79, 0x06, 0xa7, 0x90, 0x13, - 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, - 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0xb2, 0x4a, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, - 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x47, 0xb2, 0xc1, 0x3f, 0x2f, 0x15, 0x99, 0x1b, 0xec, 0xe2, 0x8d, - 0xe9, 0xfa, 0x24, 0x36, 0xb0, 0xbb, 0x8d, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x94, 0xe6, 0xed, - 0xf8, 0x56, 0x01, 0x00, 0x00, -} - -func (m *HeightData) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *HeightData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *HeightData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Value.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintHeightData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintHeightData(dAtA []byte, offset int, v uint64) int { - offset -= sovHeightData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *HeightData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Value.Size() - n += 1 + l + sovHeightData(uint64(l)) - return n -} - -func sovHeightData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozHeightData(x uint64) (n int) { - return sovHeightData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *HeightData) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHeightData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: HeightData: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: HeightData: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowHeightData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthHeightData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthHeightData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipHeightData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthHeightData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipHeightData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHeightData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHeightData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowHeightData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthHeightData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupHeightData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthHeightData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthHeightData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowHeightData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupHeightData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/height_test.go b/schema/types/base/height_test.go new file mode 100644 index 000000000..4357b8ceb --- /dev/null +++ b/schema/types/base/height_test.go @@ -0,0 +1,112 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "math" + "reflect" + "testing" + + "github.com/AssetMantle/modules/schema/types" +) + +func TestNewHeight(t *testing.T) { + type args struct { + value int64 + } + tests := []struct { + name string + args args + want types.Height + }{ + // Fails in case of overflow conditions + {"Testing with value 10", args{ + 10, + }, height{Value: 10}}, + {"Testing with value -10", args{ + -10, + }, height{Value: -1}}, + {"Testing with value math.MaxInt64", args{ + math.MaxInt64, + }, height{Value: math.MaxInt64}}, + {"Testing with value math.MinInt64", args{ + math.MinInt64, + }, height{Value: -1}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewHeight(tt.args.value); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewHeight() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_height_Compare(t *testing.T) { + type fields struct { + Value int64 + } + type args struct { + compareHeight types.Height + } + tests := []struct { + name string + fields fields + args args + want int + }{ + { + "compareHeight > height", fields{ + 10, + }, args{height{11}}, -1, + }, + { + "compareHeight < height", fields{ + 10, + }, args{height{9}}, 1, + }, + { + "compareHeight === height", fields{ + 10, + }, args{height{10}}, 0, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + height := height{ + Value: tt.fields.Value, + } + if got := height.Compare(tt.args.compareHeight); got != tt.want { + t.Errorf("Compare() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_height_Get(t *testing.T) { + type fields struct { + Value int64 + } + tests := []struct { + name string + fields fields + want int64 + }{ + { + "Testing with 100", fields{ + 100, + }, 100, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + height := height{ + Value: tt.fields.Value, + } + if got := height.Get(); got != tt.want { + t.Errorf("Get() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/schema/types/base/id.pb.go b/schema/types/base/id.pb.go deleted file mode 100644 index f665eb18b..000000000 --- a/schema/types/base/id.pb.go +++ /dev/null @@ -1,318 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/id.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type ID struct { - IdString string `protobuf:"bytes,1,opt,name=id_string,json=idString,proto3" json:"id_string,omitempty"` -} - -func (m *ID) Reset() { *m = ID{} } -func (*ID) ProtoMessage() {} -func (*ID) Descriptor() ([]byte, []int) { - return fileDescriptor_31e3a90fdeb3b61b, []int{0} -} -func (m *ID) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ID) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ID.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *ID) XXX_Merge(src proto.Message) { - xxx_messageInfo_ID.Merge(m, src) -} -func (m *ID) XXX_Size() int { - return m.Size() -} -func (m *ID) XXX_DiscardUnknown() { - xxx_messageInfo_ID.DiscardUnknown(m) -} - -var xxx_messageInfo_ID proto.InternalMessageInfo - -func (m *ID) GetIdString() string { - if m != nil { - return m.IdString - } - return "" -} - -func init() { - proto.RegisterType((*ID)(nil), "persistence_sdk.schema.types.base.ID") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/id.proto", fileDescriptor_31e3a90fdeb3b61b) -} - -var fileDescriptor_31e3a90fdeb3b61b = []byte{ - // 190 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x2a, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x4c, - 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x44, 0x53, 0xab, 0x07, 0x51, 0xab, 0x07, 0x56, - 0xab, 0x07, 0x52, 0x2b, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, - 0x2a, 0xa9, 0x73, 0x31, 0x79, 0xba, 0x08, 0x49, 0x73, 0x71, 0x66, 0xa6, 0xc4, 0x17, 0x97, 0x14, - 0x65, 0xe6, 0xa5, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x06, 0x71, 0x64, 0xa6, 0x04, 0x83, 0xf9, - 0x56, 0x2c, 0x33, 0x16, 0xc8, 0x33, 0x38, 0x85, 0x9c, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, - 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, 0x78, 0x2c, 0xc7, 0x70, 0xe3, 0xb1, - 0x1c, 0x43, 0x94, 0x55, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x3e, 0x92, - 0x33, 0xfc, 0xf3, 0x52, 0x91, 0xb9, 0xc1, 0x2e, 0xde, 0x98, 0x1e, 0x48, 0x62, 0x03, 0xbb, 0xc2, - 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xd8, 0xbb, 0xcd, 0xde, 0xec, 0x00, 0x00, 0x00, -} - -func (m *ID) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ID) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ID) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.IdString) > 0 { - i -= len(m.IdString) - copy(dAtA[i:], m.IdString) - i = encodeVarintId(dAtA, i, uint64(len(m.IdString))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintId(dAtA []byte, offset int, v uint64) int { - offset -= sovId(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *ID) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.IdString) - if l > 0 { - n += 1 + l + sovId(uint64(l)) - } - return n -} - -func sovId(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozId(x uint64) (n int) { - return sovId(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *ID) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ID: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ID: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IdString", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowId - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthId - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthId - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IdString = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipId(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthId - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipId(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowId - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowId - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowId - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthId - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupId - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthId - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthId = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowId = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupId = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/idData.pb.go b/schema/types/base/idData.pb.go deleted file mode 100644 index 5f3268516..000000000 --- a/schema/types/base/idData.pb.go +++ /dev/null @@ -1,322 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/idData.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type IDData struct { - Value ID `protobuf:"bytes,1,opt,name=value,proto3" json:"value"` -} - -func (m *IDData) Reset() { *m = IDData{} } -func (*IDData) ProtoMessage() {} -func (*IDData) Descriptor() ([]byte, []int) { - return fileDescriptor_2b059d48eb657315, []int{0} -} -func (m *IDData) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *IDData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_IDData.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *IDData) XXX_Merge(src proto.Message) { - xxx_messageInfo_IDData.Merge(m, src) -} -func (m *IDData) XXX_Size() int { - return m.Size() -} -func (m *IDData) XXX_DiscardUnknown() { - xxx_messageInfo_IDData.DiscardUnknown(m) -} - -var xxx_messageInfo_IDData proto.InternalMessageInfo - -func (m *IDData) GetValue() ID { - if m != nil { - return m.Value - } - return ID{} -} - -func init() { - proto.RegisterType((*IDData)(nil), "persistence_sdk.schema.types.base.IDData") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/idData.proto", fileDescriptor_2b059d48eb657315) -} - -var fileDescriptor_2b059d48eb657315 = []byte{ - // 210 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x2b, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x4c, - 0x71, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x44, 0x53, 0xaf, 0x07, - 0x51, 0xaf, 0x07, 0x56, 0xaf, 0x07, 0x52, 0x2f, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x56, 0xad, - 0x0f, 0x62, 0x41, 0x34, 0x4a, 0x69, 0x11, 0x63, 0x11, 0x44, 0xad, 0x52, 0x20, 0x17, 0x9b, 0xa7, - 0x0b, 0xc8, 0x52, 0x21, 0x47, 0x2e, 0xd6, 0xb2, 0xc4, 0x9c, 0xd2, 0x54, 0x09, 0x46, 0x05, 0x46, - 0x0d, 0x6e, 0x23, 0x55, 0x3d, 0x82, 0xd6, 0xeb, 0x79, 0xba, 0x38, 0xb1, 0x9c, 0xb8, 0x27, 0xcf, - 0x10, 0x04, 0xd1, 0x69, 0xc5, 0x32, 0x63, 0x81, 0x3c, 0x83, 0x53, 0xc8, 0x89, 0x47, 0x72, 0x8c, - 0x17, 0x1e, 0xc9, 0x31, 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, - 0x0c, 0x37, 0x1e, 0xcb, 0x31, 0x44, 0x59, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, - 0xe7, 0xea, 0x23, 0x99, 0xee, 0x9f, 0x97, 0x8a, 0xcc, 0x0d, 0x76, 0xf1, 0xc6, 0x74, 0x71, 0x12, - 0x1b, 0xd8, 0xbd, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xfc, 0xa3, 0xd0, 0x30, 0x46, 0x01, - 0x00, 0x00, -} - -func (m *IDData) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *IDData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *IDData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Value.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintIdData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintIdData(dAtA []byte, offset int, v uint64) int { - offset -= sovIdData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *IDData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Value.Size() - n += 1 + l + sovIdData(uint64(l)) - return n -} - -func sovIdData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozIdData(x uint64) (n int) { - return sovIdData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *IDData) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIdData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: IDData: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: IDData: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIdData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthIdData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthIdData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Value.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipIdData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthIdData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipIdData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowIdData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthIdData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupIdData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthIdData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthIdData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowIdData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupIdData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/listData.go b/schema/types/base/listData.go deleted file mode 100644 index cf4fcb4ea..000000000 --- a/schema/types/base/listData.go +++ /dev/null @@ -1,269 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "strings" - - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/utilities/meta" -) - -var ( - _ types.ListData = (*Data_ListData)(nil) - _ types.DummyListData = (*ListData)(nil) -) - -// TODO: find a better impl -func (listData Data_ListData) Compare(data types.Data) int { - compareListData, Error := listDataFromData(data) - if Error != nil { - panic(Error) - } - - var listDataString []string - for _, data := range listData.ListData.Value { - listDataString = append(listDataString, data.String()) - } - - var comparisonDataString []string - for _, data := range compareListData.ListData.Value { - comparisonDataString = append(comparisonDataString, data.String()) - } - - return strings.Compare(strings.Join(listDataString, constants.ListDataStringSeparator), strings.Join(comparisonDataString, constants.ListDataStringSeparator)) -} -func (listData Data_ListData) String() string { - dataStringList := make([]string, len(listData.ListData.Value)) - - for i, data := range listData.ListData.Value { - dataStringList[i] = data.String() - } - - return strings.Join(dataStringList, constants.ListDataStringSeparator) -} -func (listData Data_ListData) GetTypeID() types.ID { - return NewID("LD") -} -func (listData Data_ListData) ZeroValue() types.Data { - return NewListData([]types.Data{}...) -} -func (listData Data_ListData) GenerateHashID() types.ID { - if len(listData.ListData.Value) == 0 { - return NewID("") - } - - return NewID(meta.Hash(listData.String())) -} -func (listData Data_ListData) AsAccAddress() (sdkTypes.AccAddress, error) { - zeroValue, _ := Data_AccAddressData{}.ZeroValue().AsAccAddress() - return zeroValue, errors.IncorrectFormat -} -func (listData Data_ListData) AsListData() (types.ListData, error) { - return &listData, nil -} -func (listData Data_ListData) AsString() (string, error) { - zeroValue, _ := Data_StringData{}.ZeroValue().AsString() - return zeroValue, errors.IncorrectFormat -} -func (listData Data_ListData) AsDec() (sdkTypes.Dec, error) { - zeroValue, _ := Data_DecData{}.ZeroValue().AsDec() - return zeroValue, errors.IncorrectFormat -} -func (listData Data_ListData) AsHeight() (types.Height, error) { - zeroValue, _ := Data_HeightData{}.ZeroValue().AsHeight() - return zeroValue, errors.IncorrectFormat -} -func (listData Data_ListData) AsID() (types.ID, error) { - zeroValue, _ := Data_IdData{}.ZeroValue().AsID() - return zeroValue, errors.IncorrectFormat -} -func (listData Data_ListData) Get() interface{} { - return listData.ListData.Value -} -func (listData Data_ListData) Search(data types.Data) int { - return ListData{Value: listData.ListData.Value}.Search(data) -} -func (listData Data_ListData) GetList() []types.Data { - newList := make([]types.Data, len(listData.ListData.Value)) - for i, element := range listData.ListData.Value { - newList[i] = element.Data - } - return newList -} -func (listData Data_ListData) Add(dataList ...types.Data) types.ListData { - for _, data := range dataList { - dataListElement := ListData{Value: listData.ListData.Value}.Add(data).GetList() - newDataList := make([]Data, len(dataListElement)) - for i, element := range dataListElement { - newDataList[i] = *NewData(element) - } - listData.ListData.Value = newDataList - } - - return &listData -} -func (listData Data_ListData) Remove(dataList ...types.Data) types.ListData { - for _, data := range dataList { - dataListElement := ListData{Value: listData.ListData.Value}.Remove(data).GetList() - newDataList := make([]Data, len(dataListElement)) - for i, element := range dataListElement { - newDataList[i] = *NewData(element) - } - listData.ListData.Value = newDataList - } - - return &listData -} -func (listData Data_ListData) Unmarshal(dAtA []byte) error { - return listData.ListData.Unmarshal(dAtA) -} -func (listData *Data_ListData) Reset() { *listData = Data_ListData{} } -func (*Data_ListData) ProtoMessage() {} - -func listDataFromData(data types.Data) (Data_ListData, error) { - switch value := data.(type) { - case *Data_ListData: - return *value, nil - default: - return Data_ListData{}, errors.MetaDataError - } -} - -func NewListData(value ...types.Data) *Data_ListData { - newValue := make([]Data, len(value)) - for i, element := range value { - newValue[i] = *NewData(element) - } - return &Data_ListData{ - ListData: &ListData{ - Value: newValue, - }, - } -} - -func ReadAccAddressListData(dataString string) (types.Data, error) { - if dataString == "" { - return Data_ListData{}.ZeroValue(), nil - } - - dataStringList := strings.Split(dataString, constants.ListDataStringSeparator) - dataList := make([]types.Data, len(dataStringList)) - - for i, accAddressString := range dataStringList { - accAddress, Error := sdkTypes.AccAddressFromBech32(accAddressString) - if Error != nil { - return Data_ListData{}.ZeroValue(), Error - } - - dataList[i] = NewAccAddressData(accAddress) - } - - return NewListData(dataList...), nil -} - -// TODO: find a better impl for types.DummyListData -func (listData ListData) Compare(data types.Data) int { - compareListData, Error := dummyListDataFromData(data) - if Error != nil { - panic(Error) - } - - var listDataString []string - for _, data := range listData.Value { - listDataString = append(listDataString, data.String()) - } - - var comparisonDataString []string - for _, data := range compareListData.Value { - comparisonDataString = append(comparisonDataString, data.String()) - } - - return strings.Compare(strings.Join(listDataString, constants.ListDataStringSeparator), strings.Join(comparisonDataString, constants.ListDataStringSeparator)) -} -func (listData ListData) String() string { - dataStringList := make([]string, len(listData.Value)) - - for i, data := range listData.Value { - dataStringList[i] = data.String() - } - - return strings.Join(dataStringList, constants.ListDataStringSeparator) -} -func (listData ListData) GetTypeID() types.ID { - return NewID("LD") -} -func (listData ListData) ZeroValue() types.Data { - return NewListData([]types.Data{}...) -} -func (listData ListData) GenerateHashID() types.ID { - if len(listData.Value) == 0 { - return NewID("") - } - - return NewID(meta.Hash(listData.String())) -} -func (listData ListData) AsAccAddress() (sdkTypes.AccAddress, error) { - zeroValue, _ := AccAddressData{}.ZeroValue().AsAccAddress() - return zeroValue, errors.IncorrectFormat -} -func (listData ListData) AsListData() (types.ListData, error) { - //return &listData, nil - return nil, nil -} -func (listData ListData) AsString() (string, error) { - zeroValue, _ := StringData{}.ZeroValue().AsString() - return zeroValue, errors.IncorrectFormat -} -func (listData ListData) AsDec() (sdkTypes.Dec, error) { - zeroValue, _ := DecData{}.ZeroValue().AsDec() - return zeroValue, errors.IncorrectFormat -} -func (listData ListData) AsHeight() (types.Height, error) { - zeroValue, _ := HeightData{}.ZeroValue().AsHeight() - return zeroValue, errors.IncorrectFormat -} -func (listData ListData) AsID() (types.ID, error) { - zeroValue, _ := IDData{}.ZeroValue().AsID() - return zeroValue, errors.IncorrectFormat -} -func (listData ListData) Get() interface{} { - return listData.Value -} -func (listData ListData) BaseSearch(data types.Data) int { - //return listData.Value.Search(data) - return 0 -} -func (listData ListData) BaseGetList() []types.Data { - //return listData.Value - return nil -} -func (listData ListData) BaseAdd(dataList ...types.Data) types.DummyListData { - //for _, data := range dataList { - // listData.Value = listData.Value.Add(data).(sortedDataList) - //} - - return &listData -} -func (listData ListData) BaseRemove(dataList ...types.Data) types.DummyListData { - //for _, data := range dataList { - // listData.Value = listData.Value.Remove(data).(sortedDataList) - //} - - return &listData -} - -func dummyListDataFromData(data types.Data) (ListData, error) { - switch value := data.(type) { - case *ListData: - return *value, nil - default: - return ListData{}, errors.MetaDataError - } -} diff --git a/schema/types/base/listData.pb.go b/schema/types/base/listData.pb.go deleted file mode 100644 index 8254dcc73..000000000 --- a/schema/types/base/listData.pb.go +++ /dev/null @@ -1,331 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/listData.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type ListData struct { - Value []Data `protobuf:"bytes,1,rep,name=value,proto3" json:"value"` -} - -func (m *ListData) Reset() { *m = ListData{} } -func (*ListData) ProtoMessage() {} -func (*ListData) Descriptor() ([]byte, []int) { - return fileDescriptor_3f65daeca57ea5b6, []int{0} -} -func (m *ListData) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *ListData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ListData.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *ListData) XXX_Merge(src proto.Message) { - xxx_messageInfo_ListData.Merge(m, src) -} -func (m *ListData) XXX_Size() int { - return m.Size() -} -func (m *ListData) XXX_DiscardUnknown() { - xxx_messageInfo_ListData.DiscardUnknown(m) -} - -var xxx_messageInfo_ListData proto.InternalMessageInfo - -func (m *ListData) GetValue() []Data { - if m != nil { - return m.Value - } - return nil -} - -func init() { - proto.RegisterType((*ListData)(nil), "persistence_sdk.schema.types.base.ListData") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/listData.proto", fileDescriptor_3f65daeca57ea5b6) -} - -var fileDescriptor_3f65daeca57ea5b6 = []byte{ - // 212 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x28, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0xc9, - 0x2c, 0x2e, 0x71, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x44, 0xd3, - 0xa1, 0x07, 0xd1, 0xa1, 0x07, 0xd6, 0xa1, 0x07, 0xd2, 0x21, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, - 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, 0x4a, 0xe9, 0x10, 0xb6, 0x2a, 0x05, 0x6e, 0x8d, 0x52, 0x28, - 0x17, 0x87, 0x0f, 0xd4, 0x62, 0x21, 0x67, 0x2e, 0xd6, 0xb2, 0xc4, 0x9c, 0xd2, 0x54, 0x09, 0x46, - 0x05, 0x66, 0x0d, 0x6e, 0x23, 0x75, 0x3d, 0x82, 0x4e, 0xd0, 0x03, 0xe9, 0x73, 0x62, 0x39, 0x71, - 0x4f, 0x9e, 0x21, 0x08, 0xa2, 0xd7, 0x8a, 0x65, 0xc6, 0x02, 0x79, 0x06, 0xa7, 0x90, 0x13, 0x8f, - 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, - 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0xb2, 0x4a, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, - 0x4b, 0xce, 0xcf, 0xd5, 0x47, 0x32, 0xdf, 0x3f, 0x2f, 0x15, 0x99, 0x1b, 0xec, 0xe2, 0x8d, 0xe9, - 0xee, 0x24, 0x36, 0xb0, 0x9b, 0x8d, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x0f, 0x32, 0x09, 0x2a, - 0x4e, 0x01, 0x00, 0x00, -} - -func (m *ListData) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *ListData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ListData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - for iNdEx := len(m.Value) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Value[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintListData(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintListData(dAtA []byte, offset int, v uint64) int { - offset -= sovListData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *ListData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Value) > 0 { - for _, e := range m.Value { - l = e.Size() - n += 1 + l + sovListData(uint64(l)) - } - } - return n -} - -func sovListData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozListData(x uint64) (n int) { - return sovListData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *ListData) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowListData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ListData: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ListData: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowListData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthListData - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthListData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = append(m.Value, Data{}) - if err := m.Value[len(m.Value)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipListData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthListData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipListData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowListData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowListData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowListData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthListData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupListData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthListData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthListData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowListData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupListData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/listData_test.go b/schema/types/base/listData_test.go deleted file mode 100644 index 4782da7d8..000000000 --- a/schema/types/base/listData_test.go +++ /dev/null @@ -1,105 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "testing" - - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/utilities/meta" - "github.com/stretchr/testify/require" -) - -func Test_ListData(t *testing.T) { - - listValue, Error := ReadAccAddressListData("address1") - require.NotNil(t, Error) - listValue, Error = ReadAccAddressListData("cosmos1nynns8ex9fq6sjjfj8k79ymkdz4sqth06xexae") - require.Nil(t, Error) - testListData := NewListData(listValue) - listValue2, Error := ReadAccAddressListData("") - require.Nil(t, Error) - testListData2 := NewListData(listValue2) - - require.Equal(t, "cosmos1nynns8ex9fq6sjjfj8k79ymkdz4sqth06xexae", testListData.String()) - require.Equal(t, NewID(meta.Hash("cosmos1nynns8ex9fq6sjjfj8k79ymkdz4sqth06xexae")), testListData.GenerateHashID()) - - require.Equal(t, NewID(""), testListData2.GenerateHashID()) - require.Equal(t, NewID("LD"), testListData.GetTypeID()) - - dataAsString, Error := testListData.AsString() - require.Equal(t, "", dataAsString) - require.Equal(t, errors.IncorrectFormat, Error) - - dataAsHeight, Error := testListData.AsHeight() - require.Equal(t, Height{}, dataAsHeight) - require.Equal(t, errors.IncorrectFormat, Error) - - dataAsDec, Error := testListData.AsDec() - require.Equal(t, sdkTypes.ZeroDec(), dataAsDec) - require.Equal(t, errors.IncorrectFormat, Error) - - dataAsID, Error := testListData.AsID() - require.Equal(t, ID{}, dataAsID) - require.Equal(t, errors.IncorrectFormat, Error) - - dataAsList, Error := testListData.AsListData() - require.Equal(t, testListData, dataAsList) - - require.Nil(t, Error) - - require.Equal(t, testListData.(*ListData).Value, testListData.Get()) - - data, Error := ReadAccAddressListData("testString") - require.Equal(t, ListData{}, data) - require.NotNil(t, Error) - - require.Panics(t, func() { - require.Equal(t, false, testListData.Compare(NewStringData("")) == 0) - }) - require.Panics(t, func() { - require.Equal(t, false, testListData.Compare(NewHeightData(NewHeight(123))) == 0) - }) - - listValue3, Error := ReadAccAddressListData("cosmos1ce2gkxuug6g388qd535tk3p70ej2xkkvf5jm6r") - require.Nil(t, Error) - testListData3 := NewListData(listValue3) - listValue4, Error := ReadAccAddressListData("cosmos1ce2gkxuug6g388qd535tk3p70ej2xkkvf5jm6r") - require.Nil(t, Error) - testListData4 := NewListData(listValue4) - - listValue6, Error := ReadAccAddressListData("cosmos1lmx8c6dujhgt04a3f9wzx503pp763dgvuga8ry,cosmos1zz22dfpvw3zqpeyhvhmx944a588fgcalw744ts") - require.Nil(t, Error) - listValue8, Error := ReadAccAddressListData("cosmos1lmx8c6dujhgt04a3f9wzx503pp763dgvuga8ry") - require.Nil(t, Error) - dataAsList8, Error := listValue8.AsListData() - require.Nil(t, Error) - addr1, _ := sdkTypes.AccAddressFromBech32("cosmos1zz22dfpvw3zqpeyhvhmx944a588fgcalw744ts") - addr2, _ := sdkTypes.AccAddressFromBech32("cosmos1adf0nwjhg2anlfy5t7m4ztxvczhn342kvq806c") - dataAsList8 = dataAsList8.Add(NewAccAddressData(addr1), NewAccAddressData(addr2)) - listValue9, Error := ReadAccAddressListData("cosmos1adf0nwjhg2anlfy5t7m4ztxvczhn342kvq806c") - require.Nil(t, Error) - listValue10, Error := ReadAccAddressListData("cosmos1lmx8c6dujhgt04a3f9wzx503pp763dgvuga8ry,cosmos1tqcxq4xxwjc3wtn6hqqc5f7nfyqz86ktv6hssp,cosmos1zz22dfpvw3zqpeyhvhmx944a588fgcalw744ts") - require.Nil(t, Error) - listValue11, Error := ReadAccAddressListData("cosmos1tqcxq4xxwjc3wtn6hqqc5f7nfyqz86ktv6hssp") - require.Nil(t, Error) - - dataAsList6, Error := listValue6.AsListData() - require.Nil(t, Error) - dataAsList9, Error := listValue9.AsListData() - require.Nil(t, Error) - dataAsList10, Error := listValue10.AsListData() - require.Nil(t, Error) - - _ = dataAsList6.Add(dataAsList) - require.Equal(t, 0, testListData3.Compare(testListData4)) - - require.Equal(t, false, dataAsList8.Search(dataAsList9.(*ListData).Value.GetList()[0]) == len(dataAsList8.(ListData).Value.GetList())) - require.Equal(t, dataAsList6, dataAsList8.Remove(listValue9.(*ListData).Value.GetList()[0])) - require.Equal(t, dataAsList10, dataAsList6.Add(listValue11.(*ListData).Value.GetList()[0])) - -} diff --git a/schema/types/base/metaFact.go b/schema/types/base/metaFact.go deleted file mode 100644 index a64458390..000000000 --- a/schema/types/base/metaFact.go +++ /dev/null @@ -1,70 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "strings" - - "github.com/99designs/keyring" - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ types.MetaFact = (*MetaFact)(nil) - -func (metaFact MetaFact) GetHashID() types.ID { return metaFact.Data.GenerateHashID() } -func (metaFact MetaFact) GetTypeID() types.ID { return metaFact.Data.GetTypeID() } -func (metaFact MetaFact) GetSignatures() types.Signatures { return &metaFact.Signatures } -func (metaFact MetaFact) Sign(_ keyring.Keyring) types.MetaFact { - // TODO implement signing - return &metaFact -} -func (metaFact MetaFact) GetData() types.Data { return metaFact.Data.GetOneOfData() } -func (metaFact MetaFact) RemoveData() types.Fact { return NewFact(metaFact.Data.GetOneOfData()) } - -func NewMetaFact(data types.Data) *MetaFact { - return &MetaFact{ - Data: *NewData(data), - Signatures: Signatures{}, - } -} - -func ReadMetaFact(metaFactString string) (types.MetaFact, error) { - dataTypeAndString := strings.SplitN(metaFactString, constants.DataTypeAndValueSeparator, 2) - if len(dataTypeAndString) == 2 { - dataType, dataString := dataTypeAndString[0], dataTypeAndString[1] - - var data types.Data - - var Error error - - switch NewID(dataType).String() { - case Data_DecData{}.GetTypeID().String(): - data, Error = ReadDecData(dataString) - case Data_IdData{}.GetTypeID().String(): - data, Error = ReadIDData(dataString) - case Data_HeightData{}.GetTypeID().String(): - data, Error = ReadHeightData(dataString) - case Data_StringData{}.GetTypeID().String(): - data, Error = ReadStringData(dataString) - case Data_AccAddressData{}.GetTypeID().String(): - data, Error = ReadAccAddressData(dataString) - case Data_ListData{}.GetTypeID().String(): - data, Error = ReadAccAddressListData(dataString) - default: - data, Error = nil, errors.UnsupportedParameter - } - - if Error != nil { - return nil, Error - } - - return NewMetaFact(data), nil - } - - return nil, errors.IncorrectFormat -} diff --git a/schema/types/base/metaFact.pb.go b/schema/types/base/metaFact.pb.go deleted file mode 100644 index 423c6edd5..000000000 --- a/schema/types/base/metaFact.pb.go +++ /dev/null @@ -1,364 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/metaFact.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type MetaFact struct { - Signatures Signatures `protobuf:"bytes,1,opt,name=signatures,proto3" json:"signatures"` - Data Data `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` -} - -func (m *MetaFact) Reset() { *m = MetaFact{} } -func (m *MetaFact) String() string { return proto.CompactTextString(m) } -func (*MetaFact) ProtoMessage() {} -func (*MetaFact) Descriptor() ([]byte, []int) { - return fileDescriptor_f343a26a3fac91f5, []int{0} -} -func (m *MetaFact) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MetaFact) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MetaFact.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MetaFact) XXX_Merge(src proto.Message) { - xxx_messageInfo_MetaFact.Merge(m, src) -} -func (m *MetaFact) XXX_Size() int { - return m.Size() -} -func (m *MetaFact) XXX_DiscardUnknown() { - xxx_messageInfo_MetaFact.DiscardUnknown(m) -} - -var xxx_messageInfo_MetaFact proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MetaFact)(nil), "persistence_sdk.schema.types.base.MetaFact") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/metaFact.proto", fileDescriptor_f343a26a3fac91f5) -} - -var fileDescriptor_f343a26a3fac91f5 = []byte{ - // 252 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x28, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x4d, - 0x2d, 0x49, 0x74, 0x4b, 0x4c, 0x2e, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x44, 0xd3, - 0xa1, 0x07, 0xd1, 0xa1, 0x07, 0xd6, 0xa1, 0x07, 0xd2, 0x21, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, - 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, 0x4a, 0x19, 0x11, 0xb6, 0xaa, 0x38, 0x33, 0x3d, 0x2f, 0xb1, - 0xa4, 0xb4, 0x28, 0xb5, 0x18, 0xaa, 0x47, 0x87, 0xb0, 0x9e, 0x94, 0xc4, 0x92, 0x44, 0x88, 0x6a, - 0xa5, 0x15, 0x8c, 0x5c, 0x1c, 0xbe, 0x50, 0xd7, 0x0a, 0x05, 0x73, 0x71, 0x21, 0x8c, 0x93, 0x60, - 0x54, 0x60, 0xd4, 0xe0, 0x36, 0xd2, 0xd5, 0x23, 0xe8, 0x78, 0xbd, 0x60, 0xb8, 0x26, 0x27, 0x96, - 0x13, 0xf7, 0xe4, 0x19, 0x82, 0x90, 0x8c, 0x11, 0x72, 0xe4, 0x62, 0x01, 0xd9, 0x27, 0xc1, 0x04, - 0x36, 0x4e, 0x9d, 0x08, 0xe3, 0x5c, 0x12, 0x4b, 0x12, 0xa1, 0x06, 0x81, 0xb5, 0x5a, 0xb1, 0x74, - 0x2c, 0x90, 0x67, 0x70, 0x0a, 0x39, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, - 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, - 0xab, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0x24, 0xe3, 0xfd, 0xf3, - 0x52, 0x91, 0xb9, 0xc1, 0x2e, 0xde, 0x98, 0x61, 0x91, 0xc4, 0x06, 0x0e, 0x07, 0x63, 0x40, 0x00, - 0x00, 0x00, 0xff, 0xff, 0xd8, 0x6c, 0x3a, 0xc9, 0xd6, 0x01, 0x00, 0x00, -} - -func (m *MetaFact) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MetaFact) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MetaFact) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Data.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMetaFact(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.Signatures.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMetaFact(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintMetaFact(dAtA []byte, offset int, v uint64) int { - offset -= sovMetaFact(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MetaFact) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Signatures.Size() - n += 1 + l + sovMetaFact(uint64(l)) - l = m.Data.Size() - n += 1 + l + sovMetaFact(uint64(l)) - return n -} - -func sovMetaFact(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMetaFact(x uint64) (n int) { - return sovMetaFact(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MetaFact) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaFact - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MetaFact: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MetaFact: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Signatures", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaFact - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetaFact - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetaFact - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Signatures.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaFact - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetaFact - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetaFact - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMetaFact(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMetaFact - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMetaFact(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaFact - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaFact - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaFact - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMetaFact - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMetaFact - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMetaFact - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMetaFact = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMetaFact = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMetaFact = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/metaFact_test.go b/schema/types/base/metaFact_test.go deleted file mode 100644 index b6cbccbf9..000000000 --- a/schema/types/base/metaFact_test.go +++ /dev/null @@ -1,63 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/stretchr/testify/require" - "testing" -) - -func Test_MetaFact(t *testing.T) { - - stringData := NewStringData("testString") - decData := NewDecData(sdkTypes.NewDec(12)) - idData := NewIDData(NewID("id")) - heightData := NewHeightData(NewHeight(123)) - - testMetaFact := NewMetaFact(stringData) - require.Equal(t, MetaFact{Data: stringData, Signatures: Signatures{}}, testMetaFact) - require.Equal(t, stringData, testMetaFact.GetData()) - require.Equal(t, NewFact(stringData), testMetaFact.RemoveData()) - require.Equal(t, stringData.GenerateHashID(), testMetaFact.GetHashID()) - require.Equal(t, Signatures{}, testMetaFact.GetSignatures()) - require.Equal(t, NewID("S"), testMetaFact.GetTypeID()) - require.Equal(t, NewID("D"), NewMetaFact(decData).GetTypeID()) - require.Equal(t, NewID("I"), NewMetaFact(idData).GetTypeID()) - require.Equal(t, NewID("H"), NewMetaFact(heightData).GetTypeID()) - - readMetaFact, Error := ReadMetaFact("S|testString") - require.Equal(t, testMetaFact, readMetaFact) - require.Nil(t, Error) - - readMetaFact2, Error := ReadMetaFact("H|123") - require.Equal(t, NewMetaFact(heightData), readMetaFact2) - require.Nil(t, Error) - - readMetaFact3, Error := ReadMetaFact("I|id") - require.Equal(t, NewMetaFact(idData), readMetaFact3) - require.Nil(t, Error) - - readMetaFact3, Error = ReadMetaFact("I|test.Class|hash") - require.Equal(t, NewMetaFact(NewIDData(NewID("test.Class|hash"))), readMetaFact3) - require.Nil(t, Error) - - //Fix the decData case in GetTypeID Method - readMetaFact4, Error := ReadMetaFact("D|12.0") - require.Equal(t, NewMetaFact(decData), readMetaFact4) - require.Nil(t, Error) - - readMetaFact5, Error := ReadMetaFact("Z|12.0") - require.Equal(t, nil, readMetaFact5) - require.Equal(t, errors.UnsupportedParameter, Error) - - readMetaFact6, Error := ReadMetaFact("randomString") - require.Equal(t, nil, readMetaFact6) - require.Equal(t, errors.IncorrectFormat, Error) - - require.Equal(t, readMetaFact4, readMetaFact4.Sign(nil)) -} diff --git a/schema/types/base/metaProperties.go b/schema/types/base/metaProperties.go deleted file mode 100644 index 88fc5ea5e..000000000 --- a/schema/types/base/metaProperties.go +++ /dev/null @@ -1,144 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "strings" - - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ types.MetaProperties = (*MetaProperties)(nil) - -func (metaProperties MetaProperties) Get(id types.ID) types.MetaProperty { - for _, metaProperty := range metaProperties.GetList() { - if metaProperty.GetID().Compare(id) == 0 { - return metaProperty - } - } - - return nil -} -func (metaProperties MetaProperties) GetList() []types.MetaProperty { - newMetaPropertiesList := make([]types.MetaProperty, len(metaProperties.MetaPropertyList)) - for i, _ := range metaProperties.MetaPropertyList { - newMetaPropertiesList[i] = &metaProperties.MetaPropertyList[i] - } - return newMetaPropertiesList -} -func (metaProperties MetaProperties) Add(metaPropertyList ...types.MetaProperty) types.MetaProperties { - newMetaPropertyList := metaProperties.GetList() - - for _, addMetaProperty := range metaPropertyList { - if metaProperties.Get(addMetaProperty.GetID()) == nil { - newMetaPropertyList = append(newMetaPropertyList, addMetaProperty) - } - } - - return NewMetaProperties(newMetaPropertyList...) -} -func (metaProperties MetaProperties) Remove(metaPropertyList ...types.MetaProperty) types.MetaProperties { - newMetaPropertyList := metaProperties.GetList() - - for _, removeMetaProperty := range metaPropertyList { - for i, oldMetaProperty := range newMetaPropertyList { - if oldMetaProperty.GetID().Compare(removeMetaProperty.GetID()) == 0 { - newMetaPropertyList = append(newMetaPropertyList[:i], newMetaPropertyList[i+1:]...) - break - } - } - } - - return NewMetaProperties(newMetaPropertyList...) -} -func (metaProperties MetaProperties) Mutate(metaPropertyList ...types.MetaProperty) types.MetaProperties { - newMetaPropertyList := metaProperties.GetList() - - for _, mutateMetaProperty := range metaPropertyList { - for i, oldMetaProperty := range newMetaPropertyList { - if oldMetaProperty.GetID().Compare(mutateMetaProperty.GetID()) == 0 { - newMetaPropertyList[i] = mutateMetaProperty - break - } - } - } - - return NewMetaProperties(newMetaPropertyList...) -} -func (metaProperties MetaProperties) RemoveData() types.Properties { - propertyList := make([]types.Property, len(metaProperties.GetList())) - for i, oldMetaProperty := range metaProperties.GetList() { - propertyList[i] = oldMetaProperty.RemoveData() - } - - return NewProperties(propertyList...) -} - -func NewMetaProperties(metaPropertyList ...types.MetaProperty) *MetaProperties { - newMetaPropertyList := make([]MetaProperty, len(metaPropertyList)) - for i, element := range metaPropertyList { - newMetaPropertyList[i] = *NewMetaProperty(element.GetID(), element.GetMetaFact()) - } - return &MetaProperties{ - MetaPropertyList: newMetaPropertyList, - } -} - -func ReadMetaProperties(metaPropertiesString string) (types.MetaProperties, error) { - var metaPropertyList []types.MetaProperty - - metaProperties := strings.Split(metaPropertiesString, constants.PropertiesSeparator) - for _, metaPropertyString := range metaProperties { - if metaPropertyString != "" { - metaProperty, err := ReadMetaProperty(metaPropertyString) - if err != nil { - return nil, err - } - - metaPropertyList = append(metaPropertyList, metaProperty) - } - } - - return NewMetaProperties(metaPropertyList...), nil -} - -func ReadData(dataString string) (types.Data, error) { - dataTypeAndString := strings.SplitN(dataString, constants.DataTypeAndValueSeparator, 2) - if len(dataTypeAndString) == 2 { - dataType, dataString := dataTypeAndString[0], dataTypeAndString[1] - - var data types.Data - - var Error error - - switch NewID(dataType) { - case decData{}.GetTypeID(): - data, Error = ReadDecData(dataString) - case idData{}.GetTypeID(): - data, Error = ReadIDData(dataString) - case heightData{}.GetTypeID(): - data, Error = ReadHeightData(dataString) - case stringData{}.GetTypeID(): - data, Error = ReadStringData(dataString) - case accAddressData{}.GetTypeID(): - data, Error = ReadAccAddressData(dataString) - case listData{}.GetTypeID(): - data, Error = ReadAccAddressListData(dataString) - default: - data, Error = nil, errors.UnsupportedParameter - } - - if Error != nil { - return nil, Error - } - - return data, nil - } - - return nil, errors.IncorrectFormat -} diff --git a/schema/types/base/metaProperties.pb.go b/schema/types/base/metaProperties.pb.go deleted file mode 100644 index 5dfbfbfb1..000000000 --- a/schema/types/base/metaProperties.pb.go +++ /dev/null @@ -1,332 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/metaProperties.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type MetaProperties struct { - MetaPropertyList []MetaProperty `protobuf:"bytes,1,rep,name=metaPropertyList,proto3" json:"metaPropertyList"` -} - -func (m *MetaProperties) Reset() { *m = MetaProperties{} } -func (m *MetaProperties) String() string { return proto.CompactTextString(m) } -func (*MetaProperties) ProtoMessage() {} -func (*MetaProperties) Descriptor() ([]byte, []int) { - return fileDescriptor_8fb9d7c35b622115, []int{0} -} -func (m *MetaProperties) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MetaProperties) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MetaProperties.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MetaProperties) XXX_Merge(src proto.Message) { - xxx_messageInfo_MetaProperties.Merge(m, src) -} -func (m *MetaProperties) XXX_Size() int { - return m.Size() -} -func (m *MetaProperties) XXX_DiscardUnknown() { - xxx_messageInfo_MetaProperties.DiscardUnknown(m) -} - -var xxx_messageInfo_MetaProperties proto.InternalMessageInfo - -func (m *MetaProperties) GetMetaPropertyList() []MetaProperty { - if m != nil { - return m.MetaPropertyList - } - return nil -} - -func init() { - proto.RegisterType((*MetaProperties)(nil), "persistence_sdk.schema.types.base.MetaProperties") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/metaProperties.proto", fileDescriptor_8fb9d7c35b622115) -} - -var fileDescriptor_8fb9d7c35b622115 = []byte{ - // 214 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x2b, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x4d, - 0x2d, 0x49, 0x0c, 0x28, 0xca, 0x2f, 0x48, 0x2d, 0x2a, 0xc9, 0x4c, 0x2d, 0xd6, 0x2b, 0x28, 0xca, - 0x2f, 0xc9, 0x17, 0x52, 0x44, 0xd3, 0xa7, 0x07, 0xd1, 0xa7, 0x07, 0xd6, 0xa7, 0x07, 0xd2, 0x27, - 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, 0x4a, 0x99, 0x90, 0x64, - 0x61, 0x25, 0x44, 0x97, 0x52, 0x31, 0x17, 0x9f, 0x2f, 0x8a, 0x33, 0x84, 0x12, 0xb9, 0x04, 0x90, - 0xd5, 0xf9, 0x64, 0x16, 0x97, 0x48, 0x30, 0x2a, 0x30, 0x6b, 0x70, 0x1b, 0xe9, 0xeb, 0x11, 0x74, - 0x9b, 0x1e, 0x92, 0x61, 0x95, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, 0x04, 0x61, 0x18, 0xe7, 0x14, - 0x72, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, - 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c, 0x51, 0x56, 0xe9, 0x99, 0x25, 0x19, - 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x48, 0x96, 0xf9, 0xe7, 0xa5, 0x22, 0x73, 0x83, 0x5d, - 0xbc, 0x31, 0x7d, 0x97, 0xc4, 0x06, 0xf6, 0x91, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x9f, 0x2b, - 0x7a, 0xfd, 0x7a, 0x01, 0x00, 0x00, -} - -func (m *MetaProperties) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MetaProperties) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MetaProperties) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.MetaPropertyList) > 0 { - for iNdEx := len(m.MetaPropertyList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.MetaPropertyList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMetaProperties(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintMetaProperties(dAtA []byte, offset int, v uint64) int { - offset -= sovMetaProperties(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MetaProperties) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.MetaPropertyList) > 0 { - for _, e := range m.MetaPropertyList { - l = e.Size() - n += 1 + l + sovMetaProperties(uint64(l)) - } - } - return n -} - -func sovMetaProperties(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMetaProperties(x uint64) (n int) { - return sovMetaProperties(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MetaProperties) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaProperties - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MetaProperties: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MetaProperties: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MetaPropertyList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaProperties - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetaProperties - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetaProperties - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.MetaPropertyList = append(m.MetaPropertyList, MetaProperty{}) - if err := m.MetaPropertyList[len(m.MetaPropertyList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMetaProperties(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMetaProperties - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMetaProperties(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaProperties - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaProperties - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaProperties - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMetaProperties - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMetaProperties - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMetaProperties - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMetaProperties = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMetaProperties = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMetaProperties = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/metaProperty.go b/schema/types/base/metaProperty.go deleted file mode 100644 index 55afe1a55..000000000 --- a/schema/types/base/metaProperty.go +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "strings" - - "github.com/persistenceOne/persistenceSDK/constants" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ types.MetaProperty = (*MetaProperty)(nil) - -func (metaProperty MetaProperty) GetMetaFact() types.MetaFact { return &metaProperty.MetaFact } -func (metaProperty MetaProperty) GetID() types.ID { return &metaProperty.Id } -func (metaProperty MetaProperty) RemoveData() types.Property { - return NewProperty(metaProperty.GetID(), metaProperty.MetaFact.RemoveData()) -} - -func NewMetaProperty(id types.ID, metaFact types.MetaFact) *MetaProperty { - return &MetaProperty{ - Id: *NewID(id.String()), - MetaFact: *NewMetaFact(metaFact.GetData()), - } -} -func ReadMetaProperty(metaPropertyString string) (types.MetaProperty, error) { - propertyIDAndData := strings.Split(metaPropertyString, constants.PropertyIDAndDataSeparator) - if len(propertyIDAndData) == 2 && propertyIDAndData[0] != "" { - metaFact, Error := ReadMetaFact(propertyIDAndData[1]) - if Error != nil { - return nil, Error - } - - return NewMetaProperty(NewID(propertyIDAndData[0]), metaFact), nil - } - - return nil, errors.IncorrectFormat -} diff --git a/schema/types/base/metaProperty.pb.go b/schema/types/base/metaProperty.pb.go deleted file mode 100644 index a3beb8512..000000000 --- a/schema/types/base/metaProperty.pb.go +++ /dev/null @@ -1,364 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/metaProperty.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type MetaProperty struct { - Id ID `protobuf:"bytes,1,opt,name=id,proto3" json:"id"` - MetaFact MetaFact `protobuf:"bytes,2,opt,name=metaFact,proto3" json:"metaFact"` -} - -func (m *MetaProperty) Reset() { *m = MetaProperty{} } -func (m *MetaProperty) String() string { return proto.CompactTextString(m) } -func (*MetaProperty) ProtoMessage() {} -func (*MetaProperty) Descriptor() ([]byte, []int) { - return fileDescriptor_e00c620db06edd3e, []int{0} -} -func (m *MetaProperty) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MetaProperty) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MetaProperty.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MetaProperty) XXX_Merge(src proto.Message) { - xxx_messageInfo_MetaProperty.Merge(m, src) -} -func (m *MetaProperty) XXX_Size() int { - return m.Size() -} -func (m *MetaProperty) XXX_DiscardUnknown() { - xxx_messageInfo_MetaProperty.DiscardUnknown(m) -} - -var xxx_messageInfo_MetaProperty proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MetaProperty)(nil), "persistence_sdk.schema.types.base.MetaProperty") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/metaProperty.proto", fileDescriptor_e00c620db06edd3e) -} - -var fileDescriptor_e00c620db06edd3e = []byte{ - // 247 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x29, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0xcf, 0x4d, - 0x2d, 0x49, 0x0c, 0x28, 0xca, 0x2f, 0x48, 0x2d, 0x2a, 0xa9, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, - 0x17, 0x52, 0x44, 0xd3, 0xa5, 0x07, 0xd1, 0xa5, 0x07, 0xd6, 0xa5, 0x07, 0xd2, 0x25, 0x25, 0x92, - 0x9e, 0x9f, 0x9e, 0x0f, 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, 0x4a, 0x69, 0x11, 0xb6, 0x2e, 0x33, - 0x05, 0xaa, 0xd6, 0x80, 0x38, 0xa7, 0xb9, 0x25, 0x26, 0x97, 0x40, 0x74, 0x28, 0x2d, 0x60, 0xe4, - 0xe2, 0xf1, 0x45, 0x72, 0xad, 0x90, 0x35, 0x17, 0x53, 0x66, 0x8a, 0x04, 0xa3, 0x02, 0xa3, 0x06, - 0xb7, 0x91, 0xaa, 0x1e, 0x41, 0x47, 0xeb, 0x79, 0xba, 0x38, 0xb1, 0x9c, 0xb8, 0x27, 0xcf, 0x10, - 0xc4, 0x94, 0x99, 0x22, 0xe4, 0xcb, 0xc5, 0x01, 0x33, 0x5f, 0x82, 0x09, 0x6c, 0x84, 0x36, 0x11, - 0x46, 0xf8, 0x42, 0xb5, 0x40, 0x0d, 0x82, 0x1b, 0x61, 0xc5, 0xd2, 0xb1, 0x40, 0x9e, 0xc1, 0x29, - 0xe4, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, - 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0xac, 0xd2, 0x33, 0x4b, 0x32, - 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x91, 0xac, 0xf1, 0xcf, 0x4b, 0x45, 0xe6, 0x06, 0xbb, - 0x78, 0x63, 0x86, 0x43, 0x12, 0x1b, 0xd8, 0xff, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x20, - 0xeb, 0xcf, 0x94, 0xce, 0x01, 0x00, 0x00, -} - -func (m *MetaProperty) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MetaProperty) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MetaProperty) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.MetaFact.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMetaProperty(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.Id.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintMetaProperty(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintMetaProperty(dAtA []byte, offset int, v uint64) int { - offset -= sovMetaProperty(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *MetaProperty) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Id.Size() - n += 1 + l + sovMetaProperty(uint64(l)) - l = m.MetaFact.Size() - n += 1 + l + sovMetaProperty(uint64(l)) - return n -} - -func sovMetaProperty(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozMetaProperty(x uint64) (n int) { - return sovMetaProperty(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MetaProperty) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MetaProperty: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MetaProperty: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetaProperty - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetaProperty - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Id.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MetaFact", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetaProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetaProperty - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetaProperty - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.MetaFact.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMetaProperty(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthMetaProperty - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMetaProperty(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetaProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMetaProperty - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupMetaProperty - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthMetaProperty - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthMetaProperty = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMetaProperty = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupMetaProperty = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/parameter.go b/schema/types/base/parameter.go deleted file mode 100644 index 23cfcab44..000000000 --- a/schema/types/base/parameter.go +++ /dev/null @@ -1,6 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base diff --git a/schema/types/base/parameter.pb.go b/schema/types/base/parameter.pb.go deleted file mode 100644 index 22ba6100b..000000000 --- a/schema/types/base/parameter.pb.go +++ /dev/null @@ -1,379 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/parameter.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - _ "github.com/regen-network/cosmos-proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Parameter struct { - ID ID `protobuf:"bytes,1,opt,name=i_d,json=iD,proto3" json:"i_d"` - Data Data `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` -} - -func (m *Parameter) Reset() { *m = Parameter{} } -func (m *Parameter) String() string { return proto.CompactTextString(m) } -func (*Parameter) ProtoMessage() {} -func (*Parameter) Descriptor() ([]byte, []int) { - return fileDescriptor_c55cbae88e4b524a, []int{0} -} -func (m *Parameter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Parameter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Parameter.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Parameter) XXX_Merge(src proto.Message) { - xxx_messageInfo_Parameter.Merge(m, src) -} -func (m *Parameter) XXX_Size() int { - return m.Size() -} -func (m *Parameter) XXX_DiscardUnknown() { - xxx_messageInfo_Parameter.DiscardUnknown(m) -} - -var xxx_messageInfo_Parameter proto.InternalMessageInfo - -func (m *Parameter) GetID() ID { - if m != nil { - return m.ID - } - return ID{} -} - -func (m *Parameter) GetData() Data { - if m != nil { - return m.Data - } - return Data{} -} - -func init() { - proto.RegisterType((*Parameter)(nil), "persistence_sdk.schema.types.base.Parameter") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/parameter.proto", fileDescriptor_c55cbae88e4b524a) -} - -var fileDescriptor_c55cbae88e4b524a = []byte{ - // 252 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x2c, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x2f, 0x48, - 0x2c, 0x4a, 0xcc, 0x4d, 0x2d, 0x49, 0x2d, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x44, - 0xd3, 0xa2, 0x07, 0xd1, 0xa2, 0x07, 0xd6, 0xa2, 0x07, 0xd2, 0x22, 0x25, 0x92, 0x9e, 0x9f, 0x9e, - 0x0f, 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, 0x4a, 0x49, 0x26, 0xe7, 0x17, 0xe7, 0xe6, 0x17, 0xc7, - 0x43, 0x24, 0x20, 0x1c, 0xa8, 0x94, 0x16, 0x61, 0x67, 0x64, 0xa6, 0x40, 0xd5, 0xea, 0x10, 0x56, - 0x9b, 0x92, 0x58, 0x92, 0x08, 0x51, 0xad, 0xd4, 0xc3, 0xc8, 0xc5, 0x19, 0x00, 0xf3, 0x81, 0x90, - 0x0d, 0x17, 0x73, 0x66, 0x7c, 0x8a, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0xaa, 0x1e, 0x41, - 0x9f, 0xe8, 0x79, 0xba, 0x38, 0xb1, 0x9c, 0xb8, 0x27, 0xcf, 0x10, 0xc4, 0x94, 0xe9, 0x22, 0xe4, - 0xc8, 0xc5, 0x02, 0x32, 0x59, 0x82, 0x09, 0xac, 0x5d, 0x9d, 0x08, 0xed, 0x2e, 0x89, 0x25, 0x89, - 0x50, 0x03, 0xc0, 0x5a, 0x9d, 0x42, 0x4e, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, - 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, - 0xca, 0x2a, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0x1f, 0xc9, 0x60, 0xff, - 0xbc, 0x54, 0x64, 0x6e, 0xb0, 0x8b, 0x37, 0xa6, 0x7f, 0x93, 0xd8, 0xc0, 0x7e, 0x35, 0x06, 0x04, - 0x00, 0x00, 0xff, 0xff, 0xf3, 0xe9, 0x54, 0x7a, 0xce, 0x01, 0x00, 0x00, -} - -func (m *Parameter) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Parameter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Parameter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Data.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.ID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintParameter(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintParameter(dAtA []byte, offset int, v uint64) int { - offset -= sovParameter(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Parameter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.ID.Size() - n += 1 + l + sovParameter(uint64(l)) - l = m.Data.Size() - n += 1 + l + sovParameter(uint64(l)) - return n -} - -func sovParameter(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozParameter(x uint64) (n int) { - return sovParameter(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Parameter) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Parameter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Parameter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowParameter - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthParameter - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthParameter - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Data.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipParameter(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthParameter - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipParameter(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowParameter - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthParameter - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupParameter - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthParameter - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthParameter = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowParameter = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupParameter = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/properties.go b/schema/types/base/properties.go deleted file mode 100644 index 302ec67f9..000000000 --- a/schema/types/base/properties.go +++ /dev/null @@ -1,86 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ types.Properties = (*Properties)(nil) - -func (properties Properties) Get(id types.ID) types.Property { - for _, property := range properties.GetList() { - if property.GetID().Compare(id) == 0 { - return property - } - } - - return nil -} -func (properties Properties) GetList() []types.Property { - newPropertyList := make([]types.Property, len(properties.PropertyList)) - for i, _ := range properties.PropertyList { - newPropertyList[i] = &properties.PropertyList[i] - } - return newPropertyList -} -func (properties Properties) Add(propertyList ...types.Property) types.Properties { - newPropertyList := properties.GetList() - - for _, addProperty := range propertyList { - if properties.Get(addProperty.GetID()) == nil { - newPropertyList = append(newPropertyList, addProperty) - } - } - - return NewProperties(newPropertyList...) -} -func (properties Properties) Remove(propertyList ...types.Property) types.Properties { - newPropertyList := properties.GetList() - - for _, removeProperty := range propertyList { - for i, oldProperty := range newPropertyList { - if oldProperty.GetID().Compare(removeProperty.GetID()) == 0 { - newPropertyList = append(newPropertyList[:i], newPropertyList[i+1:]...) - break - } - } - } - - return NewProperties(newPropertyList...) -} -func (properties Properties) Mutate(propertyList ...types.Property) types.Properties { - newPropertyList := properties.GetList() - - for _, mutateProperty := range propertyList { - for i, oldProperty := range newPropertyList { - if oldProperty.GetID().Compare(mutateProperty.GetID()) == 0 { - newPropertyList[i] = mutateProperty - break - } - } - } - - return NewProperties(newPropertyList...) -} -func NewProperties(propertyList ...types.Property) *Properties { - newPropertyList := make([]Property, len(propertyList)) - for i, element := range propertyList { - newPropertyList[i] = *NewProperty(element.GetID(), element.GetFact()) - } - return &Properties{ - PropertyList: newPropertyList, - } -} - -func ReadProperties(propertiesString string) (types.Properties, error) { - properties, err := ReadMetaProperties(propertiesString) - if err != nil { - return nil, err - } - - return properties.RemoveData(), nil -} diff --git a/schema/types/base/properties.pb.go b/schema/types/base/properties.pb.go deleted file mode 100644 index 53b513487..000000000 --- a/schema/types/base/properties.pb.go +++ /dev/null @@ -1,332 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/properties.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Properties struct { - PropertyList []Property `protobuf:"bytes,1,rep,name=propertyList,proto3" json:"propertyList"` -} - -func (m *Properties) Reset() { *m = Properties{} } -func (m *Properties) String() string { return proto.CompactTextString(m) } -func (*Properties) ProtoMessage() {} -func (*Properties) Descriptor() ([]byte, []int) { - return fileDescriptor_be58753e8e26787a, []int{0} -} -func (m *Properties) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Properties) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Properties.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Properties) XXX_Merge(src proto.Message) { - xxx_messageInfo_Properties.Merge(m, src) -} -func (m *Properties) XXX_Size() int { - return m.Size() -} -func (m *Properties) XXX_DiscardUnknown() { - xxx_messageInfo_Properties.DiscardUnknown(m) -} - -var xxx_messageInfo_Properties proto.InternalMessageInfo - -func (m *Properties) GetPropertyList() []Property { - if m != nil { - return m.PropertyList - } - return nil -} - -func init() { - proto.RegisterType((*Properties)(nil), "persistence_sdk.schema.types.base.Properties") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/properties.proto", fileDescriptor_be58753e8e26787a) -} - -var fileDescriptor_be58753e8e26787a = []byte{ - // 210 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x2a, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x2f, 0x28, - 0xca, 0x2f, 0x48, 0x2d, 0x2a, 0xc9, 0x4c, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, - 0x44, 0xd3, 0xa3, 0x07, 0xd1, 0xa3, 0x07, 0xd6, 0xa3, 0x07, 0xd2, 0x23, 0x25, 0x92, 0x9e, 0x9f, - 0x9e, 0x0f, 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, 0x4a, 0x19, 0x10, 0x6d, 0x59, 0x25, 0x44, 0x87, - 0x52, 0x32, 0x17, 0x57, 0x00, 0xdc, 0x7a, 0xa1, 0x50, 0x2e, 0x1e, 0x98, 0xbc, 0x4f, 0x66, 0x71, - 0x89, 0x04, 0xa3, 0x02, 0xb3, 0x06, 0xb7, 0x91, 0xb6, 0x1e, 0x41, 0xf7, 0xe8, 0x41, 0x0d, 0xa9, - 0x74, 0x62, 0x39, 0x71, 0x4f, 0x9e, 0x21, 0x08, 0xc5, 0x18, 0xa7, 0x90, 0x13, 0x8f, 0xe4, 0x18, - 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f, 0xe5, - 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0xb2, 0x4a, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, - 0xcf, 0xd5, 0x47, 0xb2, 0xc4, 0x3f, 0x2f, 0x15, 0x99, 0x1b, 0xec, 0xe2, 0x8d, 0xe9, 0x93, 0x24, - 0x36, 0xb0, 0x0f, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x19, 0x72, 0x44, 0x00, 0x62, 0x01, - 0x00, 0x00, -} - -func (m *Properties) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Properties) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Properties) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.PropertyList) > 0 { - for iNdEx := len(m.PropertyList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.PropertyList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProperties(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintProperties(dAtA []byte, offset int, v uint64) int { - offset -= sovProperties(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Properties) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.PropertyList) > 0 { - for _, e := range m.PropertyList { - l = e.Size() - n += 1 + l + sovProperties(uint64(l)) - } - } - return n -} - -func sovProperties(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozProperties(x uint64) (n int) { - return sovProperties(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Properties) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProperties - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Properties: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Properties: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PropertyList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProperties - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProperties - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProperties - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PropertyList = append(m.PropertyList, Property{}) - if err := m.PropertyList[len(m.PropertyList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProperties(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProperties - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipProperties(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProperties - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProperties - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProperties - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthProperties - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupProperties - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthProperties - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthProperties = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProperties = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupProperties = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/properties_test.go b/schema/types/base/properties_test.go deleted file mode 100644 index 44b870b8d..000000000 --- a/schema/types/base/properties_test.go +++ /dev/null @@ -1,35 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/stretchr/testify/require" - "testing" -) - -func Test_Properties(t *testing.T) { - - testProperty := NewProperty(NewID("ID"), NewFact(NewStringData("Data"))) - testProperty2 := NewProperty(NewID("ID2"), NewFact(NewHeightData(NewHeight(12)))) - testProperties := NewProperties(testProperty, testProperty2) - - require.Equal(t, Properties{PropertyList: []types.Property{testProperty, testProperty2}}, testProperties) - require.Equal(t, testProperty, testProperties.Get(NewID("ID"))) - require.Equal(t, nil, testProperties.Get(NewID("RandomID"))) - require.Equal(t, []types.Property{testProperty, testProperty2}, testProperties.GetList()) - - newProperty := NewProperty(NewID("ID3"), NewFact(NewDecData(sdkTypes.NewDec(12)))) - require.Equal(t, Properties{PropertyList: []types.Property{testProperty, testProperty2, newProperty}}, testProperties.Add(newProperty)) - require.Equal(t, Properties{PropertyList: []types.Property{testProperty2}}, testProperties.Remove(testProperty)) - - mutatedProperty := NewProperty(NewID("ID2"), NewFact(NewIDData(NewID("IDString")))) - require.Equal(t, Properties{PropertyList: []types.Property{mutatedProperty, testProperty2}}, testProperties.Mutate(mutatedProperty)) - readProperties, Error := ReadProperties("ID:S|Data,ID2:H|12") - require.Equal(t, Properties{PropertyList: []types.Property{testProperty, testProperty2}}, readProperties) - require.Nil(t, Error) -} diff --git a/schema/types/base/property.go b/schema/types/base/property.go deleted file mode 100644 index 782ab85a9..000000000 --- a/schema/types/base/property.go +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ types.Property = (*Property)(nil) - -func (property Property) GetID() types.ID { return &property.Id } -func (property Property) GetFact() types.Fact { return &property.Fact } -func NewProperty(id types.ID, fact types.Fact) *Property { - return &Property{ - Id: *NewID(id.String()), - Fact: *NewFactProperty(fact.GetHashID(), fact.GetTypeID(), fact.GetSignatures()), - } -} -func ReadProperty(propertyString string) (types.Property, error) { - property, Error := ReadMetaProperty(propertyString) - if Error != nil { - return nil, Error - } - - return property.RemoveData(), nil -} diff --git a/schema/types/base/property.pb.go b/schema/types/base/property.pb.go deleted file mode 100644 index f0023d662..000000000 --- a/schema/types/base/property.pb.go +++ /dev/null @@ -1,364 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/property.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Property struct { - Id ID `protobuf:"bytes,1,opt,name=id,proto3" json:"id"` - Fact Fact `protobuf:"bytes,2,opt,name=fact,proto3" json:"fact"` -} - -func (m *Property) Reset() { *m = Property{} } -func (m *Property) String() string { return proto.CompactTextString(m) } -func (*Property) ProtoMessage() {} -func (*Property) Descriptor() ([]byte, []int) { - return fileDescriptor_94dee4c225d8dda3, []int{0} -} -func (m *Property) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Property) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Property.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Property) XXX_Merge(src proto.Message) { - xxx_messageInfo_Property.Merge(m, src) -} -func (m *Property) XXX_Size() int { - return m.Size() -} -func (m *Property) XXX_DiscardUnknown() { - xxx_messageInfo_Property.DiscardUnknown(m) -} - -var xxx_messageInfo_Property proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Property)(nil), "persistence_sdk.schema.types.base.Property") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/property.proto", fileDescriptor_94dee4c225d8dda3) -} - -var fileDescriptor_94dee4c225d8dda3 = []byte{ - // 243 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x28, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x2f, 0x28, - 0xca, 0x2f, 0x48, 0x2d, 0x2a, 0xa9, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x44, 0xd3, - 0xa1, 0x07, 0xd1, 0xa1, 0x07, 0xd6, 0xa1, 0x07, 0xd2, 0x21, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, - 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, 0x4a, 0x69, 0x11, 0xb6, 0x2a, 0x33, 0x05, 0xaa, 0x56, 0x87, - 0xb0, 0xda, 0xb4, 0xc4, 0xe4, 0x12, 0x88, 0x6a, 0xa5, 0x09, 0x8c, 0x5c, 0x1c, 0x01, 0x50, 0x57, - 0x0a, 0x59, 0x73, 0x31, 0x65, 0xa6, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x1b, 0xa9, 0xea, 0x11, - 0x74, 0xac, 0x9e, 0xa7, 0x8b, 0x13, 0xcb, 0x89, 0x7b, 0xf2, 0x0c, 0x41, 0x4c, 0x99, 0x29, 0x42, - 0x8e, 0x5c, 0x2c, 0x20, 0x73, 0x25, 0x98, 0xc0, 0xda, 0xd5, 0x89, 0xd0, 0xee, 0x96, 0x98, 0x5c, - 0x02, 0x35, 0x00, 0xac, 0xd5, 0x8a, 0xa5, 0x63, 0x81, 0x3c, 0x83, 0x53, 0xc8, 0x89, 0x47, 0x72, - 0x8c, 0x17, 0x1e, 0xc9, 0x31, 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, - 0x72, 0x0c, 0x37, 0x1e, 0xcb, 0x31, 0x44, 0x59, 0xa5, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, - 0xe7, 0xe7, 0xea, 0x23, 0x19, 0xef, 0x9f, 0x97, 0x8a, 0xcc, 0x0d, 0x76, 0xf1, 0xc6, 0xf4, 0x73, - 0x12, 0x1b, 0xd8, 0xbf, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x76, 0x76, 0x9b, 0xf3, 0xb6, - 0x01, 0x00, 0x00, -} - -func (m *Property) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Property) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Property) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Fact.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProperty(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - { - size, err := m.Id.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProperty(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintProperty(dAtA []byte, offset int, v uint64) int { - offset -= sovProperty(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Property) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Id.Size() - n += 1 + l + sovProperty(uint64(l)) - l = m.Fact.Size() - n += 1 + l + sovProperty(uint64(l)) - return n -} - -func sovProperty(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozProperty(x uint64) (n int) { - return sovProperty(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Property) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Property: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Property: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProperty - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProperty - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Id.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Fact", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProperty - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProperty - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProperty - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Fact.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProperty(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProperty - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipProperty(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProperty - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthProperty - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupProperty - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthProperty - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthProperty = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProperty = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupProperty = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/property_test.go b/schema/types/base/property_test.go deleted file mode 100644 index ca8a7ed12..000000000 --- a/schema/types/base/property_test.go +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/stretchr/testify/require" - "testing" -) - -func Test_Property(t *testing.T) { - - id := NewID("ID") - fact := NewFact(NewStringData("Data")) - - testProperty := NewProperty(id, fact) - require.Equal(t, Property{Id: id, Fact: fact}, testProperty) - require.Equal(t, id, testProperty.GetID()) - require.Equal(t, fact, testProperty.GetFact()) - - readProperty, Error := ReadProperty("ID2:S|SomeData") - require.Equal(t, NewProperty(NewID("ID2"), NewFact(NewStringData("SomeData"))), readProperty) - require.Nil(t, Error) - - readProperty, Error = ReadProperty("Random") - require.Equal(t, nil, readProperty) - require.Equal(t, errors.IncorrectFormat, Error) -} diff --git a/schema/types/base/signature.go b/schema/types/base/signature.go index 9e7fd9c5a..c04d320b8 100644 --- a/schema/types/base/signature.go +++ b/schema/types/base/signature.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base @@ -10,30 +8,37 @@ import ( "github.com/tendermint/tendermint/crypto" - "github.com/persistenceOne/persistenceSDK/schema/types" + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/types" ) -var _ types.Signature = (*Signature)(nil) +type signature struct { + ID ids.ID `json:"id"` + SignatureBytes []byte `json:"signatureBytes"` + ValidityHeight types.Height `json:"validityHeight"` +} + +var _ types.Signature = (*signature)(nil) -func (baseSignature Signature) String() string { +func (baseSignature signature) String() string { return base64.URLEncoding.EncodeToString(baseSignature.Bytes()) } -func (baseSignature Signature) Bytes() []byte { return baseSignature.SignatureBytes } -func (baseSignature Signature) GetID() types.ID { return &baseSignature.Id } -func (baseSignature Signature) Verify(pubKey crypto.PubKey, bytes []byte) bool { - return pubKey.VerifySignature(bytes, baseSignature.Bytes()) +func (baseSignature signature) Bytes() []byte { return baseSignature.SignatureBytes } +func (baseSignature signature) GetID() ids.ID { return baseSignature.ID } +func (baseSignature signature) Verify(pubKey crypto.PubKey, bytes []byte) bool { + return pubKey.VerifyBytes(bytes, baseSignature.Bytes()) } -func (baseSignature Signature) GetValidityHeight() types.Height { - return &baseSignature.ValidityHeight +func (baseSignature signature) GetValidityHeight() types.Height { + return baseSignature.ValidityHeight } -func (baseSignature Signature) HasExpired(height types.Height) bool { +func (baseSignature signature) HasExpired(height types.Height) bool { return baseSignature.GetValidityHeight().Compare(height) > 0 } -func NewSignature(id types.ID, signatureBytes []byte, validityHeight types.Height) *Signature { - return &Signature{ - Id: *NewID(id.String()), +func NewSignature(id ids.ID, signatureBytes []byte, validityHeight types.Height) types.Signature { + return signature{ + ID: id, SignatureBytes: signatureBytes, - ValidityHeight: *NewHeight(validityHeight.Get()), + ValidityHeight: validityHeight, } } diff --git a/schema/types/base/signature.pb.go b/schema/types/base/signature.pb.go deleted file mode 100644 index 1e71b9f4f..000000000 --- a/schema/types/base/signature.pb.go +++ /dev/null @@ -1,411 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/signature.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Signature struct { - Id ID `protobuf:"bytes,1,opt,name=id,proto3" json:"id"` - SignatureBytes []byte `protobuf:"bytes,2,opt,name=signature_bytes,json=signatureBytes,proto3" json:"signature_bytes,omitempty"` - ValidityHeight Height `protobuf:"bytes,3,opt,name=validity_height,json=validityHeight,proto3" json:"validity_height"` -} - -func (m *Signature) Reset() { *m = Signature{} } -func (*Signature) ProtoMessage() {} -func (*Signature) Descriptor() ([]byte, []int) { - return fileDescriptor_8496c3b012a7e5a2, []int{0} -} -func (m *Signature) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Signature) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Signature.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Signature) XXX_Merge(src proto.Message) { - xxx_messageInfo_Signature.Merge(m, src) -} -func (m *Signature) XXX_Size() int { - return m.Size() -} -func (m *Signature) XXX_DiscardUnknown() { - xxx_messageInfo_Signature.DiscardUnknown(m) -} - -var xxx_messageInfo_Signature proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Signature)(nil), "persistence_sdk.schema.types.base.Signature") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/signature.proto", fileDescriptor_8496c3b012a7e5a2) -} - -var fileDescriptor_8496c3b012a7e5a2 = []byte{ - // 287 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x2c, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x2f, 0xce, - 0x4c, 0xcf, 0x4b, 0x2c, 0x29, 0x2d, 0x4a, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x44, - 0xd3, 0xa2, 0x07, 0xd1, 0xa2, 0x07, 0xd6, 0xa2, 0x07, 0xd2, 0x22, 0x25, 0x92, 0x9e, 0x9f, 0x9e, - 0x0f, 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, 0x4a, 0x69, 0x11, 0xb6, 0x2b, 0x33, 0x05, 0xaa, 0x56, - 0x8f, 0xb0, 0xda, 0x8c, 0xd4, 0xcc, 0xf4, 0x8c, 0x12, 0x88, 0x7a, 0xa5, 0xab, 0x8c, 0x5c, 0x9c, - 0xc1, 0x30, 0x87, 0x0a, 0x59, 0x73, 0x31, 0x65, 0xa6, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x1b, - 0xa9, 0xea, 0x11, 0x74, 0xaf, 0x9e, 0xa7, 0x8b, 0x13, 0xcb, 0x89, 0x7b, 0xf2, 0x0c, 0x41, 0x4c, - 0x99, 0x29, 0x42, 0xea, 0x5c, 0xfc, 0x70, 0x2f, 0xc7, 0x27, 0x55, 0x96, 0xa4, 0x16, 0x4b, 0x30, - 0x29, 0x30, 0x6a, 0xf0, 0x04, 0xf1, 0xc1, 0x85, 0x9d, 0x40, 0xa2, 0x42, 0x11, 0x5c, 0xfc, 0x65, - 0x89, 0x39, 0x99, 0x29, 0x99, 0x25, 0x95, 0xf1, 0x10, 0xc7, 0x48, 0x30, 0x83, 0xad, 0xd4, 0x24, - 0xc2, 0x4a, 0x0f, 0xb0, 0x06, 0xa8, 0xb5, 0x7c, 0x30, 0x73, 0x20, 0xa2, 0x56, 0x1c, 0x1d, 0x0b, - 0xe4, 0x19, 0x66, 0x2c, 0x90, 0x67, 0x70, 0x0a, 0x39, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, - 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, - 0x39, 0x86, 0x28, 0xab, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0x24, - 0xeb, 0xfc, 0xf3, 0x52, 0x91, 0xb9, 0xc1, 0x2e, 0xde, 0x98, 0x41, 0x97, 0xc4, 0x06, 0x0e, 0x34, - 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xd1, 0x4e, 0x67, 0x9c, 0xfe, 0x01, 0x00, 0x00, -} - -func (m *Signature) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Signature) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Signature) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.ValidityHeight.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSignature(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - if len(m.SignatureBytes) > 0 { - i -= len(m.SignatureBytes) - copy(dAtA[i:], m.SignatureBytes) - i = encodeVarintSignature(dAtA, i, uint64(len(m.SignatureBytes))) - i-- - dAtA[i] = 0x12 - } - { - size, err := m.Id.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSignature(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintSignature(dAtA []byte, offset int, v uint64) int { - offset -= sovSignature(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Signature) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Id.Size() - n += 1 + l + sovSignature(uint64(l)) - l = len(m.SignatureBytes) - if l > 0 { - n += 1 + l + sovSignature(uint64(l)) - } - l = m.ValidityHeight.Size() - n += 1 + l + sovSignature(uint64(l)) - return n -} - -func sovSignature(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozSignature(x uint64) (n int) { - return sovSignature(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Signature) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSignature - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Signature: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Signature: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSignature - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSignature - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSignature - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Id.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SignatureBytes", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSignature - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthSignature - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthSignature - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SignatureBytes = append(m.SignatureBytes[:0], dAtA[iNdEx:postIndex]...) - if m.SignatureBytes == nil { - m.SignatureBytes = []byte{} - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidityHeight", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSignature - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSignature - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSignature - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.ValidityHeight.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSignature(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSignature - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipSignature(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSignature - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSignature - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSignature - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthSignature - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupSignature - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthSignature - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthSignature = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowSignature = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupSignature = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/signature_test.go b/schema/types/base/signature_test.go index cf041800d..5d0452414 100644 --- a/schema/types/base/signature_test.go +++ b/schema/types/base/signature_test.go @@ -1,38 +1,266 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base import ( "encoding/base64" + "reflect" "testing" + "github.com/AssetMantle/modules/schema/traits" + "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" + + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/types" ) -func Test_Signature(t *testing.T) { +type testableStringID struct { + IDString string +} + +func (t testableStringID) Compare(listable traits.Listable) int { + // TODO implement me + panic("implement me") +} + +func (t testableStringID) String() string { + // TODO implement me + panic("implement me") +} + +func (t testableStringID) Bytes() []byte { + return []byte(t.IDString) +} + +func (t testableStringID) IsStringID() { + // TODO implement me + panic("implement me") +} + +func NewStringID(idString string) ids.StringID { + return testableStringID{IDString: idString} +} + +func TestNewSignature(t *testing.T) { + privateKey := ed25519.GenPrivKey() - pubKey := privateKey.PubKey() - signatureBytes := NewID("Temp").Bytes() + // pubKey := privateKey.PubKey() + signatureBytes := []byte("Temp") signedBytes, err := privateKey.Sign(signatureBytes) require.Nil(t, err) - id := NewID("ID") + id := NewStringID("ID") validityHeight := NewHeight(123) testSignature := NewSignature(id, signedBytes, validityHeight) - require.Equal(t, Signature{Id: id, SignatureBytes: signedBytes, ValidityHeight: validityHeight}, testSignature) - require.Equal(t, base64.URLEncoding.EncodeToString(signedBytes), testSignature.String()) - require.Equal(t, signedBytes, testSignature.Bytes()) - require.Equal(t, id, testSignature.GetID()) + type args struct { + id ids.ID + signatureBytes []byte + validityHeight types.Height + } + tests := []struct { + name string + args args + want types.Signature + }{ + {"Test for New Signature", args{id, signedBytes, validityHeight}, testSignature}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := NewSignature(tt.args.id, tt.args.signatureBytes, tt.args.validityHeight); !reflect.DeepEqual(got, tt.want) { + t.Errorf("NewSignature() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_signature_Bytes(t *testing.T) { + + privateKey := ed25519.GenPrivKey() + // pubKey := privateKey.PubKey() + signatureBytes := NewStringID("Temp").Bytes() + + signedBytes, err := privateKey.Sign(signatureBytes) + require.Nil(t, err) + + id := NewStringID("ID") + validityHeight := NewHeight(123) + baseSignature := NewSignature(id, signedBytes, validityHeight) + + tests := []struct { + name string + baseSignature types.Signature + want []byte + }{ + {"Test for Bytes", baseSignature, signedBytes}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := baseSignature.Bytes(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("Bytes() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_signature_GetID(t *testing.T) { + + privateKey := ed25519.GenPrivKey() + // pubKey := privateKey.PubKey() + signatureBytes := NewStringID("Temp").Bytes() + + signedBytes, err := privateKey.Sign(signatureBytes) + require.Nil(t, err) + + id := NewStringID("ID") + validityHeight := NewHeight(123) + baseSignature := NewSignature(id, signedBytes, validityHeight) + + tests := []struct { + name string + baseSignature types.Signature + want ids.ID + }{ + {"Test to get Id", baseSignature, id}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := baseSignature.GetID(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetID() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_signature_GetValidityHeight(t *testing.T) { - require.Equal(t, validityHeight, testSignature.GetValidityHeight()) - require.Equal(t, true, testSignature.HasExpired(NewHeight(12))) + privateKey := ed25519.GenPrivKey() + // pubKey := privateKey.PubKey() + signatureBytes := NewStringID("Temp").Bytes() + + signedBytes, err := privateKey.Sign(signatureBytes) + require.Nil(t, err) + + id := NewStringID("ID") + validityHeight := NewHeight(123) + baseSignature := NewSignature(id, signedBytes, validityHeight) + + tests := []struct { + name string + baseSignature types.Signature + want types.Height + }{ + {"Test for GetValidityHeight", baseSignature, validityHeight}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := baseSignature.GetValidityHeight(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetValidityHeight() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_signature_HasExpired(t *testing.T) { + + privateKey := ed25519.GenPrivKey() + // pubKey := privateKey.PubKey() + signatureBytes := NewStringID("Temp").Bytes() + + signedBytes, err := privateKey.Sign(signatureBytes) + require.Nil(t, err) + + id := NewStringID("ID") + validityHeight := NewHeight(123) + baseSignature := NewSignature(id, signedBytes, validityHeight) + + type args struct { + height types.Height + } + tests := []struct { + name string + baseSignature types.Signature + args args + want bool + }{ + {"Test for Signature Expired", baseSignature, args{NewHeight(-10)}, true}, + {"Test for Signature Not Expired", baseSignature, args{validityHeight}, false}, + {"Test for zero case", baseSignature, args{NewHeight(0)}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := baseSignature.HasExpired(tt.args.height); got != tt.want { + t.Errorf("HasExpired() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_signature_String(t *testing.T) { + + privateKey := ed25519.GenPrivKey() + // pubKey := privateKey.PubKey() + signatureBytes := NewStringID("Temp").Bytes() + + signedBytes, err := privateKey.Sign(signatureBytes) + require.Nil(t, err) + + id := NewStringID("ID") + validityHeight := NewHeight(123) + baseSignature := NewSignature(id, signedBytes, validityHeight) + + tests := []struct { + name string + baseSignature types.Signature + want string + }{ + {"Test for String", baseSignature, base64.URLEncoding.EncodeToString(baseSignature.Bytes())}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := baseSignature.String(); got != tt.want { + t.Errorf("String() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_signature_Verify(t *testing.T) { + + privateKey := ed25519.GenPrivKey() + pubKey := privateKey.PubKey() + signatureBytes := NewStringID("Temp").Bytes() + + signedBytes, err := privateKey.Sign(signatureBytes) + require.Nil(t, err) + + id := NewStringID("ID") + validityHeight := NewHeight(123) + baseSignature := NewSignature(id, signedBytes, validityHeight) - require.Equal(t, false, testSignature.Verify(pubKey, []byte{})) - require.Equal(t, true, testSignature.Verify(pubKey, signatureBytes)) + type args struct { + pubKey crypto.PubKey + bytes []byte + } + tests := []struct { + name string + baseSignature types.Signature + args args + want bool + }{ + {"Test for Verify Signature", baseSignature, args{pubKey, signatureBytes}, true}, + {"Test for Not Equal case", baseSignature, args{pubKey, []byte{}}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := baseSignature.Verify(tt.args.pubKey, tt.args.bytes); got != tt.want { + t.Errorf("Verify() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/schema/types/base/signatures.go b/schema/types/base/signatures.go deleted file mode 100644 index c97bea086..000000000 --- a/schema/types/base/signatures.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ types.Signatures = (*Signatures)(nil) - -func (signatures Signatures) Get(id types.ID) types.Signature { - for _, signature := range signatures.SignatureList { - if signature.GetID().Compare(id) == 0 { - return &signature - } - } - - return nil -} -func (signatures Signatures) GetList() []types.Signature { - newSignatureList := make([]types.Signature, len(signatures.SignatureList)) - for i, _ := range signatures.SignatureList { - newSignatureList[i] = &signatures.SignatureList[i] - } - return newSignatureList -} -func (signatures Signatures) Add(signature types.Signature) types.Signatures { - signatures.SignatureList = append(signatures.SignatureList, *NewSignature(signature.GetID(), signature.Bytes(), signature.GetValidityHeight())) - return &signatures -} -func (signatures Signatures) Remove(signature types.Signature) types.Signatures { - signatureList := signatures.GetList() - for i, oldSignature := range signatureList { - if oldSignature.GetID().Compare(signature.GetID()) == 0 { - signatureList = append(signatureList[:i], signatureList[i+1:]...) - } - } - - return NewSignatures(signatureList) -} -func (signatures Signatures) Mutate(signature types.Signature) types.Signatures { - signatureList := signatures.GetList() - for i, oldSignature := range signatureList { - if oldSignature.GetID().Compare(signature.GetID()) == 0 { - signatureList[i] = signature - } - } - - return NewSignatures(signatureList) -} -func NewSignatures(signatureList []types.Signature) *Signatures { - newSignatureList := make([]Signature, len(signatureList)) - for i, element := range signatureList { - newSignatureList[i] = *NewSignature(element.GetID(), element.Bytes(), element.GetValidityHeight()) - } - return &Signatures{ - SignatureList: newSignatureList, - } -} diff --git a/schema/types/base/signatures.pb.go b/schema/types/base/signatures.pb.go deleted file mode 100644 index e23147a50..000000000 --- a/schema/types/base/signatures.pb.go +++ /dev/null @@ -1,332 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/signatures.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Signatures struct { - SignatureList []Signature `protobuf:"bytes,1,rep,name=signature_list,json=signatureList,proto3" json:"signature_list"` -} - -func (m *Signatures) Reset() { *m = Signatures{} } -func (m *Signatures) String() string { return proto.CompactTextString(m) } -func (*Signatures) ProtoMessage() {} -func (*Signatures) Descriptor() ([]byte, []int) { - return fileDescriptor_bfe86abedef3482d, []int{0} -} -func (m *Signatures) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Signatures) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Signatures.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Signatures) XXX_Merge(src proto.Message) { - xxx_messageInfo_Signatures.Merge(m, src) -} -func (m *Signatures) XXX_Size() int { - return m.Size() -} -func (m *Signatures) XXX_DiscardUnknown() { - xxx_messageInfo_Signatures.DiscardUnknown(m) -} - -var xxx_messageInfo_Signatures proto.InternalMessageInfo - -func (m *Signatures) GetSignatureList() []Signature { - if m != nil { - return m.SignatureList - } - return nil -} - -func init() { - proto.RegisterType((*Signatures)(nil), "persistence_sdk.schema.types.base.Signatures") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/signatures.proto", fileDescriptor_bfe86abedef3482d) -} - -var fileDescriptor_bfe86abedef3482d = []byte{ - // 220 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x2a, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x2f, 0xce, - 0x4c, 0xcf, 0x4b, 0x2c, 0x29, 0x2d, 0x4a, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, - 0x44, 0xd3, 0xa3, 0x07, 0xd1, 0xa3, 0x07, 0xd6, 0xa3, 0x07, 0xd2, 0x23, 0x25, 0x92, 0x9e, 0x9f, - 0x9e, 0x0f, 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, 0x4a, 0x19, 0x92, 0x60, 0x19, 0x44, 0x8b, 0x52, - 0x2e, 0x17, 0x57, 0x30, 0xdc, 0x7e, 0xa1, 0x48, 0x2e, 0x3e, 0xb8, 0x82, 0xf8, 0x9c, 0xcc, 0xe2, - 0x12, 0x09, 0x46, 0x05, 0x66, 0x0d, 0x6e, 0x23, 0x1d, 0x3d, 0x82, 0x4e, 0xd2, 0x83, 0x1b, 0xe3, - 0xc4, 0x72, 0xe2, 0x9e, 0x3c, 0x43, 0x10, 0x2f, 0xdc, 0x24, 0x9f, 0xcc, 0xe2, 0x12, 0x2b, 0x96, - 0x86, 0x3b, 0x0a, 0x0c, 0x4e, 0x21, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, - 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x17, 0x1e, 0xcb, 0x31, 0xdc, 0x78, 0x2c, 0xc7, 0x10, - 0x65, 0x95, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x8f, 0x64, 0x99, 0x7f, - 0x5e, 0x2a, 0x32, 0x37, 0xd8, 0xc5, 0x1b, 0xd3, 0x53, 0x49, 0x6c, 0x60, 0xbf, 0x18, 0x03, 0x02, - 0x00, 0x00, 0xff, 0xff, 0x14, 0xcd, 0x9c, 0x3c, 0x6d, 0x01, 0x00, 0x00, -} - -func (m *Signatures) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Signatures) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Signatures) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.SignatureList) > 0 { - for iNdEx := len(m.SignatureList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SignatureList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSignatures(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintSignatures(dAtA []byte, offset int, v uint64) int { - offset -= sovSignatures(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Signatures) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.SignatureList) > 0 { - for _, e := range m.SignatureList { - l = e.Size() - n += 1 + l + sovSignatures(uint64(l)) - } - } - return n -} - -func sovSignatures(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozSignatures(x uint64) (n int) { - return sovSignatures(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Signatures) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSignatures - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Signatures: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Signatures: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SignatureList", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSignatures - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSignatures - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSignatures - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SignatureList = append(m.SignatureList, Signature{}) - if err := m.SignatureList[len(m.SignatureList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSignatures(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSignatures - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipSignatures(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSignatures - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSignatures - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSignatures - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthSignatures - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupSignatures - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthSignatures - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthSignatures = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowSignatures = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupSignatures = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/signatures_test.go b/schema/types/base/signatures_test.go deleted file mode 100644 index c471e8330..000000000 --- a/schema/types/base/signatures_test.go +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -func Test_Signatures(t *testing.T) { - testSignature := NewSignature(NewID("ID"), NewID("signature").Bytes(), NewHeight(10)) - testSignature2 := NewSignature(NewID("ID2"), NewID("signature2").Bytes(), NewHeight(20)) - testSignatures := NewSignatures([]types.Signature{testSignature, testSignature2}) - require.Equal(t, Signatures{SignatureList: []types.Signature{testSignature, testSignature2}}, testSignatures) - require.Equal(t, testSignature, testSignatures.Get(NewID("ID"))) - require.Equal(t, nil, testSignatures.Get(NewID("ID3"))) - require.Equal(t, []types.Signature{testSignature, testSignature2}, testSignatures.GetList()) - - newSignature := NewSignature(NewID("ID3"), NewID("signature3").Bytes(), NewHeight(30)) - require.Equal(t, Signatures{SignatureList: []types.Signature{testSignature, testSignature2, newSignature}}, testSignatures.Add(newSignature)) - require.Equal(t, Signatures{SignatureList: []types.Signature{testSignature}}, testSignatures.Remove(testSignature2)) - - mutatedSignature := NewSignature(NewID("ID"), NewID("signatureMutated").Bytes(), NewHeight(100)) - require.Equal(t, Signatures{SignatureList: []types.Signature{mutatedSignature, testSignature2}}, testSignatures.Mutate(mutatedSignature)) -} diff --git a/schema/types/base/sortedDataList.go b/schema/types/base/sortedDataList.go deleted file mode 100644 index b4e03f737..000000000 --- a/schema/types/base/sortedDataList.go +++ /dev/null @@ -1,63 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "sort" - - "github.com/persistenceOne/persistenceSDK/schema/types" -) - -var _ types.SortedDataList = (*ListData)(nil) - -func (sortedDataList ListData) Search(data types.Data) int { - index := sort.Search( - len(sortedDataList.Value), - func(i int) bool { - return sortedDataList.Value[i].Compare(data) <= 0 - }, - ) - if index < len(sortedDataList.Value) { - if sortedDataList.Value[index].Compare(data) != 0 { - return len(sortedDataList.Value) - } - } - return index -} -func (sortedDataList ListData) GetList() []types.Data { - newList := make([]types.Data, len(sortedDataList.Value)) - for i, _ := range sortedDataList.Value { - newList[i] = &sortedDataList.Value[i] - } - return newList -} -func (sortedDataList ListData) Add(dataList ...types.Data) types.SortedDataList { - for _, data := range dataList { - if sortedDataList.Search(data) != len(sortedDataList.Value) { - return sortedDataList - } - - index := sort.Search( - len(sortedDataList.Value), - func(i int) bool { - return sortedDataList.Value[i].Compare(data) < 0 - }, - ) - newData := *NewData(data) - sortedDataList.Value = append(sortedDataList.Value, newData) - copy(sortedDataList.Value[index+1:], sortedDataList.Value[index:]) - sortedDataList.Value[index] = *NewData(data) - } - return sortedDataList -} -func (sortedDataList ListData) Remove(dataList ...types.Data) types.SortedDataList { - for _, data := range dataList { - if index := sortedDataList.Search(data); index != len(sortedDataList.Value) { - sortedDataList.Value = append(sortedDataList.Value[:index], sortedDataList.Value[index+1:]...) - } - } - return sortedDataList -} diff --git a/schema/types/base/split.pb.go b/schema/types/base/split.pb.go deleted file mode 100644 index 4a0b59953..000000000 --- a/schema/types/base/split.pb.go +++ /dev/null @@ -1,443 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: schema/types/base/split.proto - -package base - -import ( - fmt "fmt" - base "github.com/AssetMantle/modules/schema/ids/base" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type Split struct { - OwnerID *base.IdentityID `protobuf:"bytes,1,opt,name=OwnerID,proto3" json:"OwnerID,omitempty"` - OwnableID *base.OwnableID `protobuf:"bytes,2,opt,name=OwnableID,proto3" json:"OwnableID,omitempty"` - Value string `protobuf:"bytes,3,opt,name=Value,proto3" json:"Value,omitempty"` -} - -func (m *Split) Reset() { *m = Split{} } -func (m *Split) String() string { return proto.CompactTextString(m) } -func (*Split) ProtoMessage() {} -func (*Split) Descriptor() ([]byte, []int) { - return fileDescriptor_20963727f96ddfb0, []int{0} -} -func (m *Split) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Split) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Split.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Split) XXX_Merge(src proto.Message) { - xxx_messageInfo_Split.Merge(m, src) -} -func (m *Split) XXX_Size() int { - return m.Size() -} -func (m *Split) XXX_DiscardUnknown() { - xxx_messageInfo_Split.DiscardUnknown(m) -} - -var xxx_messageInfo_Split proto.InternalMessageInfo - -func (m *Split) GetOwnerID() *base.IdentityID { - if m != nil { - return m.OwnerID - } - return nil -} - -func (m *Split) GetOwnableID() *base.OwnableID { - if m != nil { - return m.OwnableID - } - return nil -} - -func (m *Split) GetValue() string { - if m != nil { - return m.Value - } - return "" -} - -func init() { - proto.RegisterType((*Split)(nil), "base.Split") -} - -func init() { proto.RegisterFile("schema/types/base/split.proto", fileDescriptor_20963727f96ddfb0) } - -var fileDescriptor_20963727f96ddfb0 = []byte{ - // 287 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2d, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x2f, 0x2e, - 0xc8, 0xc9, 0x2c, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, 0x89, 0x48, 0x29, 0x40, - 0x15, 0x65, 0xa6, 0x40, 0x95, 0x64, 0xa6, 0xa4, 0xe6, 0x95, 0x64, 0x96, 0x54, 0x7a, 0xba, 0x40, - 0xd4, 0x49, 0xc9, 0xa3, 0xab, 0xc8, 0x2f, 0xcf, 0x4b, 0x4c, 0xca, 0x49, 0x85, 0x29, 0x50, 0xaa, - 0xe0, 0x62, 0x0d, 0x06, 0x99, 0x2b, 0xa4, 0xc5, 0xc5, 0xee, 0x5f, 0x9e, 0x97, 0x5a, 0xe4, 0xe9, - 0x22, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0x6d, 0x24, 0xa0, 0x07, 0xd2, 0xa0, 0xe7, 0x09, 0x37, 0x32, - 0x08, 0xa6, 0x40, 0x48, 0x97, 0x8b, 0xd3, 0x1f, 0x66, 0x8e, 0x04, 0x13, 0x58, 0x35, 0x3f, 0x44, - 0x35, 0x5c, 0x38, 0x08, 0xa1, 0x42, 0x48, 0x84, 0x8b, 0x35, 0x2c, 0x31, 0xa7, 0x34, 0x55, 0x82, - 0x59, 0x81, 0x51, 0x83, 0x33, 0x08, 0xc2, 0x71, 0x9a, 0xc0, 0x78, 0xe2, 0x91, 0x1c, 0xe3, 0x85, - 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, - 0x8d, 0xc7, 0x72, 0x0c, 0x5c, 0x1c, 0xc9, 0xf9, 0xb9, 0x60, 0xf3, 0x9c, 0xb8, 0xc0, 0x8e, 0x0b, - 0x00, 0x39, 0x35, 0x80, 0x31, 0xca, 0x20, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, - 0x57, 0xdf, 0xb1, 0xb8, 0x38, 0xb5, 0xc4, 0x37, 0x31, 0xaf, 0x24, 0x27, 0x55, 0x3f, 0x37, 0x3f, - 0xa5, 0x34, 0x27, 0xb5, 0x58, 0x1f, 0x23, 0xcc, 0x16, 0x31, 0x31, 0x3b, 0x45, 0x44, 0xac, 0x62, - 0x62, 0x71, 0x4a, 0x2c, 0x4e, 0x3d, 0x05, 0xa1, 0x1e, 0x31, 0x09, 0x80, 0xa8, 0x18, 0xf7, 0x00, - 0x27, 0xdf, 0xd4, 0x92, 0xc4, 0x94, 0xc4, 0x92, 0xc4, 0x57, 0x10, 0x99, 0x24, 0x36, 0x70, 0x98, - 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x78, 0x13, 0xf8, 0x06, 0x7d, 0x01, 0x00, 0x00, -} - -func (m *Split) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Split) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Split) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - i -= len(m.Value) - copy(dAtA[i:], m.Value) - i = encodeVarintSplit(dAtA, i, uint64(len(m.Value))) - i-- - dAtA[i] = 0x1a - } - if m.OwnableID != nil { - { - size, err := m.OwnableID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSplit(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if m.OwnerID != nil { - { - size, err := m.OwnerID.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintSplit(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintSplit(dAtA []byte, offset int, v uint64) int { - offset -= sovSplit(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *Split) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.OwnerID != nil { - l = m.OwnerID.Size() - n += 1 + l + sovSplit(uint64(l)) - } - if m.OwnableID != nil { - l = m.OwnableID.Size() - n += 1 + l + sovSplit(uint64(l)) - } - l = len(m.Value) - if l > 0 { - n += 1 + l + sovSplit(uint64(l)) - } - return n -} - -func sovSplit(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozSplit(x uint64) (n int) { - return sovSplit(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *Split) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSplit - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Split: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Split: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OwnerID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSplit - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSplit - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSplit - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.OwnerID == nil { - m.OwnerID = &base.IdentityID{} - } - if err := m.OwnerID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OwnableID", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSplit - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthSplit - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthSplit - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.OwnableID == nil { - m.OwnableID = &base.OwnableID{} - } - if err := m.OwnableID.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSplit - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSplit - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSplit - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSplit(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSplit - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipSplit(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSplit - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSplit - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowSplit - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthSplit - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupSplit - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthSplit - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthSplit = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowSplit = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupSplit = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/split.proto b/schema/types/base/split.proto deleted file mode 100644 index 2871b69d3..000000000 --- a/schema/types/base/split.proto +++ /dev/null @@ -1,11 +0,0 @@ -syntax = "proto3"; -package base; - -import "schema/ids/base/identityID.proto"; -import "schema/ids/base/ownableID.proto"; - -message Split{ - IdentityID OwnerID = 1; - OwnableID OwnableID = 2; - string Value = 3; -} \ No newline at end of file diff --git a/schema/types/base/stringData.go b/schema/types/base/stringData.go deleted file mode 100644 index 9e8424622..000000000 --- a/schema/types/base/stringData.go +++ /dev/null @@ -1,145 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "strings" - - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/schema/types" - "github.com/persistenceOne/persistenceSDK/utilities/meta" -) - -var _, _ types.Data = (*Data_StringData)(nil), (*StringData)(nil) - -func (stringData Data_StringData) Compare(data types.Data) int { - compareStringData, Error := stringDataFromInterface(data) - if Error != nil { - panic(Error) - } - - return strings.Compare(stringData.StringData.Value, compareStringData.StringData.Value) -} -func (stringData Data_StringData) String() string { - return stringData.StringData.Value -} -func (stringData Data_StringData) GetTypeID() types.ID { - return NewID("S") -} -func (stringData Data_StringData) ZeroValue() types.Data { - return NewStringData("") -} -func (stringData Data_StringData) GenerateHashID() types.ID { - return NewID(meta.Hash(stringData.StringData.Value)) -} -func (stringData Data_StringData) AsAccAddress() (sdkTypes.AccAddress, error) { - zeroValue, _ := Data_AccAddressData{}.ZeroValue().AsAccAddress() - return zeroValue, errors.EntityNotFound -} -func (stringData Data_StringData) AsListData() (types.ListData, error) { - zeroValue, _ := Data_ListData{}.ZeroValue().AsListData() - return zeroValue, errors.IncorrectFormat -} -func (stringData Data_StringData) AsString() (string, error) { - return stringData.StringData.Value, nil -} -func (stringData Data_StringData) AsDec() (sdkTypes.Dec, error) { - zeroValue, _ := Data_DecData{}.ZeroValue().AsDec() - return zeroValue, errors.IncorrectFormat -} -func (stringData Data_StringData) AsHeight() (types.Height, error) { - zeroValue, _ := Data_HeightData{}.ZeroValue().AsHeight() - return zeroValue, errors.IncorrectFormat -} -func (stringData Data_StringData) AsID() (types.ID, error) { - zeroValue, _ := Data_IdData{}.ZeroValue().AsID() - return zeroValue, errors.IncorrectFormat -} -func (stringData Data_StringData) Get() interface{} { - return stringData.StringData.Value -} -func (stringData Data_StringData) Unmarshal(dAtA []byte) error { - return stringData.StringData.Unmarshal(dAtA) -} -func (stringData *Data_StringData) Reset() { *stringData = Data_StringData{} } -func (*Data_StringData) ProtoMessage() {} - -func stringDataFromInterface(data types.Data) (Data_StringData, error) { - switch value := data.(type) { - case *Data_StringData: - return *value, nil - default: - return Data_StringData{}, errors.MetaDataError - } -} - -func NewStringData(value string) types.Data { - return &Data_StringData{ - StringData: &StringData{ - Value: value, - }, - } -} - -func ReadStringData(stringData string) (types.Data, error) { - return NewStringData(stringData), nil -} - -func (stringData StringData) Compare(data types.Data) int { - compareStringData, Error := dummyStringDataFromInterface(data) - if Error != nil { - panic(Error) - } - - return strings.Compare(stringData.Value, compareStringData.Value) -} -func (stringData StringData) String() string { - return stringData.Value -} -func (stringData StringData) GetTypeID() types.ID { - return NewID("S") -} -func (stringData StringData) ZeroValue() types.Data { - return NewStringData("") -} -func (stringData StringData) GenerateHashID() types.ID { - return NewID(meta.Hash(stringData.Value)) -} -func (stringData StringData) AsAccAddress() (sdkTypes.AccAddress, error) { - zeroValue, _ := AccAddressData{}.ZeroValue().AsAccAddress() - return zeroValue, errors.EntityNotFound -} -func (stringData StringData) AsListData() (types.ListData, error) { - zeroValue, _ := ListData{}.ZeroValue().AsListData() - return zeroValue, errors.IncorrectFormat -} -func (stringData StringData) AsString() (string, error) { - return stringData.Value, nil -} -func (stringData StringData) AsDec() (sdkTypes.Dec, error) { - zeroValue, _ := DecData{}.ZeroValue().AsDec() - return zeroValue, errors.IncorrectFormat -} -func (stringData StringData) AsHeight() (types.Height, error) { - zeroValue, _ := HeightData{}.ZeroValue().AsHeight() - return zeroValue, errors.IncorrectFormat -} -func (stringData StringData) AsID() (types.ID, error) { - zeroValue, _ := IDData{}.ZeroValue().AsID() - return zeroValue, errors.IncorrectFormat -} -func (stringData StringData) Get() interface{} { - return stringData.Value -} -func dummyStringDataFromInterface(data types.Data) (StringData, error) { - switch value := data.(type) { - case *StringData: - return *value, nil - default: - return StringData{}, errors.MetaDataError - } -} diff --git a/schema/types/base/stringData.pb.go b/schema/types/base/stringData.pb.go deleted file mode 100644 index 5e155b1fc..000000000 --- a/schema/types/base/stringData.pb.go +++ /dev/null @@ -1,318 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: persistence_sdk/schema/types/base/stringData.proto - -package base - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -type StringData struct { - Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *StringData) Reset() { *m = StringData{} } -func (*StringData) ProtoMessage() {} -func (*StringData) Descriptor() ([]byte, []int) { - return fileDescriptor_9921211417c39aeb, []int{0} -} -func (m *StringData) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *StringData) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_StringData.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *StringData) XXX_Merge(src proto.Message) { - xxx_messageInfo_StringData.Merge(m, src) -} -func (m *StringData) XXX_Size() int { - return m.Size() -} -func (m *StringData) XXX_DiscardUnknown() { - xxx_messageInfo_StringData.DiscardUnknown(m) -} - -var xxx_messageInfo_StringData proto.InternalMessageInfo - -func (m *StringData) GetValue() string { - if m != nil { - return m.Value - } - return "" -} - -func init() { - proto.RegisterType((*StringData)(nil), "persistence_sdk.schema.types.base.StringData") -} - -func init() { - proto.RegisterFile("persistence_sdk/schema/types/base/stringData.proto", fileDescriptor_9921211417c39aeb) -} - -var fileDescriptor_9921211417c39aeb = []byte{ - // 191 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x2a, 0x48, 0x2d, 0x2a, - 0xce, 0x2c, 0x2e, 0x49, 0xcd, 0x4b, 0x4e, 0x8d, 0x2f, 0x4e, 0xc9, 0xd6, 0x2f, 0x4e, 0xce, 0x48, - 0xcd, 0x4d, 0xd4, 0x2f, 0xa9, 0x2c, 0x48, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0xd5, 0x2f, 0x2e, - 0x29, 0xca, 0xcc, 0x4b, 0x77, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, - 0x44, 0xd3, 0xa3, 0x07, 0xd1, 0xa3, 0x07, 0xd6, 0xa3, 0x07, 0xd2, 0x23, 0x25, 0x92, 0x9e, 0x9f, - 0x9e, 0x0f, 0x56, 0xad, 0x0f, 0x62, 0x41, 0x34, 0x2a, 0x69, 0x70, 0x71, 0x05, 0xc3, 0x0d, 0x13, - 0x12, 0xe1, 0x62, 0x2d, 0x4b, 0xcc, 0x29, 0x4d, 0x95, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x0c, 0x82, - 0x70, 0xac, 0x58, 0x66, 0x2c, 0x90, 0x67, 0x70, 0x0a, 0x39, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, - 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, - 0x63, 0x39, 0x86, 0x28, 0xab, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, - 0x24, 0x77, 0xf8, 0xe7, 0xa5, 0x22, 0x73, 0x83, 0x5d, 0xbc, 0x31, 0x7d, 0x92, 0xc4, 0x06, 0x76, - 0x86, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x22, 0xce, 0xdb, 0x7b, 0xf5, 0x00, 0x00, 0x00, -} - -func (m *StringData) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *StringData) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *StringData) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - i -= len(m.Value) - copy(dAtA[i:], m.Value) - i = encodeVarintStringData(dAtA, i, uint64(len(m.Value))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintStringData(dAtA []byte, offset int, v uint64) int { - offset -= sovStringData(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *StringData) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Value) - if l > 0 { - n += 1 + l + sovStringData(uint64(l)) - } - return n -} - -func sovStringData(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozStringData(x uint64) (n int) { - return sovStringData(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *StringData) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStringData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: StringData: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: StringData: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowStringData - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthStringData - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthStringData - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipStringData(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthStringData - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipStringData(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStringData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStringData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowStringData - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthStringData - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupStringData - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthStringData - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthStringData = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowStringData = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupStringData = fmt.Errorf("proto: unexpected end of group") -) diff --git a/schema/types/base/stringData_test.go b/schema/types/base/stringData_test.go deleted file mode 100644 index 01486124b..000000000 --- a/schema/types/base/stringData_test.go +++ /dev/null @@ -1,56 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package base - -import ( - "testing" - - sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/persistenceOne/persistenceSDK/utilities/meta" - "github.com/stretchr/testify/require" -) - -func Test_StringData(t *testing.T) { - - value := "data" - testStringData := NewStringData(value) - testStringData2 := NewStringData("") - - require.Equal(t, value, testStringData.String()) - require.Equal(t, NewID(meta.Hash(value)), testStringData.GenerateHashID()) - require.Equal(t, NewID(""), testStringData2.GenerateHashID()) - require.Equal(t, testStringData.GetTypeID(), NewID("S")) - require.Equal(t, testStringData.ZeroValue(), NewStringData("")) - - dataAsString, Error := testStringData.AsString() - require.Equal(t, value, dataAsString) - require.Equal(t, nil, Error) - - dataAsID, Error := testStringData.AsID() - require.Equal(t, ID{}, dataAsID) - require.Equal(t, errors.IncorrectFormat, Error) - - dataAsHeight, Error := testStringData.AsHeight() - require.Equal(t, Height{}, dataAsHeight) - require.Equal(t, errors.IncorrectFormat, Error) - - dataAsDec, Error := testStringData.AsDec() - require.Equal(t, sdkTypes.ZeroDec(), dataAsDec) - require.Equal(t, errors.IncorrectFormat, Error) - - require.Equal(t, value, testStringData.Get()) - - data, Error := ReadStringData("testString") - require.Nil(t, Error) - require.Equal(t, StringData{Value: "testString"}.String(), data.String()) - - require.Equal(t, false, testStringData.Compare(testStringData2) == 0) - require.Equal(t, true, testStringData.Compare(testStringData) == 0) - require.Panics(t, func() { - require.Equal(t, false, testStringData.Compare(NewIDData(NewID("ID"))) == 0) - }) -} diff --git a/schema/types/codec.go b/schema/types/codec.go index 91dc92299..4aa1ae538 100644 --- a/schema/types/codec.go +++ b/schema/types/codec.go @@ -7,7 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" ) -func RegisterCodec(codec *codec.LegacyAmino) { +func RegisterCodec(codec *codec.Codec) { codec.RegisterInterface((*Height)(nil), nil) codec.RegisterInterface((*Signature)(nil), nil) codec.RegisterInterface((*Split)(nil), nil) diff --git a/schema/types/codec_test.go b/schema/types/codec_test.go new file mode 100644 index 000000000..3bd398f29 --- /dev/null +++ b/schema/types/codec_test.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package types + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterCodec(t *testing.T) { + type args struct { + codec *codec.Codec + } + tests := []struct { + name string + args args + }{ + + {"+ve", args{codec.New()}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterCodec(tt.args.codec) + }) + } +} diff --git a/schema/types/customError.go b/schema/types/customError.go deleted file mode 100644 index 16909be72..000000000 --- a/schema/types/customError.go +++ /dev/null @@ -1,6 +0,0 @@ -package types - -type Error interface { - Proto - error -} diff --git a/schema/types/fact.go b/schema/types/fact.go deleted file mode 100644 index a9b05cc5f..000000000 --- a/schema/types/fact.go +++ /dev/null @@ -1,20 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -import ( - "github.com/99designs/keyring" -) - -type Fact interface { - GetHashID() ID - GetTypeID() ID - GetSignatures() Signatures - - Sign(keyring.Keyring) Fact - - Proto -} diff --git a/schema/types/height.go b/schema/types/height.go index ec2fba277..8e831095b 100644 --- a/schema/types/height.go +++ b/schema/types/height.go @@ -12,6 +12,4 @@ type Height interface { Get() int64 Compare(Height) int - - Proto } diff --git a/schema/types/listData.go b/schema/types/listData.go deleted file mode 100644 index 2b29de93c..000000000 --- a/schema/types/listData.go +++ /dev/null @@ -1,28 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -type ListData interface { - Data - - Search(Data) int - - GetList() []Data - - Add(...Data) ListData - Remove(...Data) ListData -} - -type DummyListData interface { - Data - - BaseSearch(Data) int - - BaseGetList() []Data - - BaseAdd(...Data) DummyListData - BaseRemove(...Data) DummyListData -} diff --git a/schema/types/metaFact.go b/schema/types/metaFact.go deleted file mode 100644 index 942968fd6..000000000 --- a/schema/types/metaFact.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -import ( - "github.com/99designs/keyring" -) - -type MetaFact interface { - GetHashID() ID - GetTypeID() ID - GetData() Data - GetSignatures() Signatures - - Sign(keyring.Keyring) MetaFact - RemoveData() Fact - - Proto -} diff --git a/schema/types/metaProperties.go b/schema/types/metaProperties.go deleted file mode 100644 index 97c1a5f3e..000000000 --- a/schema/types/metaProperties.go +++ /dev/null @@ -1,20 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -type MetaProperties interface { - Get(ID) MetaProperty - - GetList() []MetaProperty - - Add(...MetaProperty) MetaProperties - Remove(...MetaProperty) MetaProperties - Mutate(...MetaProperty) MetaProperties - - RemoveData() Properties - - Proto -} diff --git a/schema/types/metaProperty.go b/schema/types/metaProperty.go deleted file mode 100644 index 290ec23e7..000000000 --- a/schema/types/metaProperty.go +++ /dev/null @@ -1,14 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -type MetaProperty interface { - GetID() ID - GetMetaFact() MetaFact - RemoveData() Property - - Proto -} diff --git a/schema/types/parameter.go b/schema/types/parameter.go deleted file mode 100644 index 1392657f0..000000000 --- a/schema/types/parameter.go +++ /dev/null @@ -1,20 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -type Parameter interface { - String() string - - Equal(Parameter) bool - Validate() error - - GetID() ID - GetData() Data - GetValidator() func(interface{}) error - - Mutate(Data) Parameter - Proto -} diff --git a/schema/types/properties.go b/schema/types/properties.go deleted file mode 100644 index bfd0a8e47..000000000 --- a/schema/types/properties.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -type Properties interface { - Get(ID) Property - - GetList() []Property - - Add(...Property) Properties - Remove(...Property) Properties - Mutate(...Property) Properties - - Proto -} diff --git a/schema/types/property.go b/schema/types/property.go deleted file mode 100644 index 9784b944f..000000000 --- a/schema/types/property.go +++ /dev/null @@ -1,13 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -type Property interface { - GetID() ID - GetFact() Fact - - Proto -} diff --git a/schema/types/proto.go b/schema/types/proto.go deleted file mode 100644 index 3a0d1a6ce..000000000 --- a/schema/types/proto.go +++ /dev/null @@ -1,7 +0,0 @@ -package types - -type Proto interface { - Size() int - MarshalTo(data []byte) (int, error) - Unmarshal(dAtA []byte) error -} diff --git a/schema/types/signature.go b/schema/types/signature.go index 0a3c78b6c..8f9d843ea 100644 --- a/schema/types/signature.go +++ b/schema/types/signature.go @@ -18,6 +18,4 @@ type Signature interface { Verify(crypto.PubKey, []byte) bool GetValidityHeight() Height HasExpired(Height) bool - - Proto } diff --git a/schema/types/signatures.go b/schema/types/signatures.go deleted file mode 100644 index c13ec8f57..000000000 --- a/schema/types/signatures.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ - -package types - -type Signatures interface { - Get(ID) Signature - - GetList() []Signature - - Add(Signature) Signatures - Remove(Signature) Signatures - Mutate(Signature) Signatures - - Proto -} diff --git a/scripts/compile.sh b/scripts/compile.sh deleted file mode 100644 index 97b4aaf9c..000000000 --- a/scripts/compile.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bash - -set -eo pipefail - -protoc_gen_gocosmos() { - if ! grep "github.com/gogo/protobuf => github.com/regen-network/protobuf" go.mod &>/dev/null ; then - echo -e "\tPlease run this command from somewhere inside the cosmos-sdk folder." - return 1 - fi - - go get github.com/regen-network/cosmos-proto/protoc-gen-gocosmos@latest 2>/dev/null -} - -proto_dirs=$(find ./proto/persistence_sdk -path -prune -o -name '*.proto' -print0 | xargs -0 -n1 dirname | sort | uniq) -for dir in $proto_dirs; do - buf protoc \ - -I "proto" \ - -I "thirdParty/proto" \ - --gocosmos_out=plugins=interfacetype+grpc,\ -Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types:. \ - --grpc-gateway_out=logtostderr=true:. \ - $(find "${dir}" -maxdepth 1 -name '*.proto') - -done - -cp -r github.com/persistenceOne/persistenceSDK/* ./ -rm -rf github.com diff --git a/simulation/make/BenchmarkFullAppSimulation_test.go b/simulation/make/BenchmarkFullAppSimulation_test.go new file mode 100644 index 000000000..6103280f8 --- /dev/null +++ b/simulation/make/BenchmarkFullAppSimulation_test.go @@ -0,0 +1,48 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package make + +import ( + "os" + "testing" + + "github.com/CosmWasm/wasmd/x/wasm" + "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/applications/base" +) + +// Profile with: +// /usr/local/go/bin/go test -benchmem -run=^$ github.com/AssetMantle/modules/simapp -bench ^BenchmarkFullAppSimulation$ -Commit=true -cpuprofile cpu.out +func BenchmarkFullAppSimulation(b *testing.B) { + config, db, _, logger, _, closeFn, err := setupRun(b, "goleveldb-app-sim", "Simulation") + defer closeFn() + + require.NoError(b, err, "simulation setup failed") + + prototype := base.NewSimulationApplication(applicationName, moduleBasicManager, wasm.EnableAllProposals, moduleAccountPermissions, tokenReceiveAllowedModules).(*base.SimulationApplication) + simulationApplication := prototype.InitializeSimulationApplication(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultNodeHome(), interBlockCacheOpt()).(*base.SimulationApplication) + + // run randomized simulation + _, simParams, simErr := simulation.SimulateFromSeed( + b, os.Stdout, simulationApplication.GetBaseApp(), simapp.AppStateFn(simulationApplication.Codec(), simulationApplication.SimulationManager()), + simapp.SimulationOperations(simulationApplication, simulationApplication.Codec(), config), + simulationApplication.ModuleAccountAddrs(), config, + ) + + // export state and simParams before the simulation error is checked + if err = simapp.CheckExportSimulation(simulationApplication, config, simParams); err != nil { + b.Fatal(err) + } + + if simErr != nil { + b.Fatal(simErr) + } + + if config.Commit { + simapp.PrintStats(db) + } +} diff --git a/simulation/make/BenchmarkInvariants_test.go b/simulation/make/BenchmarkInvariants_test.go new file mode 100644 index 000000000..54dfdb7d2 --- /dev/null +++ b/simulation/make/BenchmarkInvariants_test.go @@ -0,0 +1,69 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package make + +import ( + "fmt" + "os" + "testing" + + "github.com/CosmWasm/wasmd/x/wasm" + "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/AssetMantle/modules/schema/applications/base" +) + +func BenchmarkInvariants(b *testing.B) { + config, db, _, logger, _, closeFn, err := setupRun(b, "leveldb-app-invariant-bench", "Simulation") + defer closeFn() + + require.NoError(b, err, "simulation setup failed") + + config.AllInvariants = false + + prototype := base.NewSimulationApplication(applicationName, moduleBasicManager, wasm.EnableAllProposals, moduleAccountPermissions, tokenReceiveAllowedModules).(*base.SimulationApplication) + simulationApplication := prototype.InitializeSimulationApplication(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultNodeHome(), interBlockCacheOpt()).(*base.SimulationApplication) + + // run randomized simulation + _, simParams, simErr := simulation.SimulateFromSeed( + b, os.Stdout, simulationApplication.GetBaseApp(), simapp.AppStateFn(simulationApplication.Codec(), simulationApplication.SimulationManager()), + simapp.SimulationOperations(simulationApplication, simulationApplication.Codec(), config), + simulationApplication.ModuleAccountAddrs(), config, + ) + + // export state and simParams before the simulation error is checked + if err = simapp.CheckExportSimulation(simulationApplication, config, simParams); err != nil { + b.Fatal(err) + } + + if simErr != nil { + b.Fatal(simErr) + } + + if config.Commit { + simapp.PrintStats(db) + } + + ctx := simulationApplication.GetBaseApp().NewContext(true, abci.Header{Height: simulationApplication.GetBaseApp().LastBlockHeight() + 1}) + + // 3. Benchmark each invariant separately + // + // NOTE: We use the crisis keeper as it has all the invariants registered with + // their respective metadata which makes it useful for testing/benchmarking. + for _, cr := range simulationApplication.CrisisKeeper.Routes() { + cr := cr + + b.Run(fmt.Sprintf("%s/%s", cr.ModuleName, cr.Route), func(b *testing.B) { + if res, stop := cr.Invar(ctx); stop { + b.Fatalf( + "broken invariant at block %d of %d\n%s", + ctx.BlockHeight()-1, config.NumBlocks, res, + ) + } + }) + } +} diff --git a/simulation/make/Makefile b/simulation/make/Makefile new file mode 100644 index 000000000..88600ddc4 --- /dev/null +++ b/simulation/make/Makefile @@ -0,0 +1,48 @@ +### +# Find OS and Go environment +# GO contains the Go binary +# FS contains the OS file separator +### +ifeq ($(OS),Windows_NT) + GO := $(shell where go.exe 2> NUL) + FS := "\\" +else + GO := $(shell command -v go 2> /dev/null) + FS := "/" +endif + +ifeq ($(GO),) + $(error could not find go. Is it in PATH? $(GO)) +endif + +GOPATH ?= $(shell $(GO) env GOPATH) +GITHUBDIR := $(GOPATH)$(FS)src$(FS)github.com + +### +# tools +### + +TOOLS_DESTDIR ?= $(GOPATH)/bin + +RUNSIM = $(TOOLS_DESTDIR)/runsim + +all: tools + +tools: runsim + + +# Install the runsim binary with a temporary workaround of entering an outside +# directory as the "go get" command ignores the -mod option and will pollute the +# go.{mod, sum} files. +# +# ref: https://github.com/golang/go/issues/30515 +runsim: $(RUNSIM) +$(RUNSIM): + @echo "Installing runsim..." + @(cd /tmp && go install github.com/cosmos/tools/cmd/runsim@v1.0.0) + +tools-clean: + rm -f $(RUNSIM) + rm -f tools-stamp + +.PHONY: all tools tools-clean diff --git a/simulation/make/TestAppImportExport_test.go b/simulation/make/TestAppImportExport_test.go index e91189f97..8534d8449 100644 --- a/simulation/make/TestAppImportExport_test.go +++ b/simulation/make/TestAppImportExport_test.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package make @@ -10,35 +8,37 @@ import ( "os" "testing" + "github.com/CosmWasm/wasmd/x/wasm" + "github.com/cosmos/cosmos-sdk/store" - "github.com/persistenceOne/persistenceSDK/schema/applications/base" - "github.com/CosmWasm/wasmd/x/wasm" + "github.com/AssetMantle/modules/schema/applications/base" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/distribution" "github.com/cosmos/cosmos-sdk/x/gov" "github.com/cosmos/cosmos-sdk/x/mint" "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/supply" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" - "github.com/persistenceOne/persistenceSDK/modules/assets" - "github.com/persistenceOne/persistenceSDK/modules/classifications" - "github.com/persistenceOne/persistenceSDK/modules/identities" - "github.com/persistenceOne/persistenceSDK/modules/maintainers" - "github.com/persistenceOne/persistenceSDK/modules/metas" - "github.com/persistenceOne/persistenceSDK/modules/orders" - "github.com/persistenceOne/persistenceSDK/modules/splits" + "github.com/AssetMantle/modules/modules/assets" + "github.com/AssetMantle/modules/modules/classifications" + "github.com/AssetMantle/modules/modules/identities" + "github.com/AssetMantle/modules/modules/maintainers" + "github.com/AssetMantle/modules/modules/metas" + "github.com/AssetMantle/modules/modules/orders" + "github.com/AssetMantle/modules/modules/splits" ) -// Get flags every time the simulator is run +// GetProperty flags every time the simulator is run func init() { simapp.GetSimulatorFlags() } @@ -69,8 +69,8 @@ func TestAppImportExport(t *testing.T) { require.NoError(t, err, "simulation setup failed") - prototype := base.NewSimulationApplication(applicationName, moduleBasicManager, wasm.EnableAllProposals, moduleAccountPermissions, tokenReceiveAllowedModules) - simulationApplication := prototype.Initialize(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultHome(), fauxMerkleModeOpt).(*base.SimulationApplication) + prototype := base.NewSimulationApplication(applicationName, moduleBasicManager, wasm.EnableAllProposals, moduleAccountPermissions, tokenReceiveAllowedModules).(*base.SimulationApplication) + simulationApplication := prototype.InitializeSimulationApplication(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultNodeHome(), fauxMerkleModeOpt).(*base.SimulationApplication) require.Equal(t, "SimulationApplication", simulationApplication.Name()) // Run randomized simulation @@ -101,7 +101,7 @@ func TestAppImportExport(t *testing.T) { require.NoError(t, err, "simulation setup failed") - newSimulationApplication := prototype.Initialize(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultHome()).(*base.SimulationApplication) + newSimulationApplication := prototype.Initialize(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultNodeHome()).(*base.SimulationApplication) require.Equal(t, "SimulationApplication", newSimulationApplication.Name()) var genesisState simapp.GenesisState diff --git a/simulation/make/TestAppSimulationAfterImport_test.go b/simulation/make/TestAppSimulationAfterImport_test.go index 747bfcad1..a56e27077 100644 --- a/simulation/make/TestAppSimulationAfterImport_test.go +++ b/simulation/make/TestAppSimulationAfterImport_test.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package make @@ -10,13 +8,13 @@ import ( "os" "testing" - "github.com/persistenceOne/persistenceSDK/schema/applications/base" - "github.com/CosmWasm/wasmd/x/wasm" "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" + + "github.com/AssetMantle/modules/schema/applications/base" ) func TestAppSimulationAfterImport(t *testing.T) { @@ -29,8 +27,8 @@ func TestAppSimulationAfterImport(t *testing.T) { require.NoError(t, err, "simulation setup failed") - prototype := base.NewSimulationApplication(applicationName, moduleBasicManager, wasm.EnableAllProposals, moduleAccountPermissions, tokenReceiveAllowedModules) - simulationApplication := prototype.Initialize(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultHome(), fauxMerkleModeOpt).(*base.SimulationApplication) + prototype := base.NewSimulationApplication(applicationName, moduleBasicManager, wasm.EnableAllProposals, moduleAccountPermissions, tokenReceiveAllowedModules).(*base.SimulationApplication) + simulationApplication := prototype.InitializeSimulationApplication(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultNodeHome(), fauxMerkleModeOpt).(*base.SimulationApplication) require.Equal(t, "SimulationApplication", simulationApplication.Name()) // Run randomized simulation @@ -66,7 +64,7 @@ func TestAppSimulationAfterImport(t *testing.T) { require.NoError(t, err, "simulation setup failed") - newSimulationApplication := prototype.Initialize(logger, newDB, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultHome(), fauxMerkleModeOpt).(*base.SimulationApplication) + newSimulationApplication := prototype.Initialize(logger, newDB, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultNodeHome(), fauxMerkleModeOpt).(*base.SimulationApplication) require.Equal(t, "SimulationApplication", newSimulationApplication.Name()) newSimulationApplication.InitChain(abci.RequestInitChain{ diff --git a/simulation/make/TestAppStateDeterminism_test.go b/simulation/make/TestAppStateDeterminism_test.go index 545998021..ab2018314 100644 --- a/simulation/make/TestAppStateDeterminism_test.go +++ b/simulation/make/TestAppStateDeterminism_test.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package make @@ -13,13 +11,12 @@ import ( "testing" "github.com/CosmWasm/wasmd/x/wasm" - - "github.com/persistenceOne/persistenceSDK/schema/applications/base" - "github.com/cosmos/cosmos-sdk/simapp" + "github.com/AssetMantle/modules/schema/applications/base" + "github.com/cosmos/cosmos-sdk/simapp/helpers" - "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/libs/log" dbm "github.com/tendermint/tm-db" @@ -54,8 +51,8 @@ func TestAppStateDeterminism(t *testing.T) { db := dbm.NewMemDB() - prototype := base.NewSimulationApplication(applicationName, moduleBasicManager, wasm.EnableAllProposals, moduleAccountPermissions, tokenReceiveAllowedModules) - simulationApplication := prototype.Initialize(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultHome(), interBlockCacheOpt()).(*base.SimulationApplication) + prototype := base.NewSimulationApplication(applicationName, moduleBasicManager, wasm.EnableAllProposals, moduleAccountPermissions, tokenReceiveAllowedModules).(*base.SimulationApplication) + simulationApplication := prototype.InitializeSimulationApplication(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultNodeHome(), interBlockCacheOpt()).(*base.SimulationApplication) fmt.Printf( "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n", diff --git a/simulation/make/TestFullAppSimulation_test.go b/simulation/make/TestFullAppSimulation_test.go index 6518e7f43..93f371138 100644 --- a/simulation/make/TestFullAppSimulation_test.go +++ b/simulation/make/TestFullAppSimulation_test.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package make @@ -9,31 +7,34 @@ import ( "os" "testing" - "github.com/persistenceOne/persistenceSDK/schema/applications/base" - "github.com/CosmWasm/wasmd/x/wasm" "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/applications/base" ) func TestFullAppSimulation(t *testing.T) { config, db, _, logger, skip, closeFn, err := setupRun(t, "leveldb-app-sim", "Simulation") defer closeFn() - if skip { t.Skip("skipping application simulation") } require.NoError(t, err, "simulation setup failed") - prototype := base.NewSimulationApplication(applicationName, moduleBasicManager, wasm.EnableAllProposals, moduleAccountPermissions, tokenReceiveAllowedModules) - simulationApplication := prototype.Initialize(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultHome(), fauxMerkleModeOpt).(*base.SimulationApplication) + prototype := base.NewSimulationApplication(applicationName, moduleBasicManager, wasm.EnableAllProposals, moduleAccountPermissions, tokenReceiveAllowedModules).(*base.SimulationApplication) + simulationApplication := prototype.InitializeSimulationApplication(logger, db, nil, true, simapp.FlagPeriodValue, map[int64]bool{}, prototype.GetDefaultNodeHome(), fauxMerkleModeOpt).(*base.SimulationApplication) + require.Equal(t, "SimulationApplication", simulationApplication.Name()) // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, simulationApplication.GetBaseApp(), simapp.AppStateFn(simulationApplication.Codec(), simulationApplication.SimulationManager()), + t, + os.Stdout, + simulationApplication.GetBaseApp(), + simapp.AppStateFn(simulationApplication.Codec(), simulationApplication.SimulationManager()), simapp.SimulationOperations(simulationApplication, simulationApplication.Codec(), config), simulationApplication.ModuleAccountAddrs(), config, ) diff --git a/simulation/make/constants_test.go b/simulation/make/constants_test.go new file mode 100644 index 000000000..3c0064b11 --- /dev/null +++ b/simulation/make/constants_test.go @@ -0,0 +1,72 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package make + +import ( + "github.com/CosmWasm/wasmd/x/wasm" + wasmClient "github.com/CosmWasm/wasmd/x/wasm/client" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/crisis" + "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/evidence" + "github.com/cosmos/cosmos-sdk/x/genutil" + "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/params" + paramsClient "github.com/cosmos/cosmos-sdk/x/params/client" + "github.com/cosmos/cosmos-sdk/x/slashing" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/supply" + "github.com/cosmos/cosmos-sdk/x/upgrade" + upgradeClient "github.com/cosmos/cosmos-sdk/x/upgrade/client" + + "github.com/AssetMantle/modules/modules/assets" + "github.com/AssetMantle/modules/modules/classifications" + "github.com/AssetMantle/modules/modules/identities" + "github.com/AssetMantle/modules/modules/maintainers" + "github.com/AssetMantle/modules/modules/metas" + "github.com/AssetMantle/modules/modules/orders" + "github.com/AssetMantle/modules/modules/splits" +) + +const applicationName = "SimulationApplication" + +var moduleBasicManager = module.NewBasicManager( + genutil.AppModuleBasic{}, + auth.AppModuleBasic{}, + bank.AppModuleBasic{}, + staking.AppModuleBasic{}, + mint.AppModuleBasic{}, + distribution.AppModuleBasic{}, + gov.NewAppModuleBasic(append(wasmClient.ProposalHandlers, paramsClient.ProposalHandler, distribution.ProposalHandler, upgradeClient.ProposalHandler)...), + params.AppModuleBasic{}, + crisis.AppModuleBasic{}, + wasm.AppModuleBasic{}, + slashing.AppModuleBasic{}, + supply.AppModuleBasic{}, + upgrade.AppModuleBasic{}, + evidence.AppModuleBasic{}, + + assets.Prototype(), + classifications.Prototype(), + identities.Prototype(), + maintainers.Prototype(), + metas.Prototype(), + orders.Prototype(), + splits.Prototype(), +) +var moduleAccountPermissions = map[string][]string{ + auth.FeeCollectorName: nil, + distribution.ModuleName: nil, + mint.ModuleName: {supply.Minter}, + staking.BondedPoolName: {supply.Burner, supply.Staking}, + staking.NotBondedPoolName: {supply.Burner, supply.Staking}, + gov.ModuleName: {supply.Burner}, + splits.Prototype().Name(): nil, +} +var tokenReceiveAllowedModules = map[string]bool{ + distribution.ModuleName: true, +} diff --git a/simulation/make/utilities.go b/simulation/make/utilities.go new file mode 100644 index 000000000..2e46cbb5d --- /dev/null +++ b/simulation/make/utilities.go @@ -0,0 +1,53 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package make + +import ( + "os" + + "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/x/simulation" + "github.com/tendermint/tendermint/libs/log" + db "github.com/tendermint/tm-db" +) + +type testingLogging interface { + Error(...interface{}) + Fatal(...interface{}) +} + +func setupRun(t testingLogging, dirPrefix, dbName string) (config simulation.Config, db db.DB, dir string, logger log.Logger, skip bool, closeFn func(), err error) { + closeFn = func() {} + + config, db, dir, logger, skip, err = simapp.SetupSimulation(dirPrefix, dbName) + if err != nil { + return + } + + closeFn = func() { + var gotError bool + + if db != nil { + err = db.Close() + if err != nil { + gotError = true + + t.Error(err) + } + } + + err = os.RemoveAll(dir) + if err != nil { + gotError = true + + t.Error(err) + } + + if gotError { + t.Fatal() + } + } + + return +} diff --git a/simulation/schema/types/base/data.go b/simulation/schema/types/base/data.go new file mode 100644 index 000000000..23f6ae85d --- /dev/null +++ b/simulation/schema/types/base/data.go @@ -0,0 +1,33 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/simulation" + + "github.com/AssetMantle/modules/schema/data" + baseData "github.com/AssetMantle/modules/schema/data/base" + baseTypes "github.com/AssetMantle/modules/schema/types/base" + + "math" + "math/rand" +) + +func GenerateRandomData(r *rand.Rand) data.Data { + randomPositiveInt := int(math.Abs(float64(r.Int()))) + + switch randomPositiveInt % 4 { + case 0: + return baseData.NewIDData(GenerateRandomID(r)) + case 1: + return baseData.NewStringData(simulation.RandStringOfLength(r, r.Intn(99))) + case 2: + return baseData.NewDecData(simulation.RandomDecAmount(r, sdkTypes.NewDec(99))) + case 3: + return baseData.NewHeightData(baseTypes.NewHeight(r.Int63())) + default: + return nil + } +} diff --git a/simulation/schema/types/base/data_test.go b/simulation/schema/types/base/data_test.go new file mode 100644 index 000000000..105be1316 --- /dev/null +++ b/simulation/schema/types/base/data_test.go @@ -0,0 +1,38 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "math/rand" + "reflect" + "testing" +) + +func TestGenerateRandomData(t *testing.T) { + type args struct { + r *rand.Rand + } + tests := []struct { + name string + args args + wantPanic bool + }{ + // TODO: check for nil case + {"+ve case", args{rand.New(rand.NewSource(7))}, false}, + {"nil case", args{nil}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + defer func() { + r := recover() + if (r != nil) != tt.wantPanic { + t.Errorf("GenerateRandomData() recover = %v, wantPanic = %v", r, tt.wantPanic) + } + }() + if got := GenerateRandomData(tt.args.r); reflect.TypeOf(got).String() != "base.idData" { + t.Errorf("GenerateRandomData() = %v, want base.idData", got) + } + }) + } +} diff --git a/simulation/schema/types/base/id.go b/simulation/schema/types/base/id.go new file mode 100644 index 000000000..6d4c24cfc --- /dev/null +++ b/simulation/schema/types/base/id.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "math/rand" + "strconv" + + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/cosmos/cosmos-sdk/x/simulation" + + "github.com/AssetMantle/modules/schema/ids" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" +) + +func GenerateRandomID(r *rand.Rand) ids.ID { + return baseIDs.NewStringID(simulation.RandStringOfLength(r, r.Intn(99))) +} + +func GenerateRandomIDWithDec(r *rand.Rand) ids.ID { + return baseIDs.NewStringID(sdkTypes.MustNewDecFromStr(strconv.FormatInt(r.Int63(), 10)).String()) +} + +func GenerateRandomIDWithInt64(r *rand.Rand) ids.ID { + return baseIDs.NewStringID(strconv.FormatInt(r.Int63(), 10)) +} diff --git a/simulation/schema/types/base/id_test.go b/simulation/schema/types/base/id_test.go new file mode 100644 index 000000000..3695f20ae --- /dev/null +++ b/simulation/schema/types/base/id_test.go @@ -0,0 +1,95 @@ +package base + +import ( + "math/rand" + "reflect" + "testing" +) + +func TestGenerateRandomID(t *testing.T) { + type args struct { + r *rand.Rand + } + tests := []struct { + name string + args args + wantPanic bool + want string + }{ + // TODO: check for nil case + {"test for panic case", args{nil}, true, ""}, + {"test for id type", args{rand.New(rand.NewSource(7))}, false, "base.stringID"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + defer func() { + r := recover() + if (r != nil) != tt.wantPanic { + t.Errorf("GenerateRandomID() recover = %v, wantPanic = %v", r, tt.wantPanic) + } + }() + if got := GenerateRandomID(tt.args.r); !reflect.DeepEqual(reflect.TypeOf(got).String(), tt.want) { + t.Errorf("GenerateRandomID() = %v, want %v", reflect.TypeOf(got).String(), tt.want) + } + }) + } +} + +func TestGenerateRandomIDWithDec(t *testing.T) { + type args struct { + r *rand.Rand + } + tests := []struct { + name string + args args + wantPanic bool + want string + }{ + // TODO: check for nil case + {"test for panic case", args{nil}, true, ""}, + {"test for id type", args{rand.New(rand.NewSource(7))}, false, "base.stringID"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + defer func() { + r := recover() + if (r != nil) != tt.wantPanic { + t.Errorf("GenerateRandomIDWithDec() recover = %v, wantPanic = %v", r, tt.wantPanic) + } + }() + if got := GenerateRandomIDWithDec(tt.args.r); !reflect.DeepEqual(reflect.TypeOf(got).String(), tt.want) { + t.Errorf("GenerateRandomIDWithDec() = %v, want %v", reflect.TypeOf(got).String(), tt.want) + } + }) + } +} + +func TestGenerateRandomIDWithInt64(t *testing.T) { + + type args struct { + r *rand.Rand + } + tests := []struct { + name string + args args + wantPanic bool + want string + }{ + // TODO: check for nil case + {"test for panic case", args{nil}, true, ""}, + {"test for id type", args{rand.New(rand.NewSource(7))}, false, "base.stringID"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + defer func() { + r := recover() + if (r != nil) != tt.wantPanic { + t.Errorf("GenerateRandomIDWithInt64() recover = %v, wantPanic = %v", r, tt.wantPanic) + } + }() + if got := GenerateRandomIDWithInt64(tt.args.r); !reflect.DeepEqual(reflect.TypeOf(got).String(), tt.want) { + t.Errorf("GenerateRandomIDWithInt64() = %v, want %v", reflect.TypeOf(got).String(), got) + } + }) + } +} diff --git a/simulation/schema/types/base/properties.go b/simulation/schema/types/base/properties.go new file mode 100644 index 000000000..4be430db9 --- /dev/null +++ b/simulation/schema/types/base/properties.go @@ -0,0 +1,25 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "math" + "math/rand" + + "github.com/AssetMantle/modules/schema/lists" + baseLists "github.com/AssetMantle/modules/schema/lists/base" + "github.com/AssetMantle/modules/schema/properties" +) + +func GenerateRandomPropertyList(r *rand.Rand) lists.PropertyList { + randomPositiveInt := int(math.Abs(float64(r.Int()))) % 11 + + propertyList := make([]properties.Property, randomPositiveInt) + + for i := 0; i < randomPositiveInt; i++ { + propertyList[i] = GenerateRandomProperty(r) + } + + return baseLists.NewPropertyList(propertyList...) +} diff --git a/simulation/schema/types/base/properties_test.go b/simulation/schema/types/base/properties_test.go new file mode 100644 index 000000000..183d53b0f --- /dev/null +++ b/simulation/schema/types/base/properties_test.go @@ -0,0 +1,37 @@ +package base + +import ( + "math/rand" + "reflect" + "testing" +) + +func TestGenerateRandomProperties(t *testing.T) { + + type args struct { + r *rand.Rand + } + tests := []struct { + name string + args args + wantPanic bool + }{ + // TODO: check for nil case + {"test for panic case", args{nil}, true}, + {"test for type", args{rand.New(rand.NewSource(7))}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + defer func() { + r := recover() + if (r != nil) != tt.wantPanic { + t.Errorf("GenerateRandomPropertyList() recover = %v, wantPanic = %v", r, tt.wantPanic) + } + }() + + if got := GenerateRandomPropertyList(tt.args.r); reflect.TypeOf(got).String() != "base.propertyList" { + t.Errorf("GenerateRandomPropertyList() = %v, want base.propertyList", got) + } + }) + } +} diff --git a/simulation/schema/types/base/property.go b/simulation/schema/types/base/property.go new file mode 100644 index 000000000..381ff0b63 --- /dev/null +++ b/simulation/schema/types/base/property.go @@ -0,0 +1,18 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/x/simulation" + + "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/properties" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" +) + +func GenerateRandomProperty(r *rand.Rand) properties.Property { + return baseProperties.NewMesaProperty(base.NewStringID(simulation.RandStringOfLength(r, r.Intn(99))), GenerateRandomData(r)) +} diff --git a/simulation/schema/types/base/property_test.go b/simulation/schema/types/base/property_test.go new file mode 100644 index 000000000..e96be08c5 --- /dev/null +++ b/simulation/schema/types/base/property_test.go @@ -0,0 +1,36 @@ +package base + +import ( + "math/rand" + "reflect" + "testing" +) + +func TestGenerateRandomProperty(t *testing.T) { + type args struct { + r *rand.Rand + } + tests := []struct { + name string + args args + want string + wantPanic bool + }{ + // TODO: check for nil case + {"test for panic case", args{nil}, "", true}, + {"test for type", args{rand.New(rand.NewSource(7))}, "base.mesaProperty", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + defer func() { + r := recover() + if (r != nil) != tt.wantPanic { + t.Errorf("GenerateRandomProperty() recover = %v, wantPanic = %v", r, tt.wantPanic) + } + }() + if got := GenerateRandomProperty(tt.args.r); !reflect.DeepEqual(reflect.TypeOf(got).String(), tt.want) { + t.Errorf("GenerateRandomProperty() = %v, want %v", reflect.TypeOf(got).String(), tt.want) + } + }) + } +} diff --git a/simulation/utilities.go b/simulation/utilities.go index 72776338f..daf442631 100644 --- a/simulation/utilities.go +++ b/simulation/utilities.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package simulation @@ -9,7 +7,7 @@ import ( "math/rand" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/simulation" ) func RandomBool(r *rand.Rand) bool { diff --git a/simulation/utilities_test.go b/simulation/utilities_test.go new file mode 100644 index 000000000..fa2c134d2 --- /dev/null +++ b/simulation/utilities_test.go @@ -0,0 +1,65 @@ +package simulation + +import ( + "math/rand" + "reflect" + "testing" +) + +func TestGenerateRandomAddresses(t *testing.T) { + + type args struct { + r *rand.Rand + } + tests := []struct { + name string + args args + wantPanic bool + }{ + // TODO: check for nil case + {"type test", args{rand.New(rand.NewSource(7))}, false}, + {"panic case", args{nil}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + defer func() { + r := recover() + if (r != nil) != tt.wantPanic { + t.Errorf("GenerateRandomAddresses() recover = %v, wantPanic = %v", r, tt.wantPanic) + } + }() + if got := GenerateRandomAddresses(tt.args.r); reflect.TypeOf(got).String() != "[]types.AccAddress" { + t.Errorf("GenerateRandomAddresses() = %v, want []types.AccAddress", got) + } + }) + } +} + +func TestRandomBool(t *testing.T) { + + type args struct { + r *rand.Rand + } + tests := []struct { + name string + args args + wantPanic bool + }{ + // TODO: check for nil case + {"test panic case", args{nil}, true}, + {"+ve case", args{rand.New(rand.NewSource(7))}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + defer func() { + r := recover() + if (r != nil) != tt.wantPanic { + t.Errorf("RandomBool() recover = %v, wantPanic = %v", r, tt.wantPanic) + } + }() + if got := RandomBool(tt.args.r); reflect.TypeOf(got).String() != "bool" { + t.Errorf("RandomBool() = %v, want bool", got) + } + }) + } +} diff --git a/swagger/README.md b/swagger/README.md index c0bfc3434..1cf224b9c 100644 --- a/swagger/README.md +++ b/swagger/README.md @@ -1,28 +1,35 @@ # PersistenceSDK Swagger API Documentation ### Pre-requirements -- get the [swag](https://github.com/swaggo/swag) go binary or install from source -```go + +- get the [swag](https://github.com/swaggo/swag) go binary or install from source + +``` go get -u github.com/swaggo/swag/cmd/swag ``` -### Generate Swagger +### Generate Swagger + ```bash go mod vendor cd swagger swag init --parseDependency true --parseInternal true --parseVendor true ``` ->Note: about cmd will take much longer time depends on system. + +> Note: about cmd will take much longer time depends on system. + - generate `/docs` folder. - import `/docs` into `main.go` file to use swagger. -```go - _ "github.com/persistenceOne/persistenceSDK/swagger/docs" + +``` +import _"github.com/AssetMantle/modules/swagger/docs" ``` To know more about swaggo use [this](https://github.com/swaggo/swag) ### Start AssetMantle server in unsafe mode + `assetNode start` `assetClient rest-server --chain-id test --unsafe-cors` diff --git a/swagger/configurations/constants.go b/swagger/configurations/constants.go new file mode 100644 index 000000000..692ce53a7 --- /dev/null +++ b/swagger/configurations/constants.go @@ -0,0 +1,6 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package configurations + +const Name = "AssetMantle" diff --git a/swagger/configurations/modules.go b/swagger/configurations/modules.go index 75b98284f..ed149c32f 100644 --- a/swagger/configurations/modules.go +++ b/swagger/configurations/modules.go @@ -1,15 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + package configurations import ( "github.com/CosmWasm/wasmd/x/wasm" wasmClient "github.com/CosmWasm/wasmd/x/wasm/client" - "github.com/cosmos/cosmos-sdk/std" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/crisis" "github.com/cosmos/cosmos-sdk/x/distribution" - distributionClient "github.com/cosmos/cosmos-sdk/x/distribution/client" "github.com/cosmos/cosmos-sdk/x/evidence" "github.com/cosmos/cosmos-sdk/x/genutil" "github.com/cosmos/cosmos-sdk/x/gov" @@ -18,17 +19,17 @@ import ( paramsClient "github.com/cosmos/cosmos-sdk/x/params/client" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/supply" "github.com/cosmos/cosmos-sdk/x/upgrade" upgradeClient "github.com/cosmos/cosmos-sdk/x/upgrade/client" - "github.com/persistenceOne/persistenceSDK/modules/assets" - "github.com/persistenceOne/persistenceSDK/modules/classifications" - "github.com/persistenceOne/persistenceSDK/modules/identities" - "github.com/persistenceOne/persistenceSDK/modules/maintainers" - "github.com/persistenceOne/persistenceSDK/modules/metas" - "github.com/persistenceOne/persistenceSDK/modules/orders" - "github.com/persistenceOne/persistenceSDK/modules/splits" - "github.com/persistenceOne/persistenceSDK/schema/applications/base/encoding" + "github.com/AssetMantle/modules/modules/assets" + "github.com/AssetMantle/modules/modules/classifications" + "github.com/AssetMantle/modules/modules/identities" + "github.com/AssetMantle/modules/modules/maintainers" + "github.com/AssetMantle/modules/modules/metas" + "github.com/AssetMantle/modules/modules/orders" + "github.com/AssetMantle/modules/modules/splits" ) var ModuleBasicManager = module.NewBasicManager( @@ -38,11 +39,12 @@ var ModuleBasicManager = module.NewBasicManager( staking.AppModuleBasic{}, mint.AppModuleBasic{}, distribution.AppModuleBasic{}, - gov.NewAppModuleBasic(append(wasmClient.ProposalHandlers, paramsClient.ProposalHandler, distributionClient.ProposalHandler, upgradeClient.ProposalHandler, upgradeClient.CancelProposalHandler)...), + gov.NewAppModuleBasic(append(wasmClient.ProposalHandlers, paramsClient.ProposalHandler, distribution.ProposalHandler, upgradeClient.ProposalHandler)...), params.AppModuleBasic{}, crisis.AppModuleBasic{}, wasm.AppModuleBasic{}, slashing.AppModuleBasic{}, + supply.AppModuleBasic{}, upgrade.AppModuleBasic{}, evidence.AppModuleBasic{}, @@ -56,12 +58,3 @@ var ModuleBasicManager = module.NewBasicManager( ) var EnabledWasmProposalTypeList = wasm.EnableAllProposals - -func MakeEncodingConfig() encoding.EncodingConfig { - encodingConfig := encoding.MakeEncodingConfig() - std.RegisterLegacyAminoCodec(encodingConfig.LegacyAmino) - std.RegisterInterfaces(encodingConfig.InterfaceRegistry) - ModuleBasicManager.RegisterLegacyAminoCodec(encodingConfig.LegacyAmino) - ModuleBasicManager.RegisterInterfaces(encodingConfig.InterfaceRegistry) - return encodingConfig -} diff --git a/swagger/configurations/permissions.go b/swagger/configurations/permissions.go index bfb910f29..dcb9c0c06 100644 --- a/swagger/configurations/permissions.go +++ b/swagger/configurations/permissions.go @@ -1,23 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + package configurations import ( - authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" - distributionTypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - govTypes "github.com/cosmos/cosmos-sdk/x/gov/types" - mintTypes "github.com/cosmos/cosmos-sdk/x/mint/types" - stakingTypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/persistenceOne/persistenceSDK/modules/splits" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/distribution" + "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/x/mint" + "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/cosmos-sdk/x/supply" + + "github.com/AssetMantle/modules/modules/splits" ) var ModuleAccountPermissions = map[string][]string{ - authTypes.FeeCollectorName: nil, - distributionTypes.ModuleName: nil, - mintTypes.ModuleName: {authTypes.Minter}, - stakingTypes.BondedPoolName: {authTypes.Burner, authTypes.Staking}, - stakingTypes.NotBondedPoolName: {authTypes.Burner, authTypes.Staking}, - govTypes.ModuleName: {authTypes.Burner}, - splits.Prototype().Name(): nil, + auth.FeeCollectorName: nil, + distribution.ModuleName: nil, + mint.ModuleName: {supply.Minter}, + staking.BondedPoolName: {supply.Burner, supply.Staking}, + staking.NotBondedPoolName: {supply.Burner, supply.Staking}, + gov.ModuleName: {supply.Burner}, + splits.Prototype().Name(): nil, } var TokenReceiveAllowedModules = map[string]bool{ - distributionTypes.ModuleName: true, + distribution.ModuleName: true, } diff --git a/swagger/docs/docs.go b/swagger/docs/docs.go new file mode 100644 index 000000000..b11f8f9ba --- /dev/null +++ b/swagger/docs/docs.go @@ -0,0 +1,2373 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +// Package docs GENERATED BY THE COMMAND ABOVE; DO NOT EDIT +// This file was generated by swaggo/swag +package docs + +import ( + "bytes" + "encoding/json" + "strings" + "text/template" + + "github.com/swaggo/swag" +) + +var doc = `{ + "schemes": {{ marshal .Schemes }}, + "swagger": "2.0", + "info": { + "description": "{{escape .Description}}", + "title": "{{.Title}}", + "contact": {}, + "license": { + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "{{.Version}}" + }, + "host": "{{.Host}}", + "basePath": "{{.BasePath}}", + "paths": { + "/assets/assets/{assetID}": { + "get": { + "description": "Unique identifier of an asset.", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Search for an asset by Asset ID", + "parameters": [ + { + "type": "string", + "description": "Asset ID", + "name": "assetID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful search.", + "schema": { + "$ref": "#/definitions/asset.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error.", + "schema": { + "$ref": "#/definitions/asset.queryResponse" + } + } + } + } + }, + "/assets/burn": { + "post": { + "description": "Transaction for burning an asset. request body", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Burn an asset transaction", + "parameters": [ + { + "description": "Transaction for burning an asset. request body", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/burn.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful transaction.", + "schema": { + "$ref": "#/definitions/burn.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error in the transaction.", + "schema": { + "$ref": "#/definitions/burn.transactionResponse" + } + } + } + } + }, + "/assets/define": { + "post": { + "description": "Define asset with mutable immutable properties", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Define an asset transaction", + "parameters": [ + { + "description": "A transaction to define the asset.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/define.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful transaction.", + "schema": { + "$ref": "#/definitions/define.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error in the transaction.", + "schema": { + "$ref": "#/definitions/define.transactionResponse" + } + } + } + } + }, + "/assets/deputize": { + "post": { + "description": "Deputize asset", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Deputize an asset transaction", + "parameters": [ + { + "description": "request body", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/deputize.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/deputize.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/deputize.transactionResponse" + } + } + } + } + }, + "/assets/mint": { + "post": { + "description": "Mint asset with mutable immutable properties", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Mint an asset transaction", + "parameters": [ + { + "description": "A transaction to mint the asset.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/mint.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/mint.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/mint.transactionResponse" + } + } + } + } + }, + "/assets/mutate": { + "post": { + "description": "Mutate asset", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Mutate an asset transaction", + "parameters": [ + { + "description": "A transaction to mutate an asset.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionResponse" + } + } + } + } + }, + "/assets/renumerate": { + "post": { + "description": "Renumerate asset with mutable immutable properties", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Renumerate an asset transaction", + "parameters": [ + { + "description": "A transaction to renumerate an asset.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/renumerate.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/renumerate.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/renumerate.transactionResponse" + } + } + } + } + }, + "/assets/revoke": { + "post": { + "description": "Revoke asset", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Revoke a maintainer for an asset classification transaction", + "parameters": [ + { + "description": "A transaction to revoke an asset.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/revoke.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/revoke.transactionResponse" + } + }, + "default": { + "description": "Message for unexpected error response.", + "schema": { + "$ref": "#/definitions/revoke.transactionResponse" + } + } + } + } + }, + "/classifications/classifications/{classificationID}": { + "get": { + "description": "Able to query the asset", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Classifications" + ], + "summary": "Search for an identity by identity ID", + "parameters": [ + { + "type": "string", + "description": "Unique identifier of an asset classification.", + "name": "classificationID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful search response.", + "schema": { + "$ref": "#/definitions/classification.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/classification.queryResponse" + } + } + } + } + }, + "/identities/define": { + "post": { + "description": "Define identities with mutable immutable properties", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Define an identity", + "parameters": [ + { + "description": "Deputize identities", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/define.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/define.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/define.transactionResponse" + } + } + } + } + }, + "/identities/deputize": { + "post": { + "description": "A transaction to deputize a maintainer for an identity classification.", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Deputize an identity", + "parameters": [ + { + "description": "Request body to deputize identity", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/deputize.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/deputize.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/deputize.transactionResponse" + } + } + } + } + }, + "/identities/identities/{identityID}": { + "get": { + "description": "Able to query the asset", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Search for an identity by identity ID", + "parameters": [ + { + "type": "string", + "description": "Query identity using identityID", + "name": "identityID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/identity.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/identity.queryResponse" + } + } + } + } + }, + "/identities/issue": { + "post": { + "description": "Issue identities with mutable immutable properties", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Issue an identity", + "parameters": [ + { + "description": "A transaction to issue an identity.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/issue.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/issue.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/issue.transactionResponse" + } + } + } + } + }, + "/identities/mutate": { + "post": { + "description": "Mutate identity properties", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Mutate an identity", + "parameters": [ + { + "description": "Request body to mutate Identity", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionResponse" + } + } + } + } + }, + "/identities/nub": { + "post": { + "description": "A transaction to nub an identity.", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Nub an identity", + "parameters": [ + { + "description": "A transaction to nub a base identity.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/nub.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/nub.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/nub.transactionResponse" + } + } + } + } + }, + "/identities/provision": { + "post": { + "description": "Provision identities", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Provision an identity", + "parameters": [ + { + "description": "Request body for provision identity", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/provision.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/provision.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/provision.transactionResponse" + } + } + } + } + }, + "/identities/quash": { + "post": { + "description": "Quash identity transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Quash identity transaction", + "parameters": [ + { + "description": "Request body for quash identity", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/quash.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/quash.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/quash.transactionResponse" + } + } + } + } + }, + "/identities/revoke": { + "post": { + "description": "Revoke identity transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Revoke identity transaction", + "parameters": [ + { + "description": "Request body for revoke identity", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/revoke.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/revoke.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/revoke.transactionResponse" + } + } + } + } + }, + "/identities/unprovision": { + "post": { + "description": "Unprovision identity transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Unprovision identity transaction", + "parameters": [ + { + "description": "Request body to unprovision identity", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/unprovision.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/unprovision.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/unprovision.transactionResponse" + } + } + } + } + }, + "/maintainers/maintainers/{maintainerID}": { + "get": { + "description": "Able to query the maintainers details", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Maintainers" + ], + "summary": "Search for a maintainer by maintainer ID", + "parameters": [ + { + "type": "string", + "description": "Unique identifier of a maintainer.", + "name": "maintainerID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful query response", + "schema": { + "$ref": "#/definitions/maintainer.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/maintainer.queryResponse" + } + } + } + } + }, + "/metas/metas/{dataID}": { + "get": { + "description": "Able to query the meta data", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Metas" + ], + "summary": "Search for metadata by meta ID", + "parameters": [ + { + "type": "string", + "description": "Unique identifier of metadata value.", + "name": "dataID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful query response", + "schema": { + "$ref": "#/definitions/meta.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/meta.queryResponse" + } + } + } + } + }, + "/metas/reveal": { + "post": { + "description": "Reveal metas transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Metas" + ], + "summary": "Reveal metas transaction", + "parameters": [ + { + "description": "Request body to reveal meta transaction", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/reveal.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/reveal.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/reveal.transactionResponse" + } + } + } + } + }, + "/orders/cancel": { + "post": { + "description": "cancel order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "cancel order transaction", + "parameters": [ + { + "description": "Request body to cancel order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cancel.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/cancel.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/cancel.transactionResponse" + } + } + } + } + }, + "/orders/define": { + "post": { + "description": "Define order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Define order transaction", + "parameters": [ + { + "description": "Request body to define an order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/define.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/define.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/define.transactionResponse" + } + } + } + } + }, + "/orders/deputize": { + "post": { + "description": "Deputize order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Deputize order transaction", + "parameters": [ + { + "description": "Request body to deputize an order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/deputize.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/deputize.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/deputize.transactionResponse" + } + } + } + } + }, + "/orders/immediate": { + "post": { + "description": "Immediate order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Immediate order transaction", + "parameters": [ + { + "description": "Request body for immediate order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/immediate.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/immediate.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/immediate.transactionResponse" + } + } + } + } + }, + "/orders/make": { + "post": { + "description": "Make order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Make order transaction", + "parameters": [ + { + "description": "Request body to make order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/make.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/make.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/make.transactionResponse" + } + } + } + } + }, + "/orders/modify": { + "post": { + "description": "Modify order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Modify order transaction", + "parameters": [ + { + "description": "Request body to modify order transaction", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/modify.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/modify.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/modify.transactionResponse" + } + } + } + } + }, + "/orders/orders/{orderID}": { + "get": { + "description": "Able to query the order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Query order using order id", + "parameters": [ + { + "type": "string", + "description": "order ID", + "name": "orderID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful response", + "schema": { + "$ref": "#/definitions/order.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/order.queryResponse" + } + } + } + } + }, + "/orders/revoke": { + "post": { + "description": "Revoke order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Revoke order transaction", + "parameters": [ + { + "description": "Request body to revoke order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/revoke.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/revoke.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/revoke.transactionResponse" + } + } + } + } + }, + "/orders/take": { + "post": { + "description": "Take order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Take order transaction", + "parameters": [ + { + "description": "Request body to take order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/take.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/take.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/take.transactionResponse" + } + } + } + } + }, + "/ownable/{ownableID}": { + "get": { + "description": "Able to query the asset", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Splits" + ], + "summary": "Query asset using asset id", + "parameters": [ + { + "type": "string", + "description": "ownable ID", + "name": "ownableID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful query response", + "schema": { + "$ref": "#/definitions/ownable.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/ownable.queryResponse" + } + } + } + } + }, + "/splits/send": { + "post": { + "description": "Send split transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Splits" + ], + "summary": "Send split transaction", + "parameters": [ + { + "description": "Request body to send split", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/send.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/send.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/send.transactionResponse" + } + } + } + } + }, + "/splits/splits/{splitID}": { + "get": { + "description": "Able to query the asset", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Splits" + ], + "summary": "Query split using split id", + "parameters": [ + { + "type": "string", + "description": "split ID", + "name": "splitID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful query response", + "schema": { + "$ref": "#/definitions/split.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/split.queryResponse" + } + } + } + } + }, + "/splits/unwrap": { + "post": { + "description": "Unwrap split transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Splits" + ], + "summary": "Unwrap split transaction", + "parameters": [ + { + "description": "Request body to unwrap split", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/unwrap.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/unwrap.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/unwrap.transactionResponse" + } + } + } + } + }, + "/splits/wrap": { + "post": { + "description": "Wrap split transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Splits" + ], + "summary": "Wrap split transaction", + "parameters": [ + { + "description": "Request body to wrap split", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/wrap.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/wrap.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/wrap.transactionResponse" + } + } + } + } + } + }, + "definitions": { + "asset.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "burn.transactionRequest": { + "type": "object", + "properties": { + "assetID": { + "type": "string" + }, + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + } + } + }, + "burn.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "cancel.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "orderID": { + "type": "string" + } + } + }, + "cancel.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "classification.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "define.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "immutableMetaProperties": { + "type": "string" + }, + "immutableProperties": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + } + } + }, + "define.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "deputize.transactionRequest": { + "type": "object", + "properties": { + "addMaintainer": { + "type": "boolean" + }, + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "classificationID": { + "type": "string" + }, + "fromID": { + "type": "string" + }, + "maintainedProperties": { + "type": "string" + }, + "mutateMaintainer": { + "type": "boolean" + }, + "removeMaintainer": { + "type": "boolean" + }, + "toID": { + "type": "string" + } + } + }, + "deputize.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionRequest": { + "type": "object", + "properties": { + "assetID": { + "type": "string" + }, + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + } + } + }, + "github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "identityID": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + } + } + }, + "github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "helpers.Mappable": { + "type": "object" + }, + "identity.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "immediate.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "classificationID": { + "type": "string" + }, + "expiresIn": { + "type": "integer" + }, + "fromID": { + "type": "string" + }, + "immutableMetaProperties": { + "type": "string" + }, + "immutableProperties": { + "type": "string" + }, + "makerOwnableID": { + "type": "string" + }, + "makerOwnableSplit": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + }, + "takerOwnableID": { + "type": "string" + }, + "takerOwnableSplit": { + "type": "string" + } + } + }, + "immediate.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "issue.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "classificationID": { + "type": "string" + }, + "fromID": { + "type": "string" + }, + "immutableMetaProperties": { + "type": "string" + }, + "immutableProperties": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + }, + "to": { + "type": "string" + } + } + }, + "issue.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "maintainer.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "make.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "classificationID": { + "type": "string" + }, + "expiresIn": { + "type": "integer" + }, + "fromID": { + "type": "string" + }, + "immutableMetaProperties": { + "type": "string" + }, + "immutableProperties": { + "type": "string" + }, + "makerOwnableID": { + "type": "string" + }, + "makerOwnableSplit": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + }, + "takerOwnableID": { + "type": "string" + }, + "takerOwnableSplit": { + "type": "string" + } + } + }, + "make.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "meta.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "mint.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "classificationID": { + "type": "string" + }, + "fromID": { + "type": "string" + }, + "immutableMetaProperties": { + "type": "string" + }, + "immutableProperties": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + }, + "toID": { + "type": "string" + } + } + }, + "mint.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "modify.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "expiresIn": { + "type": "integer" + }, + "fromID": { + "type": "string" + }, + "makerOwnableSplit": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + }, + "orderID": { + "type": "string" + }, + "takerOwnableSplit": { + "type": "string" + } + } + }, + "modify.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "nub.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "nubID": { + "type": "string" + } + } + }, + "nub.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "order.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "ownable.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + }, + "value": { + "type": "string" + } + } + }, + "provision.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "identityID": { + "type": "string" + }, + "to": { + "type": "string" + } + } + }, + "provision.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "quash.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "identityID": { + "type": "string" + } + } + }, + "quash.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "renumerate.transactionRequest": { + "type": "object", + "properties": { + "assetID": { + "type": "string" + }, + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + } + } + }, + "renumerate.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "rest.BaseReq": { + "type": "object", + "properties": { + "account_number": { + "type": "integer" + }, + "chain_id": { + "type": "string" + }, + "from": { + "type": "string" + }, + "gas": { + "type": "string" + }, + "gas_adjustment": { + "type": "string" + }, + "memo": { + "type": "string" + }, + "sequence": { + "type": "integer" + }, + "simulate": { + "type": "boolean" + } + } + }, + "reveal.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "data": { + "type": "string" + } + } + }, + "reveal.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "revoke.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "classificationID": { + "type": "string" + }, + "fromID": { + "type": "string" + }, + "toID": { + "type": "string" + } + } + }, + "revoke.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "send.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "ownableID": { + "type": "string" + }, + "toID": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "send.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "split.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "take.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "orderID": { + "type": "string" + }, + "takerOwnableSplit": { + "type": "string" + } + } + }, + "take.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "unprovision.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "identityID": { + "type": "string" + }, + "to": { + "type": "string" + } + } + }, + "unprovision.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "unwrap.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "ownableID": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "unwrap.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "wrap.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "coins": { + "type": "string" + }, + "fromID": { + "type": "string" + } + } + }, + "wrap.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + } + } +}` + +type swaggerInfo struct { + Version string + Host string + BasePath string + Schemes []string + Title string + Description string +} + +// SwaggerInfo holds exported Swagger Info so clients can modify it +var SwaggerInfo = swaggerInfo{ + Version: "0.1.0", + Host: "localhost:1317", + BasePath: "", + Schemes: []string{}, + Title: "Persistence Swagger Documentation", + Description: "API Documentation of Persistence custom modules", +} + +type s struct{} + +func (s *s) ReadDoc() string { + sInfo := SwaggerInfo + sInfo.Description = strings.Replace(sInfo.Description, "\n", "\\n", -1) + + t, err := template.New("swagger_info").Funcs(template.FuncMap{ + "marshal": func(v interface{}) string { + a, _ := json.Marshal(v) + return string(a) + }, + "escape": func(v interface{}) string { + // escape tabs + str := strings.Replace(v.(string), "\t", "\\t", -1) + // replace " with \", and if that results in \\", replace that with \\\" + str = strings.Replace(str, "\"", "\\\"", -1) + return strings.Replace(str, "\\\\\"", "\\\\\\\"", -1) + }, + }).Parse(doc) + if err != nil { + return doc + } + + var tpl bytes.Buffer + if err := t.Execute(&tpl, sInfo); err != nil { + return doc + } + + return tpl.String() +} + +func init() { + swag.Register(swag.Name, &s{}) +} diff --git a/swagger/docs/swagger.json b/swagger/docs/swagger.json index 2e15a0384..66d7328dd 100644 --- a/swagger/docs/swagger.json +++ b/swagger/docs/swagger.json @@ -1,2101 +1,2301 @@ { - "swagger": "2.0", - "info": { - "description": "API Documentation of Persistence custom modules", - "title": "Persistence Swagger Documentation", - "contact": {}, - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "0.1.0" - }, - "host": "localhost:1317", - "paths": { - "/assets/assets/{assetID}": { - "get": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Assets" - ], - "summary": "Query asset using asset id", - "parameters": [ - { - "type": "string", - "description": "Asset ID", - "name": "assetID", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "A succesful query response", - "schema": { - "$ref": "#/definitions/asset.queryResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/asset.queryResponse" - } - } - } - } - }, - "/assets/burn": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Assets" - ], - "summary": "burn asset transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/burn.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/burn.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/burn.transactionResponse" - } - } - } - } - }, - "/assets/define": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Assets" - ], - "summary": "define asset transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/define.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/define.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/define.transactionResponse" - } - } - } - } - }, - "/assets/deputize": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Assets" - ], - "summary": "deputize asset transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/deputize.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/deputize.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/deputize.transactionResponse" - } - } - } - } - }, - "/assets/mint": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Assets" - ], - "summary": "mint asset transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/mint.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/mint.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/mint.transactionResponse" - } - } - } - } - }, - "/assets/mutate": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Assets" - ], - "summary": "mutate asset transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/mutate.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/mutate.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/mutate.transactionResponse" - } - } - } - } - }, - "/assets/renumerate": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Assets" - ], - "summary": "renumerate asset transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/renumerate.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/renumerate.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/renumerate.transactionResponse" - } - } - } - } - }, - "/assets/revoke": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Assets" - ], - "summary": "revoke asset transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/revoke.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/revoke.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/revoke.transactionResponse" - } - } - } - } - }, - "/classifications/classifications/{classificationID}": { - "get": { - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Classifications" - ], - "summary": "Query classification using classification id", - "parameters": [ - { - "type": "string", - "description": "classification ID", - "name": "classificationID", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Sucessful query response", - "schema": { - "$ref": "#/definitions/classification.queryResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/classification.queryResponse" - } - } - } - } - }, - "/identities/define": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Identities" - ], - "summary": "define identities transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/define.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/define.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/define.transactionResponse" - } - } - } - } - }, - "/identities/deputize": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Identities" - ], - "summary": "deputize identities transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/deputize.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/deputize.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/deputize.transactionResponse" - } - } - } - } - }, - "/identities/identities/{identityID}": { - "get": { - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Identities" - ], - "summary": "Query identities using identity id", - "parameters": [ - { - "type": "string", - "description": "identity ID", - "name": "identityID", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "Sucessful query response", - "schema": { - "$ref": "#/definitions/identity.queryResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/identity.queryResponse" - } - } - } - } - }, - "/identities/issue": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Identities" - ], - "summary": "issue identities transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/issue.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/issue.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/issue.transactionResponse" - } - } - } - } - }, - "/identities/nub": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Identities" - ], - "summary": "nub identities transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/nub.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/nub.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/nub.transactionResponse" - } - } - } - } - }, - "/identities/provision": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Identities" - ], - "summary": "provision identities transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/provision.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/provision.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/provision.transactionResponse" - } - } - } - } - }, - "/identities/reveal": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Metas" - ], - "summary": "reveal metas transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/reveal.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/reveal.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/reveal.transactionResponse" - } - } - } - } - }, - "/identities/revoke": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Identities" - ], - "summary": "revoke identity transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/revoke.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/revoke.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/revoke.transactionResponse" - } - } - } - } - }, - "/identities/unprovision": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Identities" - ], - "summary": "unprovision identity transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/unprovision.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/unprovision.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/unprovision.transactionResponse" - } - } - } - } - }, - "/maintainers/maintainers/{maintainerID}": { - "get": { - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Maintainers" - ], - "summary": "Query maintainers using maintainer id", - "parameters": [ - { - "type": "string", - "description": "maintainer ID", - "name": "maintainerID", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "A successful query response", - "schema": { - "$ref": "#/definitions/maintainer.queryResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/maintainer.queryResponse" - } - } - } - } - }, - "/metas/metas/{metaID}": { - "get": { - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Metas" - ], - "summary": "Query meta using meta id", - "parameters": [ - { - "type": "string", - "description": "meta ID", - "name": "metaID", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "A successful query response", - "schema": { - "$ref": "#/definitions/meta.queryResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/meta.queryResponse" - } - } - } - } - }, - "/orders/cancel": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Orders" - ], - "summary": "cancel order transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/cancel.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/cancel.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/cancel.transactionResponse" - } - } - } - } - }, - "/orders/define": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Orders" - ], - "summary": "define order transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/define.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/define.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/define.transactionResponse" - } - } - } - } - }, - "/orders/deputize": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Orders" - ], - "summary": "deputize order transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/deputize.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/deputize.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/deputize.transactionResponse" - } - } - } - } - }, - "/orders/immediate": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Orders" - ], - "summary": "immediate order transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/immediate.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/immediate.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/immediate.transactionResponse" - } - } - } - } - }, - "/orders/make": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Orders" - ], - "summary": "make order transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/make.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/make.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/make.transactionResponse" - } - } - } - } - }, - "/orders/modify": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Orders" - ], - "summary": "modify order transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/modify.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/modify.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/modify.transactionResponse" - } - } - } - } - }, - "/orders/orders/{orderID}": { - "get": { - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Orders" - ], - "summary": "Query order using order id", - "parameters": [ - { - "type": "string", - "description": "order ID", - "name": "orderID", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "A successful query response", - "schema": { - "$ref": "#/definitions/order.queryResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/order.queryResponse" - } - } - } - } - }, - "/orders/revoke": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Orders" - ], - "summary": "revoke order transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/revoke.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/revoke.transactionResponse" - } - }, - "default": { - "description": "error", - "schema": { - "$ref": "#/definitions/revoke.transactionResponse" - } - } - } - } - }, - "/orders/take": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Orders" - ], - "summary": "take order transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/take.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/take.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/take.transactionResponse" - } - } - } - } - }, - "/splits/send": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Splits" - ], - "summary": "send split transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/send.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/send.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/send.transactionResponse" - } - } - } - } - }, - "/splits/splits/{splitID}": { - "get": { - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Splits" - ], - "summary": "Query split using split id", - "parameters": [ - { - "type": "string", - "description": "split ID", - "name": "splitID", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "A successful query response", - "schema": { - "$ref": "#/definitions/split.queryResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/split.queryResponse" - } - } - } - } - }, - "/splits/unwrap": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Splits" - ], - "summary": "unwrap split transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/unwrap.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/unwrap.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/unwrap.transactionResponse" - } - } - } - } - }, - "/splits/wrap": { - "post": { - "consumes": [ - "text/plain" - ], - "produces": [ - "application/json" - ], - "tags": [ - "Splits" - ], - "summary": "wrap split transaction", - "parameters": [ - { - "description": "request body", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/wrap.transactionRequest" - } - } - ], - "responses": { - "200": { - "description": "A successful response.", - "schema": { - "$ref": "#/definitions/wrap.transactionResponse" - } - }, - "default": { - "description": "An unexpected error response.", - "schema": { - "$ref": "#/definitions/wrap.transactionResponse" - } - } - } - } - } - }, - "definitions": { - "asset.queryResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "list": { - "type": "array", - "items": { - "$ref": "#/definitions/helpers.Mappable" - } - }, - "success": { - "type": "boolean" - } - } - }, - "burn.transactionRequest": { - "type": "object", - "properties": { - "assetID": { - "type": "string" - }, - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "fromID": { - "type": "string" - } - } - }, - "burn.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "cancel.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "fromID": { - "type": "string" - }, - "orderID": { - "type": "string" - } - } - }, - "cancel.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "classification.queryResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "list": { - "type": "array", - "items": { - "$ref": "#/definitions/helpers.Mappable" - } - }, - "success": { - "type": "boolean" - } - } - }, - "define.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "fromID": { - "type": "string" - }, - "immutableMetaProperties": { - "type": "string" - }, - "immutableProperties": { - "type": "string" - }, - "mutableMetaProperties": { - "type": "string" - }, - "mutableProperties": { - "type": "string" - } - } - }, - "define.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "deputize.transactionRequest": { - "type": "object", - "properties": { - "addMaintainer": { - "type": "boolean" - }, - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "classificationID": { - "type": "string" - }, - "fromID": { - "type": "string" - }, - "maintainedProperties": { - "type": "string" - }, - "mutateMaintainer": { - "type": "boolean" - }, - "removeMaintainer": { - "type": "boolean" - }, - "toID": { - "type": "string" - } - } - }, - "deputize.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "helpers.Mappable": { - "type": "object" - }, - "identity.queryResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "list": { - "type": "array", - "items": { - "$ref": "#/definitions/helpers.Mappable" - } - }, - "success": { - "type": "boolean" - } - } - }, - "immediate.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "classificationID": { - "type": "string" - }, - "expiresIn": { - "type": "integer" - }, - "fromID": { - "type": "string" - }, - "immutableMetaProperties": { - "type": "string" - }, - "immutableProperties": { - "type": "string" - }, - "makerOwnableID": { - "type": "string" - }, - "makerOwnableSplit": { - "type": "string" - }, - "mutableMetaProperties": { - "type": "string" - }, - "mutableProperties": { - "type": "string" - }, - "takerOwnableID": { - "type": "string" - }, - "takerOwnableSplit": { - "type": "string" - } - } - }, - "immediate.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "issue.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "classificationID": { - "type": "string" - }, - "fromID": { - "type": "string" - }, - "immutableMetaProperties": { - "type": "string" - }, - "immutableProperties": { - "type": "string" - }, - "mutableMetaProperties": { - "type": "string" - }, - "mutableProperties": { - "type": "string" - }, - "to": { - "type": "string" - } - } - }, - "issue.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "maintainer.queryResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "list": { - "type": "array", - "items": { - "$ref": "#/definitions/helpers.Mappable" - } - }, - "success": { - "type": "boolean" - } - } - }, - "make.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "classificationID": { - "type": "string" - }, - "expiresIn": { - "type": "integer" - }, - "fromID": { - "type": "string" - }, - "immutableMetaProperties": { - "type": "string" - }, - "immutableProperties": { - "type": "string" - }, - "makerOwnableID": { - "type": "string" - }, - "makerOwnableSplit": { - "type": "string" - }, - "mutableMetaProperties": { - "type": "string" - }, - "mutableProperties": { - "type": "string" - }, - "takerOwnableID": { - "type": "string" - }, - "takerOwnableSplit": { - "type": "string" - } - } - }, - "make.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "meta.queryResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "list": { - "type": "array", - "items": { - "$ref": "#/definitions/helpers.Mappable" - } - }, - "success": { - "type": "boolean" - } - } - }, - "mint.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "classificationID": { - "type": "string" - }, - "fromID": { - "type": "string" - }, - "immutableMetaProperties": { - "type": "string" - }, - "immutableProperties": { - "type": "string" - }, - "mutableMetaProperties": { - "type": "string" - }, - "mutableProperties": { - "type": "string" - }, - "toID": { - "type": "string" - } - } - }, - "mint.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "modify.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "expiresIn": { - "type": "integer" - }, - "fromID": { - "type": "string" - }, - "makerOwnableSplit": { - "type": "string" - }, - "mutableMetaProperties": { - "type": "string" - }, - "mutableProperties": { - "type": "string" - }, - "orderID": { - "type": "string" - }, - "takerOwnableSplit": { - "type": "string" - } - } - }, - "modify.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "mutate.transactionRequest": { - "type": "object", - "properties": { - "assetID": { - "type": "string" - }, - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "fromID": { - "type": "string" - }, - "mutableMetaProperties": { - "type": "string" - }, - "mutableProperties": { - "type": "string" - } - } - }, - "mutate.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "nub.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "nubID": { - "type": "string" - } - } - }, - "nub.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "order.queryResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "list": { - "type": "array", - "items": { - "$ref": "#/definitions/helpers.Mappable" - } - }, - "success": { - "type": "boolean" - } - } - }, - "provision.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "identityID": { - "type": "string" - }, - "to": { - "type": "string" - } - } - }, - "provision.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "renumerate.transactionRequest": { - "type": "object", - "properties": { - "assetID": { - "type": "string" - }, - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "fromID": { - "type": "string" - } - } - }, - "renumerate.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "rest.BaseReq": { - "type": "object", - "properties": { - "account_number": { - "type": "integer" - }, - "chain_id": { - "type": "string" - }, - "fees": { - "type": "array", - "items": { - "$ref": "#/definitions/types.Coin" - } - }, - "from": { - "type": "string" - }, - "gas": { - "type": "string" - }, - "gas_adjustment": { - "type": "string" - }, - "memo": { - "type": "string" - }, - "sequence": { - "type": "integer" - }, - "simulate": { - "type": "boolean" - } - } - }, - "reveal.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "metaFact": { - "type": "string" - } - } - }, - "reveal.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "revoke.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "classificationID": { - "type": "string" - }, - "fromID": { - "type": "string" - }, - "toID": { - "type": "string" - } - } - }, - "revoke.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "send.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "fromID": { - "type": "string" - }, - "ownableID": { - "type": "string" - }, - "toID": { - "type": "string" - }, - "value": { - "type": "string" - } - } - }, - "send.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "split.queryResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "list": { - "type": "array", - "items": { - "$ref": "#/definitions/helpers.Mappable" - } - }, - "success": { - "type": "boolean" - } - } - }, - "take.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "fromID": { - "type": "string" - }, - "orderID": { - "type": "string" - }, - "takerOwnableSplit": { - "type": "string" - } - } - }, - "take.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "types.Coin": { - "type": "object", - "properties": { - "amount": { - "description": "To allow the use of unsigned integers (see: #1273) a larger refactor will\nneed to be made. So we use signed integers for now with safety measures in\nplace preventing negative values being used.", - "$ref": "#/definitions/types.Int" - }, - "denom": { - "type": "string" - } - } - }, - "types.Int": { - "type": "object" - }, - "unprovision.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "identityID": { - "type": "string" - }, - "to": { - "type": "string" - } - } - }, - "unprovision.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "success": { - "type": "boolean" - } - } - }, - "unwrap.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "fromID": { - "type": "string" - }, - "ownableID": { - "type": "string" - }, - "value": { - "type": "string" - } - } - }, - "unwrap.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "sucess": { - "type": "boolean" - } - } - }, - "wrap.transactionRequest": { - "type": "object", - "properties": { - "baseReq": { - "$ref": "#/definitions/rest.BaseReq" - }, - "coins": { - "type": "string" - }, - "fromID": { - "type": "string" - } - } - }, - "wrap.transactionResponse": { - "type": "object", - "properties": { - "error": { - "type": "string" - }, - "sucess": { - "type": "boolean" - } - } + "swagger": "2.0", + "info": { + "description": "API Documentation of AssetMantle custom modules", + "title": "AssetMantle Modules Swagger Documentation", + "contact": {}, + "license": { + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "0.1.0" + }, + "host": "localhost:1317", + "paths": { + "/assets/assets/{assetID}": { + "get": { + "description": "Unique identifier of an asset.", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Search for an asset by Asset ID", + "parameters": [ + { + "type": "string", + "description": "Asset ID", + "name": "assetID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful search.", + "schema": { + "$ref": "#/definitions/asset.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error.", + "schema": { + "$ref": "#/definitions/asset.queryResponse" + } + } + } + } + }, + "/assets/burn": { + "post": { + "description": "Transaction for burning an asset. request body", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Burn an asset transaction", + "parameters": [ + { + "description": "Transaction for burning an asset. request body", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/burn.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful transaction.", + "schema": { + "$ref": "#/definitions/burn.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error in the transaction.", + "schema": { + "$ref": "#/definitions/burn.transactionResponse" + } + } + } + } + }, + "/assets/define": { + "post": { + "description": "Define asset with mutable immutable properties", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Define an asset transaction", + "parameters": [ + { + "description": "A transaction to define the asset.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/define.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful transaction.", + "schema": { + "$ref": "#/definitions/define.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error in the transaction.", + "schema": { + "$ref": "#/definitions/define.transactionResponse" + } + } + } + } + }, + "/assets/deputize": { + "post": { + "description": "Deputize asset", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Deputize an asset transaction", + "parameters": [ + { + "description": "request body", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/deputize.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/deputize.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/deputize.transactionResponse" + } + } + } + } + }, + "/assets/mint": { + "post": { + "description": "Mint asset with mutable immutable properties", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Mint an asset transaction", + "parameters": [ + { + "description": "A transaction to mint the asset.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/mint.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/mint.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/mint.transactionResponse" + } + } + } + } + }, + "/assets/mutate": { + "post": { + "description": "Mutate asset", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Mutate an asset transaction", + "parameters": [ + { + "description": "A transaction to mutate an asset.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionResponse" + } + } + } + } + }, + "/assets/renumerate": { + "post": { + "description": "Renumerate asset with mutable immutable properties", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Renumerate an asset transaction", + "parameters": [ + { + "description": "A transaction to renumerate an asset.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/renumerate.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/renumerate.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/renumerate.transactionResponse" + } + } + } + } + }, + "/assets/revoke": { + "post": { + "description": "Revoke asset", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Assets" + ], + "summary": "Revoke a maintainer for an asset classification transaction", + "parameters": [ + { + "description": "A transaction to revoke an asset.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/revoke.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/revoke.transactionResponse" + } + }, + "default": { + "description": "Message for unexpected error response.", + "schema": { + "$ref": "#/definitions/revoke.transactionResponse" + } + } + } + } + }, + "/classifications/classifications/{classificationID}": { + "get": { + "description": "Able to query the asset", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Classifications" + ], + "summary": "Search for an identity by identity ID", + "parameters": [ + { + "type": "string", + "description": "Unique identifier of an asset classification.", + "name": "classificationID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful search response.", + "schema": { + "$ref": "#/definitions/classification.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/classification.queryResponse" + } + } + } + } + }, + "/identities/define": { + "post": { + "description": "Define identities with mutable immutable properties", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Define an identity", + "parameters": [ + { + "description": "Deputize identities", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/define.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/define.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/define.transactionResponse" + } + } + } + } + }, + "/identities/deputize": { + "post": { + "description": "A transaction to deputize a maintainer for an identity classification.", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Deputize an identity", + "parameters": [ + { + "description": "Request body to deputize identity", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/deputize.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/deputize.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/deputize.transactionResponse" + } + } + } + } + }, + "/identities/identities/{identityID}": { + "get": { + "description": "Able to query the asset", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Search for an identity by identity ID", + "parameters": [ + { + "type": "string", + "description": "Query identity using identityID", + "name": "identityID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/identity.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/identity.queryResponse" + } + } + } + } + }, + "/identities/issue": { + "post": { + "description": "Issue identities with mutable immutable properties", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Issue an identity", + "parameters": [ + { + "description": "A transaction to issue an identity.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/issue.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/issue.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/issue.transactionResponse" + } + } + } + } + }, + "/identities/mutate": { + "post": { + "description": "Mutate identity properties", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Mutate an identity", + "parameters": [ + { + "description": "Request body to mutate Identity", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionResponse" + } + } + } + } + }, + "/identities/nub": { + "post": { + "description": "A transaction to nub an identity.", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Nub an identity", + "parameters": [ + { + "description": "A transaction to nub a base identity.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/nub.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/nub.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/nub.transactionResponse" + } + } + } + } + }, + "/identities/provision": { + "post": { + "description": "Provision identities", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Provision an identity", + "parameters": [ + { + "description": "Request body for provision identity", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/provision.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/provision.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/provision.transactionResponse" + } + } + } + } + }, + "/identities/quash": { + "post": { + "description": "Quash identity transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Quash identity transaction", + "parameters": [ + { + "description": "Request body for quash identity", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/quash.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/quash.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/quash.transactionResponse" + } + } + } + } + }, + "/identities/revoke": { + "post": { + "description": "Revoke identity transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Revoke identity transaction", + "parameters": [ + { + "description": "Request body for revoke identity", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/revoke.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/revoke.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/revoke.transactionResponse" + } + } + } + } + }, + "/identities/unprovision": { + "post": { + "description": "Unprovision identity transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Identities" + ], + "summary": "Unprovision identity transaction", + "parameters": [ + { + "description": "Request body to unprovision identity", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/unprovision.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/unprovision.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/unprovision.transactionResponse" + } + } + } + } + }, + "/maintainers/maintainers/{maintainerID}": { + "get": { + "description": "Able to query the maintainers details", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Maintainers" + ], + "summary": "Search for a maintainer by maintainer ID", + "parameters": [ + { + "type": "string", + "description": "Unique identifier of a maintainer.", + "name": "maintainerID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful query response", + "schema": { + "$ref": "#/definitions/maintainer.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/maintainer.queryResponse" + } + } + } + } + }, + "/metas/metas/{dataID}": { + "get": { + "description": "Able to query the meta data", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Metas" + ], + "summary": "Search for metadata by meta ID", + "parameters": [ + { + "type": "string", + "description": "Unique identifier of metadata value.", + "name": "dataID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful query response", + "schema": { + "$ref": "#/definitions/meta.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/meta.queryResponse" + } + } + } + } + }, + "/metas/reveal": { + "post": { + "description": "Reveal metas transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Metas" + ], + "summary": "Reveal metas transaction", + "parameters": [ + { + "description": "Request body to reveal meta transaction", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/reveal.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/reveal.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/reveal.transactionResponse" + } + } + } + } + }, + "/orders/cancel": { + "post": { + "description": "cancel order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "cancel order transaction", + "parameters": [ + { + "description": "Request body to cancel order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/cancel.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/cancel.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/cancel.transactionResponse" + } + } + } + } + }, + "/orders/define": { + "post": { + "description": "Define order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Define order transaction", + "parameters": [ + { + "description": "Request body to define an order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/define.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/define.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/define.transactionResponse" + } + } + } + } + }, + "/orders/deputize": { + "post": { + "description": "Deputize order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Deputize order transaction", + "parameters": [ + { + "description": "Request body to deputize an order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/deputize.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/deputize.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/deputize.transactionResponse" + } + } + } + } + }, + "/orders/immediate": { + "post": { + "description": "Immediate order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Immediate order transaction", + "parameters": [ + { + "description": "Request body for immediate order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/immediate.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/immediate.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/immediate.transactionResponse" + } + } + } + } + }, + "/orders/make": { + "post": { + "description": "Make order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Make order transaction", + "parameters": [ + { + "description": "Request body to make order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/make.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/make.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/make.transactionResponse" + } + } + } + } + }, + "/orders/modify": { + "post": { + "description": "Modify order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Modify order transaction", + "parameters": [ + { + "description": "Request body to modify order transaction", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/modify.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/modify.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/modify.transactionResponse" + } + } + } + } + }, + "/orders/orders/{orderID}": { + "get": { + "description": "Able to query the order", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Query order using order id", + "parameters": [ + { + "type": "string", + "description": "order ID", + "name": "orderID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful response", + "schema": { + "$ref": "#/definitions/order.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/order.queryResponse" + } + } + } + } + }, + "/orders/revoke": { + "post": { + "description": "Revoke order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Revoke order transaction", + "parameters": [ + { + "description": "Request body to revoke order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/revoke.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/revoke.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/revoke.transactionResponse" + } + } + } + } + }, + "/orders/take": { + "post": { + "description": "Take order transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Orders" + ], + "summary": "Take order transaction", + "parameters": [ + { + "description": "Request body to take order", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/take.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/take.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/take.transactionResponse" + } + } + } + } + }, + "/ownable/{ownableID}": { + "get": { + "description": "Able to query the asset", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Splits" + ], + "summary": "Query asset using asset id", + "parameters": [ + { + "type": "string", + "description": "ownable ID", + "name": "ownableID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful query response", + "schema": { + "$ref": "#/definitions/ownable.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/ownable.queryResponse" + } + } + } + } + }, + "/splits/send": { + "post": { + "description": "Send split transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Splits" + ], + "summary": "Send split transaction", + "parameters": [ + { + "description": "Request body to send split", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/send.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/send.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/send.transactionResponse" + } + } + } + } + }, + "/splits/splits/{splitID}": { + "get": { + "description": "Able to query the asset", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Splits" + ], + "summary": "Query split using split id", + "parameters": [ + { + "type": "string", + "description": "split ID", + "name": "splitID", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "Message for a successful query response", + "schema": { + "$ref": "#/definitions/split.queryResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/split.queryResponse" + } + } + } + } + }, + "/splits/unwrap": { + "post": { + "description": "Unwrap split transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Splits" + ], + "summary": "Unwrap split transaction", + "parameters": [ + { + "description": "Request body to unwrap split", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/unwrap.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/unwrap.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/unwrap.transactionResponse" + } + } + } + } + }, + "/splits/wrap": { + "post": { + "description": "Wrap split transaction", + "consumes": [ + "text/plain" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Splits" + ], + "summary": "Wrap split transaction", + "parameters": [ + { + "description": "Request body to wrap split", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/wrap.transactionRequest" + } + } + ], + "responses": { + "200": { + "description": "Message for a successful response.", + "schema": { + "$ref": "#/definitions/wrap.transactionResponse" + } + }, + "default": { + "description": "Message for an unexpected error response.", + "schema": { + "$ref": "#/definitions/wrap.transactionResponse" + } + } + } + } + } + }, + "definitions": { + "asset.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "burn.transactionRequest": { + "type": "object", + "properties": { + "assetID": { + "type": "string" + }, + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + } + } + }, + "burn.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "cancel.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "orderID": { + "type": "string" + } + } + }, + "cancel.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "classification.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "define.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "immutableMetaProperties": { + "type": "string" + }, + "immutableProperties": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + } + } + }, + "define.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "deputize.transactionRequest": { + "type": "object", + "properties": { + "addMaintainer": { + "type": "boolean" + }, + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "classificationID": { + "type": "string" + }, + "fromID": { + "type": "string" + }, + "maintainedProperties": { + "type": "string" + }, + "mutateMaintainer": { + "type": "boolean" + }, + "removeMaintainer": { + "type": "boolean" + }, + "toID": { + "type": "string" + } + } + }, + "deputize.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionRequest": { + "type": "object", + "properties": { + "assetID": { + "type": "string" + }, + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + } + } + }, + "github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "identityID": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + } + } + }, + "github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "helpers.Mappable": { + "type": "object" + }, + "identity.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "immediate.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "classificationID": { + "type": "string" + }, + "expiresIn": { + "type": "integer" + }, + "fromID": { + "type": "string" + }, + "immutableMetaProperties": { + "type": "string" + }, + "immutableProperties": { + "type": "string" + }, + "makerOwnableID": { + "type": "string" + }, + "makerOwnableSplit": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + }, + "takerOwnableID": { + "type": "string" + }, + "takerOwnableSplit": { + "type": "string" + } + } + }, + "immediate.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "issue.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "classificationID": { + "type": "string" + }, + "fromID": { + "type": "string" + }, + "immutableMetaProperties": { + "type": "string" + }, + "immutableProperties": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + }, + "to": { + "type": "string" + } + } + }, + "issue.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "maintainer.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "make.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "classificationID": { + "type": "string" + }, + "expiresIn": { + "type": "integer" + }, + "fromID": { + "type": "string" + }, + "immutableMetaProperties": { + "type": "string" + }, + "immutableProperties": { + "type": "string" + }, + "makerOwnableID": { + "type": "string" + }, + "makerOwnableSplit": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + }, + "takerOwnableID": { + "type": "string" + }, + "takerOwnableSplit": { + "type": "string" + } + } + }, + "make.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "meta.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "mint.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "classificationID": { + "type": "string" + }, + "fromID": { + "type": "string" + }, + "immutableMetaProperties": { + "type": "string" + }, + "immutableProperties": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + }, + "toID": { + "type": "string" + } + } + }, + "mint.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "modify.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "expiresIn": { + "type": "integer" + }, + "fromID": { + "type": "string" + }, + "makerOwnableSplit": { + "type": "string" + }, + "mutableMetaProperties": { + "type": "string" + }, + "mutableProperties": { + "type": "string" + }, + "orderID": { + "type": "string" + }, + "takerOwnableSplit": { + "type": "string" + } + } + }, + "modify.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "nub.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "nubID": { + "type": "string" + } + } + }, + "nub.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "order.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "ownable.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + }, + "value": { + "type": "string" + } + } + }, + "provision.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "identityID": { + "type": "string" + }, + "to": { + "type": "string" + } + } + }, + "provision.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "quash.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "identityID": { + "type": "string" + } + } + }, + "quash.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "renumerate.transactionRequest": { + "type": "object", + "properties": { + "assetID": { + "type": "string" + }, + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + } + } + }, + "renumerate.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "rest.BaseReq": { + "type": "object", + "properties": { + "account_number": { + "type": "integer" + }, + "chain_id": { + "type": "string" + }, + "from": { + "type": "string" + }, + "gas": { + "type": "string" + }, + "gas_adjustment": { + "type": "string" + }, + "memo": { + "type": "string" + }, + "sequence": { + "type": "integer" + }, + "simulate": { + "type": "boolean" + } + } + }, + "reveal.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "data": { + "type": "string" + } + } + }, + "reveal.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "revoke.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "classificationID": { + "type": "string" + }, + "fromID": { + "type": "string" + }, + "toID": { + "type": "string" + } + } + }, + "revoke.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "send.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "ownableID": { + "type": "string" + }, + "toID": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "send.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "split.queryResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "list": { + "type": "array", + "items": { + "$ref": "#/definitions/helpers.Mappable" + } + }, + "success": { + "type": "boolean" + } + } + }, + "take.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "orderID": { + "type": "string" + }, + "takerOwnableSplit": { + "type": "string" + } + } + }, + "take.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "unprovision.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "identityID": { + "type": "string" + }, + "to": { + "type": "string" + } + } + }, + "unprovision.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "unwrap.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "fromID": { + "type": "string" + }, + "ownableID": { + "type": "string" + }, + "value": { + "type": "string" + } + } + }, + "unwrap.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" + } + } + }, + "wrap.transactionRequest": { + "type": "object", + "properties": { + "baseReq": { + "$ref": "#/definitions/rest.BaseReq" + }, + "coins": { + "type": "string" + }, + "fromID": { + "type": "string" + } + } + }, + "wrap.transactionResponse": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "success": { + "type": "boolean" } + } } + } } \ No newline at end of file diff --git a/swagger/docs/swagger.yaml b/swagger/docs/swagger.yaml new file mode 100644 index 000000000..4e5f4be9b --- /dev/null +++ b/swagger/docs/swagger.yaml @@ -0,0 +1,1495 @@ +definitions: + asset.queryResponse: + properties: + error: + type: string + list: + items: + $ref: '#/definitions/helpers.Mappable' + type: array + success: + type: boolean + type: object + burn.transactionRequest: + properties: + assetID: + type: string + baseReq: + $ref: '#/definitions/rest.BaseReq' + fromID: + type: string + type: object + burn.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + cancel.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + fromID: + type: string + orderID: + type: string + type: object + cancel.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + classification.queryResponse: + properties: + error: + type: string + list: + items: + $ref: '#/definitions/helpers.Mappable' + type: array + success: + type: boolean + type: object + define.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + fromID: + type: string + immutableMetaProperties: + type: string + immutableProperties: + type: string + mutableMetaProperties: + type: string + mutableProperties: + type: string + type: object + define.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + deputize.transactionRequest: + properties: + addMaintainer: + type: boolean + baseReq: + $ref: '#/definitions/rest.BaseReq' + classificationID: + type: string + fromID: + type: string + maintainedProperties: + type: string + mutateMaintainer: + type: boolean + removeMaintainer: + type: boolean + toID: + type: string + type: object + deputize.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionRequest: + properties: + assetID: + type: string + baseReq: + $ref: '#/definitions/rest.BaseReq' + fromID: + type: string + mutableMetaProperties: + type: string + mutableProperties: + type: string + type: object + github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + fromID: + type: string + identityID: + type: string + mutableMetaProperties: + type: string + mutableProperties: + type: string + type: object + github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + helpers.Mappable: + type: object + identity.queryResponse: + properties: + error: + type: string + list: + items: + $ref: '#/definitions/helpers.Mappable' + type: array + success: + type: boolean + type: object + immediate.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + classificationID: + type: string + expiresIn: + type: integer + fromID: + type: string + immutableMetaProperties: + type: string + immutableProperties: + type: string + makerOwnableID: + type: string + makerOwnableSplit: + type: string + mutableMetaProperties: + type: string + mutableProperties: + type: string + takerOwnableID: + type: string + takerOwnableSplit: + type: string + type: object + immediate.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + issue.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + classificationID: + type: string + fromID: + type: string + immutableMetaProperties: + type: string + immutableProperties: + type: string + mutableMetaProperties: + type: string + mutableProperties: + type: string + to: + type: string + type: object + issue.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + maintainer.queryResponse: + properties: + error: + type: string + list: + items: + $ref: '#/definitions/helpers.Mappable' + type: array + success: + type: boolean + type: object + make.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + classificationID: + type: string + expiresIn: + type: integer + fromID: + type: string + immutableMetaProperties: + type: string + immutableProperties: + type: string + makerOwnableID: + type: string + makerOwnableSplit: + type: string + mutableMetaProperties: + type: string + mutableProperties: + type: string + takerOwnableID: + type: string + takerOwnableSplit: + type: string + type: object + make.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + meta.queryResponse: + properties: + error: + type: string + list: + items: + $ref: '#/definitions/helpers.Mappable' + type: array + success: + type: boolean + type: object + mint.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + classificationID: + type: string + fromID: + type: string + immutableMetaProperties: + type: string + immutableProperties: + type: string + mutableMetaProperties: + type: string + mutableProperties: + type: string + toID: + type: string + type: object + mint.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + modify.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + expiresIn: + type: integer + fromID: + type: string + makerOwnableSplit: + type: string + mutableMetaProperties: + type: string + mutableProperties: + type: string + orderID: + type: string + takerOwnableSplit: + type: string + type: object + modify.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + nub.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + nubID: + type: string + type: object + nub.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + order.queryResponse: + properties: + error: + type: string + list: + items: + $ref: '#/definitions/helpers.Mappable' + type: array + success: + type: boolean + type: object + ownable.queryResponse: + properties: + error: + type: string + success: + type: boolean + value: + type: string + type: object + provision.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + identityID: + type: string + to: + type: string + type: object + provision.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + quash.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + fromID: + type: string + identityID: + type: string + type: object + quash.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + renumerate.transactionRequest: + properties: + assetID: + type: string + baseReq: + $ref: '#/definitions/rest.BaseReq' + fromID: + type: string + type: object + renumerate.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + rest.BaseReq: + properties: + account_number: + type: integer + chain_id: + type: string + from: + type: string + gas: + type: string + gas_adjustment: + type: string + memo: + type: string + sequence: + type: integer + simulate: + type: boolean + type: object + reveal.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + data: + type: string + type: object + reveal.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + revoke.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + classificationID: + type: string + fromID: + type: string + toID: + type: string + type: object + revoke.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + send.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + fromID: + type: string + ownableID: + type: string + toID: + type: string + value: + type: string + type: object + send.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + split.queryResponse: + properties: + error: + type: string + list: + items: + $ref: '#/definitions/helpers.Mappable' + type: array + success: + type: boolean + type: object + take.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + fromID: + type: string + orderID: + type: string + takerOwnableSplit: + type: string + type: object + take.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + unprovision.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + identityID: + type: string + to: + type: string + type: object + unprovision.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + unwrap.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + fromID: + type: string + ownableID: + type: string + value: + type: string + type: object + unwrap.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object + wrap.transactionRequest: + properties: + baseReq: + $ref: '#/definitions/rest.BaseReq' + coins: + type: string + fromID: + type: string + type: object + wrap.transactionResponse: + properties: + error: + type: string + success: + type: boolean + type: object +host: localhost:1317 +info: + contact: { } + description: API Documentation of Persistence custom modules + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: Persistence Swagger Documentation + version: 0.1.0 +paths: + /assets/assets/{assetID}: + get: + consumes: + - text/plain + description: Unique identifier of an asset. + parameters: + - description: Asset ID + in: path + name: assetID + required: true + type: string + produces: + - application/json + responses: + "200": + description: Message for a successful search. + schema: + $ref: '#/definitions/asset.queryResponse' + default: + description: Message for an unexpected error. + schema: + $ref: '#/definitions/asset.queryResponse' + summary: Search for an asset by Asset ID + tags: + - Assets + /assets/burn: + post: + consumes: + - text/plain + description: Transaction for burning an asset. request body + parameters: + - description: Transaction for burning an asset. request body + in: body + name: body + required: true + schema: + $ref: '#/definitions/burn.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful transaction. + schema: + $ref: '#/definitions/burn.transactionResponse' + default: + description: Message for an unexpected error in the transaction. + schema: + $ref: '#/definitions/burn.transactionResponse' + summary: Burn an asset transaction + tags: + - Assets + /assets/define: + post: + consumes: + - text/plain + description: Define asset with mutable immutable properties + parameters: + - description: A transaction to define the asset. + in: body + name: body + required: true + schema: + $ref: '#/definitions/define.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful transaction. + schema: + $ref: '#/definitions/define.transactionResponse' + default: + description: Message for an unexpected error in the transaction. + schema: + $ref: '#/definitions/define.transactionResponse' + summary: Define an asset transaction + tags: + - Assets + /assets/deputize: + post: + consumes: + - text/plain + description: Deputize asset + parameters: + - description: request body + in: body + name: body + required: true + schema: + $ref: '#/definitions/deputize.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/deputize.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/deputize.transactionResponse' + summary: Deputize an asset transaction + tags: + - Assets + /assets/mint: + post: + consumes: + - text/plain + description: Mint asset with mutable immutable properties + parameters: + - description: A transaction to mint the asset. + in: body + name: body + required: true + schema: + $ref: '#/definitions/mint.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/mint.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/mint.transactionResponse' + summary: Mint an asset transaction + tags: + - Assets + /assets/mutate: + post: + consumes: + - text/plain + description: Mutate asset + parameters: + - description: A transaction to mutate an asset. + in: body + name: body + required: true + schema: + $ref: '#/definitions/github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/github.com_persistenceOne_persistenceSDK_modules_assets_internal_transactions_mutate.transactionResponse' + summary: Mutate an asset transaction + tags: + - Assets + /assets/renumerate: + post: + consumes: + - text/plain + description: Renumerate asset with mutable immutable properties + parameters: + - description: A transaction to renumerate an asset. + in: body + name: body + required: true + schema: + $ref: '#/definitions/renumerate.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/renumerate.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/renumerate.transactionResponse' + summary: Renumerate an asset transaction + tags: + - Assets + /assets/revoke: + post: + consumes: + - text/plain + description: Revoke asset + parameters: + - description: A transaction to revoke an asset. + in: body + name: body + required: true + schema: + $ref: '#/definitions/revoke.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/revoke.transactionResponse' + default: + description: Message for unexpected error response. + schema: + $ref: '#/definitions/revoke.transactionResponse' + summary: Revoke a maintainer for an asset classification transaction + tags: + - Assets + /classifications/classifications/{classificationID}: + get: + consumes: + - application/json + description: Able to query the asset + parameters: + - description: Unique identifier of an asset classification. + in: path + name: classificationID + required: true + type: string + produces: + - application/json + responses: + "200": + description: Message for a successful search response. + schema: + $ref: '#/definitions/classification.queryResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/classification.queryResponse' + summary: Search for an identity by identity ID + tags: + - Classifications + /identities/define: + post: + consumes: + - text/plain + description: Define identities with mutable immutable properties + parameters: + - description: Deputize identities + in: body + name: body + required: true + schema: + $ref: '#/definitions/define.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/define.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/define.transactionResponse' + summary: Define an identity + tags: + - Identities + /identities/deputize: + post: + consumes: + - text/plain + description: A transaction to deputize a maintainer for an identity classification. + parameters: + - description: Request body to deputize identity + in: body + name: body + required: true + schema: + $ref: '#/definitions/deputize.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/deputize.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/deputize.transactionResponse' + summary: Deputize an identity + tags: + - Identities + /identities/identities/{identityID}: + get: + consumes: + - application/json + description: Able to query the asset + parameters: + - description: Query identity using identityID + in: path + name: identityID + required: true + type: string + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/identity.queryResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/identity.queryResponse' + summary: Search for an identity by identity ID + tags: + - Identities + /identities/issue: + post: + consumes: + - text/plain + description: Issue identities with mutable immutable properties + parameters: + - description: A transaction to issue an identity. + in: body + name: body + required: true + schema: + $ref: '#/definitions/issue.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/issue.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/issue.transactionResponse' + summary: Issue an identity + tags: + - Identities + /identities/mutate: + post: + consumes: + - text/plain + description: Mutate identity properties + parameters: + - description: Request body to mutate Identity + in: body + name: body + required: true + schema: + $ref: '#/definitions/github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/github.com_persistenceOne_persistenceSDK_modules_identities_internal_transactions_mutate.transactionResponse' + summary: Mutate an identity + tags: + - Identities + /identities/nub: + post: + consumes: + - text/plain + description: A transaction to nub an identity. + parameters: + - description: A transaction to nub a base identity. + in: body + name: body + required: true + schema: + $ref: '#/definitions/nub.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/nub.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/nub.transactionResponse' + summary: Nub an identity + tags: + - Identities + /identities/provision: + post: + consumes: + - text/plain + description: Provision identities + parameters: + - description: Request body for provision identity + in: body + name: body + required: true + schema: + $ref: '#/definitions/provision.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/provision.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/provision.transactionResponse' + summary: Provision an identity + tags: + - Identities + /identities/quash: + post: + consumes: + - text/plain + description: Quash identity transaction + parameters: + - description: Request body for quash identity + in: body + name: body + required: true + schema: + $ref: '#/definitions/quash.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/quash.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/quash.transactionResponse' + summary: Quash identity transaction + tags: + - Identities + /identities/revoke: + post: + consumes: + - text/plain + description: Revoke identity transaction + parameters: + - description: Request body for revoke identity + in: body + name: body + required: true + schema: + $ref: '#/definitions/revoke.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/revoke.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/revoke.transactionResponse' + summary: Revoke identity transaction + tags: + - Identities + /identities/unprovision: + post: + consumes: + - text/plain + description: Unprovision identity transaction + parameters: + - description: Request body to unprovision identity + in: body + name: body + required: true + schema: + $ref: '#/definitions/unprovision.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/unprovision.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/unprovision.transactionResponse' + summary: Unprovision identity transaction + tags: + - Identities + /maintainers/maintainers/{maintainerID}: + get: + consumes: + - application/json + description: Able to query the maintainers details + parameters: + - description: Unique identifier of a maintainer. + in: path + name: maintainerID + required: true + type: string + produces: + - application/json + responses: + "200": + description: Message for a successful query response + schema: + $ref: '#/definitions/maintainer.queryResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/maintainer.queryResponse' + summary: Search for a maintainer by maintainer ID + tags: + - Maintainers + /metas/metas/{dataID}: + get: + consumes: + - application/json + description: Able to query the meta data + parameters: + - description: Unique identifier of metadata value. + in: path + name: dataID + required: true + type: string + produces: + - application/json + responses: + "200": + description: Message for a successful query response + schema: + $ref: '#/definitions/meta.queryResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/meta.queryResponse' + summary: Search for metadata by meta ID + tags: + - Metas + /metas/reveal: + post: + consumes: + - text/plain + description: Reveal metas transaction + parameters: + - description: Request body to reveal meta transaction + in: body + name: body + required: true + schema: + $ref: '#/definitions/reveal.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/reveal.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/reveal.transactionResponse' + summary: Reveal metas transaction + tags: + - Metas + /orders/cancel: + post: + consumes: + - text/plain + description: cancel order transaction + parameters: + - description: Request body to cancel order + in: body + name: body + required: true + schema: + $ref: '#/definitions/cancel.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/cancel.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/cancel.transactionResponse' + summary: cancel order transaction + tags: + - Orders + /orders/define: + post: + consumes: + - text/plain + description: Define order transaction + parameters: + - description: Request body to define an order + in: body + name: body + required: true + schema: + $ref: '#/definitions/define.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/define.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/define.transactionResponse' + summary: Define order transaction + tags: + - Orders + /orders/deputize: + post: + consumes: + - text/plain + description: Deputize order transaction + parameters: + - description: Request body to deputize an order + in: body + name: body + required: true + schema: + $ref: '#/definitions/deputize.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/deputize.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/deputize.transactionResponse' + summary: Deputize order transaction + tags: + - Orders + /orders/immediate: + post: + consumes: + - text/plain + description: Immediate order transaction + parameters: + - description: Request body for immediate order + in: body + name: body + required: true + schema: + $ref: '#/definitions/immediate.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/immediate.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/immediate.transactionResponse' + summary: Immediate order transaction + tags: + - Orders + /orders/make: + post: + consumes: + - text/plain + description: Make order transaction + parameters: + - description: Request body to make order + in: body + name: body + required: true + schema: + $ref: '#/definitions/make.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/make.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/make.transactionResponse' + summary: Make order transaction + tags: + - Orders + /orders/modify: + post: + consumes: + - text/plain + description: Modify order transaction + parameters: + - description: Request body to modify order transaction + in: body + name: body + required: true + schema: + $ref: '#/definitions/modify.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/modify.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/modify.transactionResponse' + summary: Modify order transaction + tags: + - Orders + /orders/orders/{orderID}: + get: + consumes: + - application/json + description: Able to query the order + parameters: + - description: order ID + in: path + name: orderID + required: true + type: string + produces: + - application/json + responses: + "200": + description: Message for a successful response + schema: + $ref: '#/definitions/order.queryResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/order.queryResponse' + summary: Query order using order id + tags: + - Orders + /orders/revoke: + post: + consumes: + - text/plain + description: Revoke order transaction + parameters: + - description: Request body to revoke order + in: body + name: body + required: true + schema: + $ref: '#/definitions/revoke.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/revoke.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/revoke.transactionResponse' + summary: Revoke order transaction + tags: + - Orders + /orders/take: + post: + consumes: + - text/plain + description: Take order transaction + parameters: + - description: Request body to take order + in: body + name: body + required: true + schema: + $ref: '#/definitions/take.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/take.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/take.transactionResponse' + summary: Take order transaction + tags: + - Orders + /ownable/{ownableID}: + get: + consumes: + - application/json + description: Able to query the asset + parameters: + - description: ownable ID + in: path + name: ownableID + required: true + type: string + produces: + - application/json + responses: + "200": + description: Message for a successful query response + schema: + $ref: '#/definitions/ownable.queryResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/ownable.queryResponse' + summary: Query asset using asset id + tags: + - Splits + /splits/send: + post: + consumes: + - text/plain + description: Send split transaction + parameters: + - description: Request body to send split + in: body + name: body + required: true + schema: + $ref: '#/definitions/send.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/send.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/send.transactionResponse' + summary: Send split transaction + tags: + - Splits + /splits/splits/{splitID}: + get: + consumes: + - application/json + description: Able to query the asset + parameters: + - description: split ID + in: path + name: splitID + required: true + type: string + produces: + - application/json + responses: + "200": + description: Message for a successful query response + schema: + $ref: '#/definitions/split.queryResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/split.queryResponse' + summary: Query split using split id + tags: + - Splits + /splits/unwrap: + post: + consumes: + - text/plain + description: Unwrap split transaction + parameters: + - description: Request body to unwrap split + in: body + name: body + required: true + schema: + $ref: '#/definitions/unwrap.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/unwrap.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/unwrap.transactionResponse' + summary: Unwrap split transaction + tags: + - Splits + /splits/wrap: + post: + consumes: + - text/plain + description: Wrap split transaction + parameters: + - description: Request body to wrap split + in: body + name: body + required: true + schema: + $ref: '#/definitions/wrap.transactionRequest' + produces: + - application/json + responses: + "200": + description: Message for a successful response. + schema: + $ref: '#/definitions/wrap.transactionResponse' + default: + description: Message for an unexpected error response. + schema: + $ref: '#/definitions/wrap.transactionResponse' + summary: Wrap split transaction + tags: + - Splits +swagger: "2.0" diff --git a/swagger/main.go b/swagger/main.go index da2e56a34..bbe95868e 100644 --- a/swagger/main.go +++ b/swagger/main.go @@ -1,16 +1,19 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + package main import ( - "github.com/cosmos/cosmos-sdk/client" "log" "net/http" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/gorilla/mux" - "github.com/persistenceOne/persistenceSDK/schema/applications/base" - "github.com/persistenceOne/persistenceSDK/swagger/configurations" + "github.com/AssetMantle/modules/schema/applications/base" + "github.com/AssetMantle/modules/swagger/configurations" - _ "github.com/persistenceOne/persistenceSDK/swagger/docs" + _ "github.com/AssetMantle/modules/swagger/docs" httpSwagger "github.com/swaggo/http-swagger" ) @@ -18,14 +21,14 @@ import ( var Prototype = base.NewApplication( configurations.Name, configurations.ModuleBasicManager, - configurations.MakeEncodingConfig(), configurations.EnabledWasmProposalTypeList, configurations.ModuleAccountPermissions, + configurations.TokenReceiveAllowedModules, ) -// @title Persistence Swagger Documentation +// @title AssetMantle Modules Swagger Documentation // @version 0.1.0 -// @description API Documentation of Persistence custom modules +// @description API Documentation of AssetMantle custom modules // @host localhost:1317 // @license.name Apache 2.0 @@ -33,7 +36,7 @@ var Prototype = base.NewApplication( func main() { r := mux.NewRouter() - ctx := client.Context{} + ctx := context.NewCLIContext() Prototype.GetModuleBasicManager().RegisterRESTRoutes(ctx, r) r.PathPrefix("/swagger").Handler(httpSwagger.WrapHandler) log.Println("listen on :1318") diff --git a/thirdParty/proto/confio/proofs.proto b/thirdParty/proto/confio/proofs.proto deleted file mode 100644 index da43503ec..000000000 --- a/thirdParty/proto/confio/proofs.proto +++ /dev/null @@ -1,234 +0,0 @@ -syntax = "proto3"; - -package ics23; -option go_package = "github.com/confio/ics23/go"; - -enum HashOp { - // NO_HASH is the default if no data passed. Note this is an illegal argument some places. - NO_HASH = 0; - SHA256 = 1; - SHA512 = 2; - KECCAK = 3; - RIPEMD160 = 4; - BITCOIN = 5; // ripemd160(sha256(x)) -} - -/** -LengthOp defines how to process the key and value of the LeafOp -to include length information. After encoding the length with the given -algorithm, the length will be prepended to the key and value bytes. -(Each one with it's own encoded length) -*/ -enum LengthOp { - // NO_PREFIX don't include any length info - NO_PREFIX = 0; - // VAR_PROTO uses protobuf (and go-amino) varint encoding of the length - VAR_PROTO = 1; - // VAR_RLP uses rlp int encoding of the length - VAR_RLP = 2; - // FIXED32_BIG uses big-endian encoding of the length as a 32 bit integer - FIXED32_BIG = 3; - // FIXED32_LITTLE uses little-endian encoding of the length as a 32 bit integer - FIXED32_LITTLE = 4; - // FIXED64_BIG uses big-endian encoding of the length as a 64 bit integer - FIXED64_BIG = 5; - // FIXED64_LITTLE uses little-endian encoding of the length as a 64 bit integer - FIXED64_LITTLE = 6; - // REQUIRE_32_BYTES is like NONE, but will fail if the input is not exactly 32 bytes (sha256 output) - REQUIRE_32_BYTES = 7; - // REQUIRE_64_BYTES is like NONE, but will fail if the input is not exactly 64 bytes (sha512 output) - REQUIRE_64_BYTES = 8; -} - -/** -ExistenceProof takes a key and a value and a set of steps to perform on it. -The result of peforming all these steps will provide a "root hash", which can -be compared to the value in a header. - -Since it is computationally infeasible to produce a hash collission for any of the used -cryptographic hash functions, if someone can provide a series of operations to transform -a given key and value into a root hash that matches some trusted root, these key and values -must be in the referenced merkle tree. - -The only possible issue is maliablity in LeafOp, such as providing extra prefix data, -which should be controlled by a spec. Eg. with lengthOp as NONE, - prefix = FOO, key = BAR, value = CHOICE -and - prefix = F, key = OOBAR, value = CHOICE -would produce the same value. - -With LengthOp this is tricker but not impossible. Which is why the "leafPrefixEqual" field -in the ProofSpec is valuable to prevent this mutability. And why all trees should -length-prefix the data before hashing it. -*/ -message ExistenceProof { - bytes key = 1; - bytes value = 2; - LeafOp leaf = 3; - repeated InnerOp path = 4; -} - -/* -NonExistenceProof takes a proof of two neighbors, one left of the desired key, -one right of the desired key. If both proofs are valid AND they are neighbors, -then there is no valid proof for the given key. -*/ -message NonExistenceProof { - bytes key = 1; // TODO: remove this as unnecessary??? we prove a range - ExistenceProof left = 2; - ExistenceProof right = 3; -} - -/* -CommitmentProof is either an ExistenceProof or a NonExistenceProof, or a Batch of such messages -*/ -message CommitmentProof { - oneof proof { - ExistenceProof exist = 1; - NonExistenceProof nonexist = 2; - BatchProof batch = 3; - CompressedBatchProof compressed = 4; - } -} - -/** -LeafOp represents the raw key-value data we wish to prove, and -must be flexible to represent the internal transformation from -the original key-value pairs into the basis hash, for many existing -merkle trees. - -key and value are passed in. So that the signature of this operation is: - leafOp(key, value) -> output - -To process this, first prehash the keys and values if needed (ANY means no hash in this case): - hkey = prehashKey(key) - hvalue = prehashValue(value) - -Then combine the bytes, and hash it - output = hash(prefix || length(hkey) || hkey || length(hvalue) || hvalue) -*/ -message LeafOp { - HashOp hash = 1; - HashOp prehash_key = 2; - HashOp prehash_value = 3; - LengthOp length = 4; - // prefix is a fixed bytes that may optionally be included at the beginning to differentiate - // a leaf node from an inner node. - bytes prefix = 5; -} - -/** -InnerOp represents a merkle-proof step that is not a leaf. -It represents concatenating two children and hashing them to provide the next result. - -The result of the previous step is passed in, so the signature of this op is: - innerOp(child) -> output - -The result of applying InnerOp should be: - output = op.hash(op.prefix || child || op.suffix) - - where the || operator is concatenation of binary data, -and child is the result of hashing all the tree below this step. - -Any special data, like prepending child with the length, or prepending the entire operation with -some value to differentiate from leaf nodes, should be included in prefix and suffix. -If either of prefix or suffix is empty, we just treat it as an empty string -*/ -message InnerOp { - HashOp hash = 1; - bytes prefix = 2; - bytes suffix = 3; -} - - -/** -ProofSpec defines what the expected parameters are for a given proof type. -This can be stored in the client and used to validate any incoming proofs. - - verify(ProofSpec, Proof) -> Proof | Error - -As demonstrated in tests, if we don't fix the algorithm used to calculate the -LeafHash for a given tree, there are many possible key-value pairs that can -generate a given hash (by interpretting the preimage differently). -We need this for proper security, requires client knows a priori what -tree format server uses. But not in code, rather a configuration object. -*/ -message ProofSpec { - // any field in the ExistenceProof must be the same as in this spec. - // except Prefix, which is just the first bytes of prefix (spec can be longer) - LeafOp leaf_spec = 1; - InnerSpec inner_spec = 2; - // max_depth (if > 0) is the maximum number of InnerOps allowed (mainly for fixed-depth tries) - int32 max_depth = 3; - // min_depth (if > 0) is the minimum number of InnerOps allowed (mainly for fixed-depth tries) - int32 min_depth = 4; -} - -/* -InnerSpec contains all store-specific structure info to determine if two proofs from a -given store are neighbors. - -This enables: - - isLeftMost(spec: InnerSpec, op: InnerOp) - isRightMost(spec: InnerSpec, op: InnerOp) - isLeftNeighbor(spec: InnerSpec, left: InnerOp, right: InnerOp) -*/ -message InnerSpec { - // Child order is the ordering of the children node, must count from 0 - // iavl tree is [0, 1] (left then right) - // merk is [0, 2, 1] (left, right, here) - repeated int32 child_order = 1; - int32 child_size = 2; - int32 min_prefix_length = 3; - int32 max_prefix_length = 4; - // empty child is the prehash image that is used when one child is nil (eg. 20 bytes of 0) - bytes empty_child = 5; - // hash is the algorithm that must be used for each InnerOp - HashOp hash = 6; -} - -/* -BatchProof is a group of multiple proof types than can be compressed -*/ -message BatchProof { - repeated BatchEntry entries = 1; -} - -// Use BatchEntry not CommitmentProof, to avoid recursion -message BatchEntry { - oneof proof { - ExistenceProof exist = 1; - NonExistenceProof nonexist = 2; - } -} - - -/****** all items here are compressed forms *******/ - -message CompressedBatchProof { - repeated CompressedBatchEntry entries = 1; - repeated InnerOp lookup_inners = 2; -} - -// Use BatchEntry not CommitmentProof, to avoid recursion -message CompressedBatchEntry { - oneof proof { - CompressedExistenceProof exist = 1; - CompressedNonExistenceProof nonexist = 2; - } -} - -message CompressedExistenceProof { - bytes key = 1; - bytes value = 2; - LeafOp leaf = 3; - // these are indexes into the lookup_inners table in CompressedBatchProof - repeated int32 path = 4; -} - -message CompressedNonExistenceProof { - bytes key = 1; // TODO: remove this as unnecessary??? we prove a range - CompressedExistenceProof left = 2; - CompressedExistenceProof right = 3; -} diff --git a/thirdParty/proto/cosmos_proto/cosmos.proto b/thirdParty/proto/cosmos_proto/cosmos.proto deleted file mode 100644 index 167b17075..000000000 --- a/thirdParty/proto/cosmos_proto/cosmos.proto +++ /dev/null @@ -1,16 +0,0 @@ -syntax = "proto3"; -package cosmos_proto; - -import "google/protobuf/descriptor.proto"; - -option go_package = "github.com/regen-network/cosmos-proto"; - -extend google.protobuf.MessageOptions { - string interface_type = 93001; - - string implements_interface = 93002; -} - -extend google.protobuf.FieldOptions { - string accepts_interface = 93001; -} diff --git a/thirdParty/proto/gogoproto/gogo.proto b/thirdParty/proto/gogoproto/gogo.proto deleted file mode 100644 index 49e78f99f..000000000 --- a/thirdParty/proto/gogoproto/gogo.proto +++ /dev/null @@ -1,145 +0,0 @@ -// Protocol Buffers for Go with Gadgets -// -// Copyright (c) 2013, The GoGo Authors. All rights reserved. -// http://github.com/gogo/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto2"; -package gogoproto; - -import "google/protobuf/descriptor.proto"; - -option java_package = "com.google.protobuf"; -option java_outer_classname = "GoGoProtos"; -option go_package = "github.com/gogo/protobuf/gogoproto"; - -extend google.protobuf.EnumOptions { - optional bool goproto_enum_prefix = 62001; - optional bool goproto_enum_stringer = 62021; - optional bool enum_stringer = 62022; - optional string enum_customname = 62023; - optional bool enumdecl = 62024; -} - -extend google.protobuf.EnumValueOptions { - optional string enumvalue_customname = 66001; -} - -extend google.protobuf.FileOptions { - optional bool goproto_getters_all = 63001; - optional bool goproto_enum_prefix_all = 63002; - optional bool goproto_stringer_all = 63003; - optional bool verbose_equal_all = 63004; - optional bool face_all = 63005; - optional bool gostring_all = 63006; - optional bool populate_all = 63007; - optional bool stringer_all = 63008; - optional bool onlyone_all = 63009; - - optional bool equal_all = 63013; - optional bool description_all = 63014; - optional bool testgen_all = 63015; - optional bool benchgen_all = 63016; - optional bool marshaler_all = 63017; - optional bool unmarshaler_all = 63018; - optional bool stable_marshaler_all = 63019; - - optional bool sizer_all = 63020; - - optional bool goproto_enum_stringer_all = 63021; - optional bool enum_stringer_all = 63022; - - optional bool unsafe_marshaler_all = 63023; - optional bool unsafe_unmarshaler_all = 63024; - - optional bool goproto_extensions_map_all = 63025; - optional bool goproto_unrecognized_all = 63026; - optional bool gogoproto_import = 63027; - optional bool protosizer_all = 63028; - optional bool compare_all = 63029; - optional bool typedecl_all = 63030; - optional bool enumdecl_all = 63031; - - optional bool goproto_registration = 63032; - optional bool messagename_all = 63033; - - optional bool goproto_sizecache_all = 63034; - optional bool goproto_unkeyed_all = 63035; -} - -extend google.protobuf.MessageOptions { - optional bool goproto_getters = 64001; - optional bool goproto_stringer = 64003; - optional bool verbose_equal = 64004; - optional bool face = 64005; - optional bool gostring = 64006; - optional bool populate = 64007; - optional bool stringer = 67008; - optional bool onlyone = 64009; - - optional bool equal = 64013; - optional bool description = 64014; - optional bool testgen = 64015; - optional bool benchgen = 64016; - optional bool marshaler = 64017; - optional bool unmarshaler = 64018; - optional bool stable_marshaler = 64019; - - optional bool sizer = 64020; - - optional bool unsafe_marshaler = 64023; - optional bool unsafe_unmarshaler = 64024; - - optional bool goproto_extensions_map = 64025; - optional bool goproto_unrecognized = 64026; - - optional bool protosizer = 64028; - optional bool compare = 64029; - - optional bool typedecl = 64030; - - optional bool messagename = 64033; - - optional bool goproto_sizecache = 64034; - optional bool goproto_unkeyed = 64035; -} - -extend google.protobuf.FieldOptions { - optional bool nullable = 65001; - optional bool embed = 65002; - optional string customtype = 65003; - optional string customname = 65004; - optional string jsontag = 65005; - optional string moretags = 65006; - optional string casttype = 65007; - optional string castkey = 65008; - optional string castvalue = 65009; - - optional bool stdtime = 65010; - optional bool stdduration = 65011; - optional bool wktpointer = 65012; - - optional string castrepeated = 65013; -} diff --git a/thirdParty/proto/google/api/annotations.proto b/thirdParty/proto/google/api/annotations.proto deleted file mode 100644 index 85c361b47..000000000 --- a/thirdParty/proto/google/api/annotations.proto +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) 2015, Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package google.api; - -import "google/api/http.proto"; -import "google/protobuf/descriptor.proto"; - -option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; -option java_multiple_files = true; -option java_outer_classname = "AnnotationsProto"; -option java_package = "com.google.api"; -option objc_class_prefix = "GAPI"; - -extend google.protobuf.MethodOptions { - // See `HttpRule`. - HttpRule http = 72295728; -} diff --git a/thirdParty/proto/google/api/http.proto b/thirdParty/proto/google/api/http.proto deleted file mode 100644 index 2bd3a19bf..000000000 --- a/thirdParty/proto/google/api/http.proto +++ /dev/null @@ -1,318 +0,0 @@ -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package google.api; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; -option java_multiple_files = true; -option java_outer_classname = "HttpProto"; -option java_package = "com.google.api"; -option objc_class_prefix = "GAPI"; - - -// Defines the HTTP configuration for an API service. It contains a list of -// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method -// to one or more HTTP REST API methods. -message Http { - // A list of HTTP configuration rules that apply to individual API methods. - // - // **NOTE:** All service configuration rules follow "last one wins" order. - repeated HttpRule rules = 1; - - // When set to true, URL path parmeters will be fully URI-decoded except in - // cases of single segment matches in reserved expansion, where "%2F" will be - // left encoded. - // - // The default behavior is to not decode RFC 6570 reserved characters in multi - // segment matches. - bool fully_decode_reserved_expansion = 2; -} - -// `HttpRule` defines the mapping of an RPC method to one or more HTTP -// REST API methods. The mapping specifies how different portions of the RPC -// request message are mapped to URL path, URL query parameters, and -// HTTP request body. The mapping is typically specified as an -// `google.api.http` annotation on the RPC method, -// see "google/api/annotations.proto" for details. -// -// The mapping consists of a field specifying the path template and -// method kind. The path template can refer to fields in the request -// message, as in the example below which describes a REST GET -// operation on a resource collection of messages: -// -// -// service Messaging { -// rpc GetMessage(GetMessageRequest) returns (Message) { -// option (google.api.http).get = "/v1/messages/{message_id}/{sub.subfield}"; -// } -// } -// message GetMessageRequest { -// message SubMessage { -// string subfield = 1; -// } -// string message_id = 1; // mapped to the URL -// SubMessage sub = 2; // `sub.subfield` is url-mapped -// } -// message Message { -// string text = 1; // content of the resource -// } -// -// The same http annotation can alternatively be expressed inside the -// `GRPC API Configuration` YAML file. -// -// http: -// rules: -// - selector: .Messaging.GetMessage -// get: /v1/messages/{message_id}/{sub.subfield} -// -// This definition enables an automatic, bidrectional mapping of HTTP -// JSON to RPC. Example: -// -// HTTP | RPC -// -----|----- -// `GET /v1/messages/123456/foo` | `GetMessage(message_id: "123456" sub: SubMessage(subfield: "foo"))` -// -// In general, not only fields but also field paths can be referenced -// from a path pattern. Fields mapped to the path pattern cannot be -// repeated and must have a primitive (non-message) type. -// -// Any fields in the request message which are not bound by the path -// pattern automatically become (optional) HTTP query -// parameters. Assume the following definition of the request message: -// -// -// service Messaging { -// rpc GetMessage(GetMessageRequest) returns (Message) { -// option (google.api.http).get = "/v1/messages/{message_id}"; -// } -// } -// message GetMessageRequest { -// message SubMessage { -// string subfield = 1; -// } -// string message_id = 1; // mapped to the URL -// int64 revision = 2; // becomes a parameter -// SubMessage sub = 3; // `sub.subfield` becomes a parameter -// } -// -// -// This enables a HTTP JSON to RPC mapping as below: -// -// HTTP | RPC -// -----|----- -// `GET /v1/messages/123456?revision=2&sub.subfield=foo` | `GetMessage(message_id: "123456" revision: 2 sub: SubMessage(subfield: "foo"))` -// -// Note that fields which are mapped to HTTP parameters must have a -// primitive type or a repeated primitive type. Message types are not -// allowed. In the case of a repeated type, the parameter can be -// repeated in the URL, as in `...?param=A¶m=B`. -// -// For HTTP method kinds which allow a request body, the `body` field -// specifies the mapping. Consider a REST update method on the -// message resource collection: -// -// -// service Messaging { -// rpc UpdateMessage(UpdateMessageRequest) returns (Message) { -// option (google.api.http) = { -// put: "/v1/messages/{message_id}" -// body: "message" -// }; -// } -// } -// message UpdateMessageRequest { -// string message_id = 1; // mapped to the URL -// Message message = 2; // mapped to the body -// } -// -// -// The following HTTP JSON to RPC mapping is enabled, where the -// representation of the JSON in the request body is determined by -// protos JSON encoding: -// -// HTTP | RPC -// -----|----- -// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" message { text: "Hi!" })` -// -// The special name `*` can be used in the body mapping to define that -// every field not bound by the path template should be mapped to the -// request body. This enables the following alternative definition of -// the update method: -// -// service Messaging { -// rpc UpdateMessage(Message) returns (Message) { -// option (google.api.http) = { -// put: "/v1/messages/{message_id}" -// body: "*" -// }; -// } -// } -// message Message { -// string message_id = 1; -// string text = 2; -// } -// -// -// The following HTTP JSON to RPC mapping is enabled: -// -// HTTP | RPC -// -----|----- -// `PUT /v1/messages/123456 { "text": "Hi!" }` | `UpdateMessage(message_id: "123456" text: "Hi!")` -// -// Note that when using `*` in the body mapping, it is not possible to -// have HTTP parameters, as all fields not bound by the path end in -// the body. This makes this option more rarely used in practice of -// defining REST APIs. The common usage of `*` is in custom methods -// which don't use the URL at all for transferring data. -// -// It is possible to define multiple HTTP methods for one RPC by using -// the `additional_bindings` option. Example: -// -// service Messaging { -// rpc GetMessage(GetMessageRequest) returns (Message) { -// option (google.api.http) = { -// get: "/v1/messages/{message_id}" -// additional_bindings { -// get: "/v1/users/{user_id}/messages/{message_id}" -// } -// }; -// } -// } -// message GetMessageRequest { -// string message_id = 1; -// string user_id = 2; -// } -// -// -// This enables the following two alternative HTTP JSON to RPC -// mappings: -// -// HTTP | RPC -// -----|----- -// `GET /v1/messages/123456` | `GetMessage(message_id: "123456")` -// `GET /v1/users/me/messages/123456` | `GetMessage(user_id: "me" message_id: "123456")` -// -// # Rules for HTTP mapping -// -// The rules for mapping HTTP path, query parameters, and body fields -// to the request message are as follows: -// -// 1. The `body` field specifies either `*` or a field path, or is -// omitted. If omitted, it indicates there is no HTTP request body. -// 2. Leaf fields (recursive expansion of nested messages in the -// request) can be classified into three types: -// (a) Matched in the URL template. -// (b) Covered by body (if body is `*`, everything except (a) fields; -// else everything under the body field) -// (c) All other fields. -// 3. URL query parameters found in the HTTP request are mapped to (c) fields. -// 4. Any body sent with an HTTP request can contain only (b) fields. -// -// The syntax of the path template is as follows: -// -// Template = "/" Segments [ Verb ] ; -// Segments = Segment { "/" Segment } ; -// Segment = "*" | "**" | LITERAL | Variable ; -// Variable = "{" FieldPath [ "=" Segments ] "}" ; -// FieldPath = IDENT { "." IDENT } ; -// Verb = ":" LITERAL ; -// -// The syntax `*` matches a single path segment. The syntax `**` matches zero -// or more path segments, which must be the last part of the path except the -// `Verb`. The syntax `LITERAL` matches literal text in the path. -// -// The syntax `Variable` matches part of the URL path as specified by its -// template. A variable template must not contain other variables. If a variable -// matches a single path segment, its template may be omitted, e.g. `{var}` -// is equivalent to `{var=*}`. -// -// If a variable contains exactly one path segment, such as `"{var}"` or -// `"{var=*}"`, when such a variable is expanded into a URL path, all characters -// except `[-_.~0-9a-zA-Z]` are percent-encoded. Such variables show up in the -// Discovery Document as `{var}`. -// -// If a variable contains one or more path segments, such as `"{var=foo/*}"` -// or `"{var=**}"`, when such a variable is expanded into a URL path, all -// characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. Such variables -// show up in the Discovery Document as `{+var}`. -// -// NOTE: While the single segment variable matches the semantics of -// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 -// Simple String Expansion, the multi segment variable **does not** match -// RFC 6570 Reserved Expansion. The reason is that the Reserved Expansion -// does not expand special characters like `?` and `#`, which would lead -// to invalid URLs. -// -// NOTE: the field paths in variables and in the `body` must not refer to -// repeated fields or map fields. -message HttpRule { - // Selects methods to which this rule applies. - // - // Refer to [selector][google.api.DocumentationRule.selector] for syntax details. - string selector = 1; - - // Determines the URL pattern is matched by this rules. This pattern can be - // used with any of the {get|put|post|delete|patch} methods. A custom method - // can be defined using the 'custom' field. - oneof pattern { - // Used for listing and getting information about resources. - string get = 2; - - // Used for updating a resource. - string put = 3; - - // Used for creating a resource. - string post = 4; - - // Used for deleting a resource. - string delete = 5; - - // Used for updating a resource. - string patch = 6; - - // The custom pattern is used for specifying an HTTP method that is not - // included in the `pattern` field, such as HEAD, or "*" to leave the - // HTTP method unspecified for this rule. The wild-card rule is useful - // for services that provide content to Web (HTML) clients. - CustomHttpPattern custom = 8; - } - - // The name of the request field whose value is mapped to the HTTP body, or - // `*` for mapping all fields not captured by the path pattern to the HTTP - // body. NOTE: the referred field must not be a repeated field and must be - // present at the top-level of request message type. - string body = 7; - - // Optional. The name of the response field whose value is mapped to the HTTP - // body of response. Other response fields are ignored. When - // not set, the response message will be used as HTTP body of response. - string response_body = 12; - - // Additional HTTP bindings for the selector. Nested bindings must - // not contain an `additional_bindings` field themselves (that is, - // the nesting may only be one level deep). - repeated HttpRule additional_bindings = 11; -} - -// A custom pattern is used for defining custom HTTP verb. -message CustomHttpPattern { - // The name of this custom HTTP verb. - string kind = 1; - - // The path matched by this custom verb. - string path = 2; -} diff --git a/thirdParty/proto/google/api/httpbody.proto b/thirdParty/proto/google/api/httpbody.proto deleted file mode 100644 index 96c82b99c..000000000 --- a/thirdParty/proto/google/api/httpbody.proto +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2018 Google LLC. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -syntax = "proto3"; - -package google.api; - -import "google/protobuf/any.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/api/httpbody;httpbody"; -option java_multiple_files = true; -option java_outer_classname = "HttpBodyProto"; -option java_package = "com.google.api"; -option objc_class_prefix = "GAPI"; - -// Message that represents an arbitrary HTTP body. It should only be used for -// payload formats that can't be represented as JSON, such as raw binary or -// an HTML page. -// -// -// This message can be used both in streaming and non-streaming API methods in -// the request as well as the response. -// -// It can be used as a top-level request field, which is convenient if one -// wants to extract parameters from either the URL or HTTP template into the -// request fields and also want access to the raw HTTP body. -// -// Example: -// -// message GetResourceRequest { -// // A unique request id. -// string request_id = 1; -// -// // The raw HTTP body is bound to this field. -// google.api.HttpBody http_body = 2; -// } -// -// service ResourceService { -// rpc GetResource(GetResourceRequest) returns (google.api.HttpBody); -// rpc UpdateResource(google.api.HttpBody) returns -// (google.protobuf.Empty); -// } -// -// Example with streaming methods: -// -// service CaldavService { -// rpc GetCalendar(stream google.api.HttpBody) -// returns (stream google.api.HttpBody); -// rpc UpdateCalendar(stream google.api.HttpBody) -// returns (stream google.api.HttpBody); -// } -// -// Use of this type only changes how the request and response bodies are -// handled, all other features will continue to work unchanged. -message HttpBody { - // The HTTP Content-Type header value specifying the content type of the body. - string content_type = 1; - - // The HTTP request/response body as raw binary. - bytes data = 2; - - // Application specific response metadata. Must be set in the first response - // for streaming APIs. - repeated google.protobuf.Any extensions = 3; -} diff --git a/thirdParty/proto/google/protobuf/any.proto b/thirdParty/proto/google/protobuf/any.proto deleted file mode 100644 index 58b511583..000000000 --- a/thirdParty/proto/google/protobuf/any.proto +++ /dev/null @@ -1,164 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package google.protobuf; - -import "gogoproto/gogo.proto"; - -option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option go_package = "types"; -option java_package = "com.google.protobuf"; -option java_outer_classname = "AnyProto"; -option java_multiple_files = true; -option objc_class_prefix = "GPB"; - -// `Any` contains an arbitrary serialized protocol buffer message along with a -// URL that describes the type of the serialized message. -// -// Protobuf library provides support to pack/unpack Any values in the form -// of utility functions or additional generated methods of the Any type. -// -// Example 1: Pack and unpack a message in C++. -// -// Foo foo = ...; -// Any any; -// any.PackFrom(foo); -// ... -// if (any.UnpackTo(&foo)) { -// ... -// } -// -// Example 2: Pack and unpack a message in Java. -// -// Foo foo = ...; -// Any any = Any.pack(foo); -// ... -// if (any.is(Foo.class)) { -// foo = any.unpack(Foo.class); -// } -// -// Example 3: Pack and unpack a message in Python. -// -// foo = Foo(...) -// any = Any() -// any.Pack(foo) -// ... -// if any.Is(Foo.DESCRIPTOR): -// any.Unpack(foo) -// ... -// -// Example 4: Pack and unpack a message in Go -// -// foo := &pb.Foo{...} -// any, err := ptypes.MarshalAny(foo) -// ... -// foo := &pb.Foo{} -// if err := ptypes.UnmarshalAny(any, foo); err != nil { -// ... -// } -// -// The pack methods provided by protobuf library will by default use -// 'type.googleapis.com/full.type.name' as the type URL and the unpack -// methods only use the fully qualified type name after the last '/' -// in the type URL, for example "foo.bar.com/x/y.z" will yield type -// name "y.z". -// -// -// JSON -// ==== -// The JSON representation of an `Any` value uses the regular -// representation of the deserialized, embedded message, with an -// additional field `@type` which contains the type URL. Example: -// -// package google.profile; -// message Person { -// string first_name = 1; -// string last_name = 2; -// } -// -// { -// "@type": "type.googleapis.com/google.profile.Person", -// "firstName": , -// "lastName": -// } -// -// If the embedded message type is well-known and has a custom JSON -// representation, that representation will be embedded adding a field -// `value` which holds the custom JSON in addition to the `@type` -// field. Example (for message [google.protobuf.Duration][]): -// -// { -// "@type": "type.googleapis.com/google.protobuf.Duration", -// "value": "1.212s" -// } -// -message Any { - // A URL/resource name that uniquely identifies the type of the serialized - // protocol buffer message. This string must contain at least - // one "/" character. The last segment of the URL's path must represent - // the fully qualified name of the type (as in - // `path/google.protobuf.Duration`). The name should be in a canonical form - // (e.g., leading "." is not accepted). - // - // In practice, teams usually precompile into the binary all types that they - // expect it to use in the context of Any. However, for URLs which use the - // scheme `http`, `https`, or no scheme, one can optionally set up a type - // server that maps type URLs to message definitions as follows: - // - // * If no scheme is provided, `https` is assumed. - // * An HTTP GET on the URL must yield a [google.protobuf.Type][] - // value in binary format, or produce an error. - // * Applications are allowed to cache lookup results based on the - // URL, or have them precompiled into a binary to avoid any - // lookup. Therefore, binary compatibility needs to be preserved - // on changes to types. (Use versioned type names to manage - // breaking changes.) - // - // Note: this functionality is not currently available in the official - // protobuf release, and it is not used for type URLs beginning with - // type.googleapis.com. - // - // Schemes other than `http`, `https` (or the empty scheme) might be - // used with implementation specific semantics. - // - string type_url = 1; - - // Must be a valid serialized protocol buffer of the above specified type. - bytes value = 2; - - option (gogoproto.typedecl) = false; - option (gogoproto.goproto_stringer) = false; - option (gogoproto.gostring) = false; - option (gogoproto.stringer) = false; -} - -option (gogoproto.goproto_registration) = false; diff --git a/thirdParty/proto/tendermint/abci/types.proto b/thirdParty/proto/tendermint/abci/types.proto deleted file mode 100644 index 2cbcabb29..000000000 --- a/thirdParty/proto/tendermint/abci/types.proto +++ /dev/null @@ -1,407 +0,0 @@ -syntax = "proto3"; -package tendermint.abci; - -option go_package = "github.com/tendermint/tendermint/abci/types"; - -// For more information on gogo.proto, see: -// https://github.com/gogo/protobuf/blob/master/extensions.md -import "tendermint/crypto/proof.proto"; -import "tendermint/types/types.proto"; -import "tendermint/crypto/keys.proto"; -import "tendermint/types/params.proto"; -import "google/protobuf/timestamp.proto"; -import "gogoproto/gogo.proto"; - -// This file is copied from http://github.com/tendermint/abci -// NOTE: When using custom types, mind the warnings. -// https://github.com/gogo/protobuf/blob/master/custom_types.md#warnings-and-issues - -//---------------------------------------- -// Request types - -message Request { - oneof value { - RequestEcho echo = 1; - RequestFlush flush = 2; - RequestInfo info = 3; - RequestSetOption set_option = 4; - RequestInitChain init_chain = 5; - RequestQuery query = 6; - RequestBeginBlock begin_block = 7; - RequestCheckTx check_tx = 8; - RequestDeliverTx deliver_tx = 9; - RequestEndBlock end_block = 10; - RequestCommit commit = 11; - RequestListSnapshots list_snapshots = 12; - RequestOfferSnapshot offer_snapshot = 13; - RequestLoadSnapshotChunk load_snapshot_chunk = 14; - RequestApplySnapshotChunk apply_snapshot_chunk = 15; - } -} - -message RequestEcho { - string message = 1; -} - -message RequestFlush {} - -message RequestInfo { - string version = 1; - uint64 block_version = 2; - uint64 p2p_version = 3; -} - -// nondeterministic -message RequestSetOption { - string key = 1; - string value = 2; -} - -message RequestInitChain { - google.protobuf.Timestamp time = 1 - [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; - string chain_id = 2; - ConsensusParams consensus_params = 3; - repeated ValidatorUpdate validators = 4 [(gogoproto.nullable) = false]; - bytes app_state_bytes = 5; - int64 initial_height = 6; -} - -message RequestQuery { - bytes data = 1; - string path = 2; - int64 height = 3; - bool prove = 4; -} - -message RequestBeginBlock { - bytes hash = 1; - tendermint.types.Header header = 2 [(gogoproto.nullable) = false]; - LastCommitInfo last_commit_info = 3 [(gogoproto.nullable) = false]; - repeated Evidence byzantine_validators = 4 [(gogoproto.nullable) = false]; -} - -enum CheckTxType { - NEW = 0 [(gogoproto.enumvalue_customname) = "New"]; - RECHECK = 1 [(gogoproto.enumvalue_customname) = "Recheck"]; -} - -message RequestCheckTx { - bytes tx = 1; - CheckTxType type = 2; -} - -message RequestDeliverTx { - bytes tx = 1; -} - -message RequestEndBlock { - int64 height = 1; -} - -message RequestCommit {} - -// lists available snapshots -message RequestListSnapshots { -} - -// offers a snapshot to the application -message RequestOfferSnapshot { - Snapshot snapshot = 1; // snapshot offered by peers - bytes app_hash = 2; // light client-verified app hash for snapshot height -} - -// loads a snapshot chunk -message RequestLoadSnapshotChunk { - uint64 height = 1; - uint32 format = 2; - uint32 chunk = 3; -} - -// Applies a snapshot chunk -message RequestApplySnapshotChunk { - uint32 index = 1; - bytes chunk = 2; - string sender = 3; -} - -//---------------------------------------- -// Response types - -message Response { - oneof value { - ResponseException exception = 1; - ResponseEcho echo = 2; - ResponseFlush flush = 3; - ResponseInfo info = 4; - ResponseSetOption set_option = 5; - ResponseInitChain init_chain = 6; - ResponseQuery query = 7; - ResponseBeginBlock begin_block = 8; - ResponseCheckTx check_tx = 9; - ResponseDeliverTx deliver_tx = 10; - ResponseEndBlock end_block = 11; - ResponseCommit commit = 12; - ResponseListSnapshots list_snapshots = 13; - ResponseOfferSnapshot offer_snapshot = 14; - ResponseLoadSnapshotChunk load_snapshot_chunk = 15; - ResponseApplySnapshotChunk apply_snapshot_chunk = 16; - } -} - -// nondeterministic -message ResponseException { - string error = 1; -} - -message ResponseEcho { - string message = 1; -} - -message ResponseFlush {} - -message ResponseInfo { - string data = 1; - - string version = 2; - uint64 app_version = 3; - - int64 last_block_height = 4; - bytes last_block_app_hash = 5; -} - -// nondeterministic -message ResponseSetOption { - uint32 code = 1; - // bytes data = 2; - string log = 3; - string info = 4; -} - -message ResponseInitChain { - ConsensusParams consensus_params = 1; - repeated ValidatorUpdate validators = 2 [(gogoproto.nullable) = false]; - bytes app_hash = 3; -} - -message ResponseQuery { - uint32 code = 1; - // bytes data = 2; // use "value" instead. - string log = 3; // nondeterministic - string info = 4; // nondeterministic - int64 index = 5; - bytes key = 6; - bytes value = 7; - tendermint.crypto.ProofOps proof_ops = 8; - int64 height = 9; - string codespace = 10; -} - -message ResponseBeginBlock { - repeated Event events = 1 - [(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"]; -} - -message ResponseCheckTx { - uint32 code = 1; - bytes data = 2; - string log = 3; // nondeterministic - string info = 4; // nondeterministic - int64 gas_wanted = 5 [json_name = "gas_wanted"]; - int64 gas_used = 6 [json_name = "gas_used"]; - repeated Event events = 7 - [(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"]; - string codespace = 8; -} - -message ResponseDeliverTx { - uint32 code = 1; - bytes data = 2; - string log = 3; // nondeterministic - string info = 4; // nondeterministic - int64 gas_wanted = 5 [json_name = "gas_wanted"]; - int64 gas_used = 6 [json_name = "gas_used"]; - repeated Event events = 7 - [(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"]; - string codespace = 8; -} - -message ResponseEndBlock { - repeated ValidatorUpdate validator_updates = 1 - [(gogoproto.nullable) = false]; - ConsensusParams consensus_param_updates = 2; - repeated Event events = 3 - [(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"]; -} - -message ResponseCommit { - // reserve 1 - bytes data = 2; - int64 retain_height = 3; -} - -message ResponseListSnapshots { - repeated Snapshot snapshots = 1; -} - -message ResponseOfferSnapshot { - Result result = 1; - - enum Result { - UNKNOWN = 0; // Unknown result, abort all snapshot restoration - ACCEPT = 1; // Snapshot accepted, apply chunks - ABORT = 2; // Abort all snapshot restoration - REJECT = 3; // Reject this specific snapshot, try others - REJECT_FORMAT = 4; // Reject all snapshots of this format, try others - REJECT_SENDER = 5; // Reject all snapshots from the sender(s), try others - } -} - -message ResponseLoadSnapshotChunk { - bytes chunk = 1; -} - -message ResponseApplySnapshotChunk { - Result result = 1; - repeated uint32 refetch_chunks = 2; // Chunks to refetch and reapply - repeated string reject_senders = 3; // Chunk senders to reject and ban - - enum Result { - UNKNOWN = 0; // Unknown result, abort all snapshot restoration - ACCEPT = 1; // Chunk successfully accepted - ABORT = 2; // Abort all snapshot restoration - RETRY = 3; // Retry chunk (combine with refetch and reject) - RETRY_SNAPSHOT = 4; // Retry snapshot (combine with refetch and reject) - REJECT_SNAPSHOT = 5; // Reject this snapshot, try others - } -} - -//---------------------------------------- -// Misc. - -// ConsensusParams contains all consensus-relevant parameters -// that can be adjusted by the abci app -message ConsensusParams { - BlockParams block = 1; - tendermint.types.EvidenceParams evidence = 2; - tendermint.types.ValidatorParams validator = 3; - tendermint.types.VersionParams version = 4; -} - -// BlockParams contains limits on the block size. -message BlockParams { - // Note: must be greater than 0 - int64 max_bytes = 1; - // Note: must be greater or equal to -1 - int64 max_gas = 2; -} - -message LastCommitInfo { - int32 round = 1; - repeated VoteInfo votes = 2 [(gogoproto.nullable) = false]; -} - -// Event allows application developers to attach additional information to -// ResponseBeginBlock, ResponseEndBlock, ResponseCheckTx and ResponseDeliverTx. -// Later, transactions may be queried using these events. -message Event { - string type = 1; - repeated EventAttribute attributes = 2 [ - (gogoproto.nullable) = false, - (gogoproto.jsontag) = "attributes,omitempty" - ]; -} - -// EventAttribute is a single key-value pair, associated with an event. -message EventAttribute { - bytes key = 1; - bytes value = 2; - bool index = 3; // nondeterministic -} - -// TxResult contains results of executing the transaction. -// -// One usage is indexing transaction results. -message TxResult { - int64 height = 1; - uint32 index = 2; - bytes tx = 3; - ResponseDeliverTx result = 4 [(gogoproto.nullable) = false]; -} - -//---------------------------------------- -// Blockchain Types - -// Validator -message Validator { - bytes address = 1; // The first 20 bytes of SHA256(public key) - // PubKey pub_key = 2 [(gogoproto.nullable)=false]; - int64 power = 3; // The voting power -} - -// ValidatorUpdate -message ValidatorUpdate { - tendermint.crypto.PublicKey pub_key = 1 [(gogoproto.nullable) = false]; - int64 power = 2; -} - -// VoteInfo -message VoteInfo { - Validator validator = 1 [(gogoproto.nullable) = false]; - bool signed_last_block = 2; -} - -enum EvidenceType { - UNKNOWN = 0; - DUPLICATE_VOTE = 1; - LIGHT_CLIENT_ATTACK = 2; -} - -message Evidence { - EvidenceType type = 1; - // The offending validator - Validator validator = 2 [(gogoproto.nullable) = false]; - // The height when the offense occurred - int64 height = 3; - // The corresponding time where the offense occurred - google.protobuf.Timestamp time = 4 [ - (gogoproto.nullable) = false, - (gogoproto.stdtime) = true - ]; - // Total voting power of the validator set in case the ABCI application does - // not store historical validators. - // https://github.com/tendermint/tendermint/issues/4581 - int64 total_voting_power = 5; -} - -//---------------------------------------- -// State Sync Types - -message Snapshot { - uint64 height = 1; // The height at which the snapshot was taken - uint32 format = 2; // The application-specific snapshot format - uint32 chunks = 3; // Number of chunks in the snapshot - bytes hash = 4; // Arbitrary snapshot hash, equal only if identical - bytes metadata = 5; // Arbitrary application metadata -} - -//---------------------------------------- -// Service Definition - -service ABCIApplication { - rpc Echo(RequestEcho) returns (ResponseEcho); - rpc Flush(RequestFlush) returns (ResponseFlush); - rpc Info(RequestInfo) returns (ResponseInfo); - rpc SetOption(RequestSetOption) returns (ResponseSetOption); - rpc DeliverTx(RequestDeliverTx) returns (ResponseDeliverTx); - rpc CheckTx(RequestCheckTx) returns (ResponseCheckTx); - rpc Query(RequestQuery) returns (ResponseQuery); - rpc Commit(RequestCommit) returns (ResponseCommit); - rpc InitChain(RequestInitChain) returns (ResponseInitChain); - rpc BeginBlock(RequestBeginBlock) returns (ResponseBeginBlock); - rpc EndBlock(RequestEndBlock) returns (ResponseEndBlock); - rpc ListSnapshots(RequestListSnapshots) returns (ResponseListSnapshots); - rpc OfferSnapshot(RequestOfferSnapshot) returns (ResponseOfferSnapshot); - rpc LoadSnapshotChunk(RequestLoadSnapshotChunk) returns (ResponseLoadSnapshotChunk); - rpc ApplySnapshotChunk(RequestApplySnapshotChunk) returns (ResponseApplySnapshotChunk); -} diff --git a/thirdParty/proto/tendermint/crypto/keys.proto b/thirdParty/proto/tendermint/crypto/keys.proto deleted file mode 100644 index 16fd7adf3..000000000 --- a/thirdParty/proto/tendermint/crypto/keys.proto +++ /dev/null @@ -1,17 +0,0 @@ -syntax = "proto3"; -package tendermint.crypto; - -option go_package = "github.com/tendermint/tendermint/proto/tendermint/crypto"; - -import "gogoproto/gogo.proto"; - -// PublicKey defines the keys available for use with Tendermint Validators -message PublicKey { - option (gogoproto.compare) = true; - option (gogoproto.equal) = true; - - oneof sum { - bytes ed25519 = 1; - bytes secp256k1 = 2; - } -} diff --git a/thirdParty/proto/tendermint/crypto/proof.proto b/thirdParty/proto/tendermint/crypto/proof.proto deleted file mode 100644 index 975df7685..000000000 --- a/thirdParty/proto/tendermint/crypto/proof.proto +++ /dev/null @@ -1,41 +0,0 @@ -syntax = "proto3"; -package tendermint.crypto; - -option go_package = "github.com/tendermint/tendermint/proto/tendermint/crypto"; - -import "gogoproto/gogo.proto"; - -message Proof { - int64 total = 1; - int64 index = 2; - bytes leaf_hash = 3; - repeated bytes aunts = 4; -} - -message ValueOp { - // Encoded in ProofOp.Key. - bytes key = 1; - - // To encode in ProofOp.Data - Proof proof = 2; -} - -message DominoOp { - string key = 1; - string input = 2; - string output = 3; -} - -// ProofOp defines an operation used for calculating Merkle root -// The data could be arbitrary format, providing nessecary data -// for example neighbouring node hash -message ProofOp { - string type = 1; - bytes key = 2; - bytes data = 3; -} - -// ProofOps is Merkle proof defined by the list of ProofOps -message ProofOps { - repeated ProofOp ops = 1 [(gogoproto.nullable) = false]; -} diff --git a/thirdParty/proto/tendermint/libs/bits/types.proto b/thirdParty/proto/tendermint/libs/bits/types.proto deleted file mode 100644 index 3111d113a..000000000 --- a/thirdParty/proto/tendermint/libs/bits/types.proto +++ /dev/null @@ -1,9 +0,0 @@ -syntax = "proto3"; -package tendermint.libs.bits; - -option go_package = "github.com/tendermint/tendermint/proto/tendermint/libs/bits"; - -message BitArray { - int64 bits = 1; - repeated uint64 elems = 2; -} diff --git a/thirdParty/proto/tendermint/p2p/types.proto b/thirdParty/proto/tendermint/p2p/types.proto deleted file mode 100644 index 0d42ea400..000000000 --- a/thirdParty/proto/tendermint/p2p/types.proto +++ /dev/null @@ -1,34 +0,0 @@ -syntax = "proto3"; -package tendermint.p2p; - -option go_package = "github.com/tendermint/tendermint/proto/tendermint/p2p"; - -import "gogoproto/gogo.proto"; - -message NetAddress { - string id = 1 [(gogoproto.customname) = "ID"]; - string ip = 2 [(gogoproto.customname) = "IP"]; - uint32 port = 3; -} - -message ProtocolVersion { - uint64 p2p = 1 [(gogoproto.customname) = "P2P"]; - uint64 block = 2; - uint64 app = 3; -} - -message DefaultNodeInfo { - ProtocolVersion protocol_version = 1 [(gogoproto.nullable) = false]; - string default_node_id = 2 [(gogoproto.customname) = "DefaultNodeID"]; - string listen_addr = 3; - string network = 4; - string version = 5; - bytes channels = 6; - string moniker = 7; - DefaultNodeInfoOther other = 8 [(gogoproto.nullable) = false]; -} - -message DefaultNodeInfoOther { - string tx_index = 1; - string rpc_address = 2 [(gogoproto.customname) = "RPCAddress"]; -} diff --git a/thirdParty/proto/tendermint/types/block.proto b/thirdParty/proto/tendermint/types/block.proto deleted file mode 100644 index 84e9bb15d..000000000 --- a/thirdParty/proto/tendermint/types/block.proto +++ /dev/null @@ -1,15 +0,0 @@ -syntax = "proto3"; -package tendermint.types; - -option go_package = "github.com/tendermint/tendermint/proto/tendermint/types"; - -import "gogoproto/gogo.proto"; -import "tendermint/types/types.proto"; -import "tendermint/types/evidence.proto"; - -message Block { - Header header = 1 [(gogoproto.nullable) = false]; - Data data = 2 [(gogoproto.nullable) = false]; - tendermint.types.EvidenceList evidence = 3 [(gogoproto.nullable) = false]; - Commit last_commit = 4; -} diff --git a/thirdParty/proto/tendermint/types/evidence.proto b/thirdParty/proto/tendermint/types/evidence.proto deleted file mode 100644 index 3b234571b..000000000 --- a/thirdParty/proto/tendermint/types/evidence.proto +++ /dev/null @@ -1,38 +0,0 @@ -syntax = "proto3"; -package tendermint.types; - -option go_package = "github.com/tendermint/tendermint/proto/tendermint/types"; - -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; -import "tendermint/types/types.proto"; -import "tendermint/types/validator.proto"; - -message Evidence { - oneof sum { - DuplicateVoteEvidence duplicate_vote_evidence = 1; - LightClientAttackEvidence light_client_attack_evidence = 2; - } -} - -// DuplicateVoteEvidence contains evidence of a validator signed two conflicting votes. -message DuplicateVoteEvidence { - tendermint.types.Vote vote_a = 1; - tendermint.types.Vote vote_b = 2; - int64 total_voting_power = 3; - int64 validator_power = 4; - google.protobuf.Timestamp timestamp = 5 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; -} - -// LightClientAttackEvidence contains evidence of a set of validators attempting to mislead a light client. -message LightClientAttackEvidence { - tendermint.types.LightBlock conflicting_block = 1; - int64 common_height = 2; - repeated tendermint.types.Validator byzantine_validators = 3; - int64 total_voting_power = 4; - google.protobuf.Timestamp timestamp = 5 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; -} - -message EvidenceList { - repeated Evidence evidence = 1 [(gogoproto.nullable) = false]; -} diff --git a/thirdParty/proto/tendermint/types/params.proto b/thirdParty/proto/tendermint/types/params.proto deleted file mode 100644 index 0de7d846f..000000000 --- a/thirdParty/proto/tendermint/types/params.proto +++ /dev/null @@ -1,80 +0,0 @@ -syntax = "proto3"; -package tendermint.types; - -option go_package = "github.com/tendermint/tendermint/proto/tendermint/types"; - -import "gogoproto/gogo.proto"; -import "google/protobuf/duration.proto"; - -option (gogoproto.equal_all) = true; - -// ConsensusParams contains consensus critical parameters that determine the -// validity of blocks. -message ConsensusParams { - BlockParams block = 1 [(gogoproto.nullable) = false]; - EvidenceParams evidence = 2 [(gogoproto.nullable) = false]; - ValidatorParams validator = 3 [(gogoproto.nullable) = false]; - VersionParams version = 4 [(gogoproto.nullable) = false]; -} - -// BlockParams contains limits on the block size. -message BlockParams { - // Max block size, in bytes. - // Note: must be greater than 0 - int64 max_bytes = 1; - // Max gas per block. - // Note: must be greater or equal to -1 - int64 max_gas = 2; - // Minimum time increment between consecutive blocks (in milliseconds) If the - // block header timestamp is ahead of the system clock, decrease this value. - // - // Not exposed to the application. - int64 time_iota_ms = 3; -} - -// EvidenceParams determine how we handle evidence of malfeasance. -message EvidenceParams { - // Max age of evidence, in blocks. - // - // The basic formula for calculating this is: MaxAgeDuration / {average block - // time}. - int64 max_age_num_blocks = 1; - - // Max age of evidence, in time. - // - // It should correspond with an app's "unbonding period" or other similar - // mechanism for handling [Nothing-At-Stake - // attacks](https://github.com/ethereum/wiki/wiki/Proof-of-Stake-FAQ#what-is-the-nothing-at-stake-problem-and-how-can-it-be-fixed). - google.protobuf.Duration max_age_duration = 2 - [(gogoproto.nullable) = false, (gogoproto.stdduration) = true]; - - // This sets the maximum size of total evidence in bytes that can be committed in a single block. - // and should fall comfortably under the max block bytes. - // Default is 1048576 or 1MB - int64 max_bytes = 3; -} - -// ValidatorParams restrict the public key types validators can use. -// NOTE: uses ABCI pubkey naming, not Amino names. -message ValidatorParams { - option (gogoproto.populate) = true; - option (gogoproto.equal) = true; - - repeated string pub_key_types = 1; -} - -// VersionParams contains the ABCI application version. -message VersionParams { - option (gogoproto.populate) = true; - option (gogoproto.equal) = true; - - uint64 app_version = 1; -} - -// HashedParams is a subset of ConsensusParams. -// -// It is hashed into the Header.ConsensusHash. -message HashedParams { - int64 block_max_bytes = 1; - int64 block_max_gas = 2; -} diff --git a/thirdParty/proto/tendermint/types/types.proto b/thirdParty/proto/tendermint/types/types.proto deleted file mode 100644 index 7f7ea74ca..000000000 --- a/thirdParty/proto/tendermint/types/types.proto +++ /dev/null @@ -1,157 +0,0 @@ -syntax = "proto3"; -package tendermint.types; - -option go_package = "github.com/tendermint/tendermint/proto/tendermint/types"; - -import "gogoproto/gogo.proto"; -import "google/protobuf/timestamp.proto"; -import "tendermint/crypto/proof.proto"; -import "tendermint/version/types.proto"; -import "tendermint/types/validator.proto"; - -// BlockIdFlag indicates which BlcokID the signature is for -enum BlockIDFlag { - option (gogoproto.goproto_enum_stringer) = true; - option (gogoproto.goproto_enum_prefix) = false; - - BLOCK_ID_FLAG_UNKNOWN = 0 [(gogoproto.enumvalue_customname) = "BlockIDFlagUnknown"]; - BLOCK_ID_FLAG_ABSENT = 1 [(gogoproto.enumvalue_customname) = "BlockIDFlagAbsent"]; - BLOCK_ID_FLAG_COMMIT = 2 [(gogoproto.enumvalue_customname) = "BlockIDFlagCommit"]; - BLOCK_ID_FLAG_NIL = 3 [(gogoproto.enumvalue_customname) = "BlockIDFlagNil"]; -} - -// SignedMsgType is a type of signed message in the consensus. -enum SignedMsgType { - option (gogoproto.goproto_enum_stringer) = true; - option (gogoproto.goproto_enum_prefix) = false; - - SIGNED_MSG_TYPE_UNKNOWN = 0 [(gogoproto.enumvalue_customname) = "UnknownType"]; - // Votes - SIGNED_MSG_TYPE_PREVOTE = 1 [(gogoproto.enumvalue_customname) = "PrevoteType"]; - SIGNED_MSG_TYPE_PRECOMMIT = 2 [(gogoproto.enumvalue_customname) = "PrecommitType"]; - - // Proposals - SIGNED_MSG_TYPE_PROPOSAL = 32 [(gogoproto.enumvalue_customname) = "ProposalType"]; -} - -// PartsetHeader -message PartSetHeader { - uint32 total = 1; - bytes hash = 2; -} - -message Part { - uint32 index = 1; - bytes bytes = 2; - tendermint.crypto.Proof proof = 3 [(gogoproto.nullable) = false]; -} - -// BlockID -message BlockID { - bytes hash = 1; - PartSetHeader part_set_header = 2 [(gogoproto.nullable) = false]; -} - -// -------------------------------- - -// Header defines the structure of a Tendermint block header. -message Header { - // basic block info - tendermint.version.Consensus version = 1 [(gogoproto.nullable) = false]; - string chain_id = 2 [(gogoproto.customname) = "ChainID"]; - int64 height = 3; - google.protobuf.Timestamp time = 4 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; - - // prev block info - BlockID last_block_id = 5 [(gogoproto.nullable) = false]; - - // hashes of block data - bytes last_commit_hash = 6; // commit from validators from the last block - bytes data_hash = 7; // transactions - - // hashes from the app output from the prev block - bytes validators_hash = 8; // validators for the current block - bytes next_validators_hash = 9; // validators for the next block - bytes consensus_hash = 10; // consensus params for current block - bytes app_hash = 11; // state after txs from the previous block - bytes last_results_hash = 12; // root hash of all results from the txs from the previous block - - // consensus info - bytes evidence_hash = 13; // evidence included in the block - bytes proposer_address = 14; // original proposer of the block -} - -// Data contains the set of transactions included in the block -message Data { - // Txs that will be applied by state @ block.Height+1. - // NOTE: not all txs here are valid. We're just agreeing on the order first. - // This means that block.AppHash does not include these txs. - repeated bytes txs = 1; -} - -// Vote represents a prevote, precommit, or commit vote from validators for -// consensus. -message Vote { - SignedMsgType type = 1; - int64 height = 2; - int32 round = 3; - BlockID block_id = 4 - [(gogoproto.nullable) = false, (gogoproto.customname) = "BlockID"]; // zero if vote is nil. - google.protobuf.Timestamp timestamp = 5 - [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; - bytes validator_address = 6; - int32 validator_index = 7; - bytes signature = 8; -} - -// Commit contains the evidence that a block was committed by a set of validators. -message Commit { - int64 height = 1; - int32 round = 2; - BlockID block_id = 3 [(gogoproto.nullable) = false, (gogoproto.customname) = "BlockID"]; - repeated CommitSig signatures = 4 [(gogoproto.nullable) = false]; -} - -// CommitSig is a part of the Vote included in a Commit. -message CommitSig { - BlockIDFlag block_id_flag = 1; - bytes validator_address = 2; - google.protobuf.Timestamp timestamp = 3 - [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; - bytes signature = 4; -} - -message Proposal { - SignedMsgType type = 1; - int64 height = 2; - int32 round = 3; - int32 pol_round = 4; - BlockID block_id = 5 [(gogoproto.customname) = "BlockID", (gogoproto.nullable) = false]; - google.protobuf.Timestamp timestamp = 6 - [(gogoproto.nullable) = false, (gogoproto.stdtime) = true]; - bytes signature = 7; -} - -message SignedHeader { - Header header = 1; - Commit commit = 2; -} - -message LightBlock { - SignedHeader signed_header = 1; - tendermint.types.ValidatorSet validator_set = 2; -} - -message BlockMeta { - BlockID block_id = 1 [(gogoproto.customname) = "BlockID", (gogoproto.nullable) = false]; - int64 block_size = 2; - Header header = 3 [(gogoproto.nullable) = false]; - int64 num_txs = 4; -} - -// TxProof represents a Merkle proof of the presence of a transaction in the Merkle tree. -message TxProof { - bytes root_hash = 1; - bytes data = 2; - tendermint.crypto.Proof proof = 3; -} diff --git a/thirdParty/proto/tendermint/types/validator.proto b/thirdParty/proto/tendermint/types/validator.proto deleted file mode 100644 index 49860b96d..000000000 --- a/thirdParty/proto/tendermint/types/validator.proto +++ /dev/null @@ -1,25 +0,0 @@ -syntax = "proto3"; -package tendermint.types; - -option go_package = "github.com/tendermint/tendermint/proto/tendermint/types"; - -import "gogoproto/gogo.proto"; -import "tendermint/crypto/keys.proto"; - -message ValidatorSet { - repeated Validator validators = 1; - Validator proposer = 2; - int64 total_voting_power = 3; -} - -message Validator { - bytes address = 1; - tendermint.crypto.PublicKey pub_key = 2 [(gogoproto.nullable) = false]; - int64 voting_power = 3; - int64 proposer_priority = 4; -} - -message SimpleValidator { - tendermint.crypto.PublicKey pub_key = 1; - int64 voting_power = 2; -} diff --git a/thirdParty/proto/tendermint/version/types.proto b/thirdParty/proto/tendermint/version/types.proto deleted file mode 100644 index 6061868bd..000000000 --- a/thirdParty/proto/tendermint/version/types.proto +++ /dev/null @@ -1,24 +0,0 @@ -syntax = "proto3"; -package tendermint.version; - -option go_package = "github.com/tendermint/tendermint/proto/tendermint/version"; - -import "gogoproto/gogo.proto"; - -// App includes the protocol and software version for the application. -// This information is included in ResponseInfo. The App.Protocol can be -// updated in ResponseEndBlock. -message App { - uint64 protocol = 1; - string software = 2; -} - -// Consensus captures the consensus rules for processing a block in the blockchain, -// including all blockchain data structures and the rules of the application's -// state transition machine. -message Consensus { - option (gogoproto.equal) = true; - - uint64 block = 1; - uint64 app = 2; -} diff --git a/utilities/codec.go b/utilities/codec.go deleted file mode 100644 index 17cfc1dee..000000000 --- a/utilities/codec.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors -// SPDX-License-Identifier: Apache-2.0 - -package utilities - -import ( - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/AssetMantle/modules/schema/data" - baseData "github.com/AssetMantle/modules/schema/data/base" - "github.com/AssetMantle/modules/schema/helpers" -) - -func MakeModuleCode(keyPrototype func() helpers.Key, mappablePrototype func() helpers.Mappable) *codec.LegacyAmino { - Codec := codec.NewLegacyAmino() - keyPrototype().RegisterCodec(Codec) - mappablePrototype().RegisterCodec(Codec) - RegisterCodec(Codec) - Codec.Seal() - - return Codec -} - -func MakeMessageCodec(messagePrototype func() helpers.Message) *codec.LegacyAmino { - Codec := codec.NewLegacyAmino() - messagePrototype().RegisterCodec(Codec) - RegisterCodec(Codec) - Codec.Seal() - - return Codec -} - -func RegisterCodec(codec *codec.LegacyAmino) { - - data.RegisterCodec(codec) - baseData.RegisterCodec(codec) - // - // documents.RegisterCodec(codec) - // baseDocuments.RegisterCodec(codec) - // - // errors.RegisterCodec(codec) - // - // helpers.RegisterCodec(codec) - // - // ids.RegisterCodec(codec) - // baseIDs.RegisterCodec(codec) - // - // lists.RegisterCodec(codec) - // baseLists.RegisterCodec(codec) - // - // parameters.RegisterCodec(codec) - // baseParameters.RegisterCodec(codec) - // - // properties.RegisterCodec(codec) - // baseProperties.RegisterCodec(codec) - // - // qualified.RegisterCodec(codec) - // baseQualified.RegisterCodec(codec) - // - // traits.RegisterCodec(codec) - // - // typesSchema.RegisterCodec(codec) - // baseTypes.RegisterCodec(codec) -} diff --git a/utilities/codec/concrete.go b/utilities/codec/concrete.go new file mode 100644 index 000000000..30f12beb0 --- /dev/null +++ b/utilities/codec/concrete.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package codec + +import ( + "reflect" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func RegisterModuleConcrete(codec *codec.Codec, o interface{}) { + codec.RegisterConcrete(o, reflect.TypeOf(o).PkgPath()+"/"+reflect.TypeOf(o).Name(), nil) +} diff --git a/utilities/codec/concrete_test.go b/utilities/codec/concrete_test.go new file mode 100644 index 000000000..952b62018 --- /dev/null +++ b/utilities/codec/concrete_test.go @@ -0,0 +1,31 @@ +package codec + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" +) + +func TestRegisterModuleConcrete(t *testing.T) { + type args struct { + codec *codec.Codec + o interface{} + } + tests := []struct { + name string + args args + }{ + { + name: "positive", + args: args{ + codec: codec.New(), + o: args{}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + RegisterModuleConcrete(tt.args.codec, tt.args.o) + }) + } +} diff --git a/utilities/cuckoo/DemoStruct.go b/utilities/cuckoo/DemoStruct.go deleted file mode 100644 index 62803c250..000000000 --- a/utilities/cuckoo/DemoStruct.go +++ /dev/null @@ -1,11 +0,0 @@ -package cuckoo - -type ID struct { - IDString string `json:"idString"` -} - -func NewID(idString string) *ID { - return &ID{ - IDString: idString, - } -} diff --git a/utilities/cuckoo/filter.go b/utilities/cuckoo/filter.go new file mode 100644 index 000000000..00302f8a9 --- /dev/null +++ b/utilities/cuckoo/filter.go @@ -0,0 +1,171 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package cuckoo + +import ( + "bytes" + "crypto/sha256" + "encoding/binary" + "errors" + "math" + "math/rand" +) + +type bucket []fingerprint +type fingerprint []byte + +// Cuckoo https://www.pdl.cmu.edu/PDL-FTP/FS/cuckoo-conext2014.pdf +type Cuckoo struct { + buckets []bucket + numBuckets uint // buckets + entriesPerBucket uint // entries per bucket + fingerprintLength uint // fingerprint length + n uint // filter capacity (rename cap?) + retries int // how many times do we try to move items around? +} + +func NewCuckoo(numItems uint, entriesPerBucket uint, retries int, falsePositiveRate float64) *Cuckoo { + fingerprintLength := getFingerprintLength(entriesPerBucket, falsePositiveRate) + numBuckets := nextPower(numItems / fingerprintLength * 8) + buckets := make([]bucket, numBuckets) + + for i := uint(0); i < numBuckets; i++ { + buckets[i] = make(bucket, entriesPerBucket) + } + + return &Cuckoo{ + buckets: buckets, + numBuckets: numBuckets, + entriesPerBucket: entriesPerBucket, + fingerprintLength: fingerprintLength, + n: numItems, + retries: retries, + } +} + +// Delete delete the fingerprint from the cuckoo filter +func (c *Cuckoo) Delete(needle string) { + i1, i2, f := c.hashes(needle) + // try to remove from f1 + b1 := c.buckets[i1%c.numBuckets] + if ind, ok := b1.Contains(f); ok { + b1[ind] = nil + return + } + + b2 := c.buckets[i2%c.numBuckets] + if ind, ok := b2.Contains(f); ok { + b2[ind] = nil + return + } +} + +// Lookup find needle in the cuckoo filter +func (c *Cuckoo) Lookup(needle string) bool { + i1, i2, f := c.hashes(needle) + _, b1 := c.buckets[i1%c.numBuckets].Contains(f) + _, b2 := c.buckets[i2%c.numBuckets].Contains(f) + + return b1 || b2 +} + +func (b bucket) Contains(f fingerprint) (int, bool) { + for i, x := range b { + if bytes.Equal(x, f) { + return i, true + } + } + + return -1, false +} + +func (c *Cuckoo) Insert(input string) error { + i1, i2, f := c.hashes(input) + // bucket one + b1 := c.buckets[i1%c.numBuckets] + if i, err := b1.nextIndex(); err == nil { + b1[i] = f + return nil + } + + // bucket two + b2 := c.buckets[i2%c.numBuckets] + if i, err := b2.nextIndex(); err == nil { + b2[i] = f + return nil + } + + // else we need to start relocating items + i := i1 + for r := 0; r < c.retries; r++ { + index := i % c.numBuckets + entryIndex := rand.Intn(int(c.entriesPerBucket)) //nolint:gosec + // swap + f, c.buckets[index][entryIndex] = c.buckets[index][entryIndex], f + + i ^= uint(binary.BigEndian.Uint32(Hash(f))) + b := c.buckets[i%c.numBuckets] + + if idx, err := b.nextIndex(); err == nil { + b[idx] = f + + return nil + } + } + + return errors.New("bucket full") +} + +// nextIndex returns the next index for entry, or an error if the bucket is full +func (b bucket) nextIndex() (int, error) { + for i, f := range b { + if f == nil { + return i, nil + } + } + + return -1, errors.New("bucket full") +} + +// hashes returns h1, h2 and the fingerprint +func (c *Cuckoo) hashes(data string) (uint, uint, fingerprint) { + h := Hash([]byte(data)) + f := h[0:c.fingerprintLength] + i1 := uint(binary.BigEndian.Uint32(h)) + i2 := i1 ^ uint(binary.BigEndian.Uint32(Hash(f))) + + return i1, i2, f +} + +func Hash(data []byte) []byte { + shaHash := sha256.New() + shaHash.Write(data) + hash := shaHash.Sum(nil) + + return hash +} + +func getFingerprintLength(b uint, e float64) uint { + f := uint(math.Ceil(math.Log(2 * float64(b) / e))) + f /= 8 + + if f < 1 { + return 1 + } + + return f +} + +func nextPower(i uint) uint { + i-- + i |= i >> 1 + i |= i >> 2 + i |= i >> 4 + i |= i >> 8 + i |= i >> 16 + i |= i >> 32 + i++ + + return i +} diff --git a/utilities/cuckoo/filter_test.go b/utilities/cuckoo/filter_test.go new file mode 100644 index 000000000..a6fbbbf3a --- /dev/null +++ b/utilities/cuckoo/filter_test.go @@ -0,0 +1,99 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package cuckoo + +import ( + "fmt" + "math/rand" + "testing" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/tendermint/tendermint/crypto" +) + +var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") + +var numData = 32 +var fpRate = 0.0001 +var retries = 500 +var entriesPerBucket = uint(2) + +var testFPRandomData = numData * 100 +var simulations = 1 + +func TestCuckoo(t *testing.T) { + totalFPs := 0 + numErrors := 0 + totalNegatives := 0 + c := NewCuckoo(uint(numData), entriesPerBucket, retries, fpRate) + fmt.Println("entriesPerBucket:", c.entriesPerBucket) + fmt.Println("numBuckets:", c.numBuckets) + fmt.Println("fingerprintLength:", c.fingerprintLength) + fmt.Println("numItems:", c.n) + for i := 0; i < simulations; i++ { + fp, allNegatives, errs := simulate() + totalFPs = totalFPs + fp + totalNegatives = totalNegatives + allNegatives + numErrors = numErrors + errs + } + fmt.Println("\nSimulation Result (Total):", simulations, "total random data tested per simulation:", testFPRandomData) + fmt.Println("total false positive:", totalFPs) + fmt.Println("total negatives:", totalNegatives) + fmt.Println("total errors:", numErrors) +} + +func simulate() (int, int, int) { + data := generateData(numData) + c := NewCuckoo(uint(numData), entriesPerBucket, retries, fpRate) + + insertMap := make(map[string]bool) + full := 0 + + for _, v := range data { + err := c.Insert(v) + if err == nil { + insertMap[v] = true + } else { + full++ + } + } + + allNegatives := 0 + for _, v := range data { + ok := c.Lookup(v) + if !ok { + // all should be negative + allNegatives++ + } + } + + falsePositives := 0 + for i := 0; i < testFPRandomData; i++ { + + ok := c.Lookup(randStringRunes(5)) // strconv.Itoa(i)) + if ok { + // all should be negative + falsePositives++ + } + } + return falsePositives, allNegatives, full +} + +func randStringRunes(n int) string { + b := make([]rune, n) + random := rand.New(rand.NewSource(time.Now().UnixNano())) + for i := range b { + b[i] = letterRunes[random.Intn(len(letterRunes))] + } + return string(b) +} + +func generateData(length int) []string { + result := make([]string, length) + for i := 0; i < length; i++ { + result[i] = sdk.AccAddress(crypto.AddressHash([]byte(randStringRunes(45)))).String() + } + return result +} diff --git a/utilities/helpers/string.go b/utilities/helpers/string.go deleted file mode 100644 index a25364a90..000000000 --- a/utilities/helpers/string.go +++ /dev/null @@ -1,16 +0,0 @@ -package helpers - -import ( - "strings" - - "github.com/AssetMantle/modules/schema/lists/constants" -) - -// TODO write testcase for empty and singular input -func JoinListStrings(listStrings ...string) string { - return strings.Join(listStrings, constants.ListStringSeparator) -} - -func SplitListString(listString string) []string { - return strings.Split(listString, constants.ListStringSeparator) -} diff --git a/utilities/module/codec.go b/utilities/module/codec.go new file mode 100644 index 000000000..e3958c613 --- /dev/null +++ b/utilities/module/codec.go @@ -0,0 +1,21 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package module + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" +) + +func RegisterCodec(keyPrototype func() helpers.Key, mappablePrototype func() helpers.Mappable) *codec.Codec { + Codec := codec.New() + keyPrototype().RegisterCodec(Codec) + mappablePrototype().RegisterCodec(Codec) + schema.RegisterCodec(Codec) + Codec.Seal() + + return Codec +} diff --git a/utilities/module/codec_test.go b/utilities/module/codec_test.go new file mode 100644 index 000000000..849cc8367 --- /dev/null +++ b/utilities/module/codec_test.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package module + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRegisterCodec(t *testing.T) { + require.Panics(t, func() { + require.Equal(t, RegisterCodec(nil, nil), nil) + }) +} diff --git a/utilities/property/duplicate.go b/utilities/property/duplicate.go new file mode 100644 index 000000000..1e9e9abfe --- /dev/null +++ b/utilities/property/duplicate.go @@ -0,0 +1,23 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package property + +import ( + "github.com/AssetMantle/modules/schema/ids" + "github.com/AssetMantle/modules/schema/properties" +) + +func Duplicate(propertyList []properties.Property) bool { + propertyIDMap := map[ids.ID]bool{} + + for _, property := range propertyList { + if _, ok := propertyIDMap[property.GetID()]; ok { + return true + } + + propertyIDMap[property.GetID()] = true + } + + return false +} diff --git a/utilities/property/duplicate_test.go b/utilities/property/duplicate_test.go new file mode 100644 index 000000000..7041cf424 --- /dev/null +++ b/utilities/property/duplicate_test.go @@ -0,0 +1,40 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package property + +import ( + "testing" + + baseData "github.com/AssetMantle/modules/schema/data/base" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/schema/properties" + baseProperties "github.com/AssetMantle/modules/schema/properties/base" +) + +func TestDuplicate(t *testing.T) { + type args struct { + propertyList []properties.Property + } + tests := []struct { + name string + args args + want bool + }{ + {"Positive Case, Unique PropertyList", args{propertyList: []properties.Property{baseProperties.NewMesaProperty(baseIDs.NewStringID("a"), baseData.NewStringData("factA")), + baseProperties.NewMesaProperty(baseIDs.NewStringID("b"), baseData.NewStringData("factB")), + baseProperties.NewMesaProperty(baseIDs.NewStringID("c"), baseData.NewStringData("factC")), + baseProperties.NewMesaProperty(baseIDs.NewStringID("d"), baseData.NewStringData("factD"))}}, false}, + {"Negative Case, DuplicateExists", args{propertyList: []properties.Property{baseProperties.NewMesaProperty(baseIDs.NewStringID("a"), baseData.NewStringData("factA")), + baseProperties.NewMesaProperty(baseIDs.NewStringID("b"), baseData.NewStringData("factB")), + baseProperties.NewMesaProperty(baseIDs.NewStringID("c"), baseData.NewStringData("factC")), + baseProperties.NewMesaProperty(baseIDs.NewStringID("a"), baseData.NewStringData("factD"))}}, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Duplicate(tt.args.propertyList); got != tt.want { + t.Errorf("Duplicate() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/utilities/random/bool.go b/utilities/random/bool.go new file mode 100644 index 000000000..39ab6b1b0 --- /dev/null +++ b/utilities/random/bool.go @@ -0,0 +1,12 @@ +package random + +import ( + "math" + "math/rand" + "time" +) + +func GenerateRandomBool() bool { + rand.Seed(time.Now().UnixNano()) + return rand.Intn(math.MaxInt)%2 == 0 +} diff --git a/utilities/random/id.go b/utilities/random/id.go new file mode 100644 index 000000000..c5ae3f84f --- /dev/null +++ b/utilities/random/id.go @@ -0,0 +1,32 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package random + +import ( + "crypto/rand" + "math/big" + "strconv" + "strings" + "sync/atomic" + "time" +) + +// counter is a counter that adds when each time a function is called +var counter int64 + +// GenerateUniqueIdentifier is a random unique ID generator, output is a string. +// Warning: Non-deterministic, not to used to generate blockchain state, for testing and client utility only +func GenerateUniqueIdentifier(prefix ...string) string { + randomNumber, err := rand.Int(rand.Reader, big.NewInt(89999)) + if err != nil { + panic(err) + } + + atomic.AddInt64(&counter, 1) + + return strings.Join(prefix, "") + + strconv.Itoa(10000+int(counter)%89999) + + strconv.Itoa(10000000+int(time.Now().UnixNano())%89999999) + + strconv.FormatInt(10000+randomNumber.Int64(), 10) +} diff --git a/utilities/rest/keys/add/handler.go b/utilities/rest/keys/add/handler.go new file mode 100644 index 000000000..e4ea62512 --- /dev/null +++ b/utilities/rest/keys/add/handler.go @@ -0,0 +1,92 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package add + +import ( + "fmt" + "net/http" + "strings" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/keys" + + cryptoKeys "github.com/cosmos/cosmos-sdk/crypto/keys" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/rest" + "github.com/gorilla/mux" + "github.com/spf13/viper" +) + +func handler(cliContext context.CLIContext) http.HandlerFunc { + return func(responseWriter http.ResponseWriter, httpRequest *http.Request) { + var request request + if !rest.ReadRESTReq(responseWriter, httpRequest, cliContext.Codec, &request) { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, "") + return + } + + err := request.Validate() + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) + return + } + + keyring, err := cryptoKeys.NewKeyring(sdkTypes.KeyringServiceName(), viper.GetString(flags.FlagKeyringBackend), viper.GetString(flags.FlagHome), strings.NewReader(keys.DefaultKeyPass)) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusInternalServerError, err.Error()) + return + } + + _, err = keyring.Get(request.Name) + if err == nil { + rest.WriteErrorResponse(responseWriter, http.StatusInternalServerError, fmt.Sprintf("Account for keyname %v already exists", request.Name)) + return + } + + if request.Mnemonic != "" && !bip39.IsMnemonicValid(request.Mnemonic) { + rest.WriteErrorResponse(responseWriter, http.StatusInternalServerError, "invalid mnemonic") + return + } + + if request.Mnemonic == "" { + const mnemonicEntropySize = 256 + + var entropySeed []byte + entropySeed, err = bip39.NewEntropy(mnemonicEntropySize) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusInternalServerError, err.Error()) + return + } + + request.Mnemonic, err = bip39.NewMnemonic(entropySeed) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusInternalServerError, err.Error()) + return + } + } + + var info cryptoKeys.Info + + info, err = keyring.CreateAccount(request.Name, request.Mnemonic, cryptoKeys.DefaultBIP39Passphrase, keys.DefaultKeyPass, sdkTypes.FullFundraiserPath, cryptoKeys.Secp256k1) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusInternalServerError, err.Error()) + return + } + + var keyOutput cryptoKeys.KeyOutput + keyOutput, err = cryptoKeys.Bech32KeyOutput(info) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusInternalServerError, err.Error()) + return + } + + keyOutput.Mnemonic = request.Mnemonic + rest.PostProcessResponse(responseWriter, cliContext, newResponse(keyOutput, nil)) + } +} + +func RegisterRESTRoutes(cliContext context.CLIContext, router *mux.Router) { + router.HandleFunc("/keys/add", handler(cliContext)).Methods("POST") +} diff --git a/utilities/rest/keys/add/handler_test.go b/utilities/rest/keys/add/handler_test.go new file mode 100644 index 000000000..8441e7829 --- /dev/null +++ b/utilities/rest/keys/add/handler_test.go @@ -0,0 +1,144 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package add + +import ( + "bytes" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys" + cryptoKeys "github.com/cosmos/cosmos-sdk/crypto/keys" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/rest" + "github.com/gorilla/mux" + "github.com/spf13/viper" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema" +) + +func TestHandler(t *testing.T) { + Codec := codec.New() + schema.RegisterCodec(Codec) + Codec.RegisterConcrete(request{}, "request", nil) + Codec.RegisterConcrete(response{}, "response", nil) + + clientContext := context.NewCLIContext().WithCodec(Codec) + + handler := handler(clientContext) + + viper.Set(flags.FlagKeyringBackend, keys.BackendTest) + viper.Set(flags.FlagHome, t.TempDir()) + + keyring, err := cryptoKeys.NewKeyring(sdk.KeyringServiceName(), keys.BackendTest, t.TempDir(), strings.NewReader("")) + require.NoError(t, err) + + router := mux.NewRouter() + RegisterRESTRoutes(clientContext, router) + + t.Cleanup(func() { + _ = keyring.Delete("keyName1", "", true) + _ = keyring.Delete("keyName2", "", true) + _ = keyring.Delete("keyName3", "", true) + }) + + getResponse := func(responseBytes []byte) response { + var Response rest.ResponseWithHeight + + innerErr := Codec.UnmarshalJSON(responseBytes, &Response) + require.Nil(t, innerErr) + + var ResponseValue response + innerErr = Codec.UnmarshalJSON(Response.Result, &ResponseValue) + require.Nil(t, innerErr) + + return ResponseValue + } + + // create account without mnemonic + var requestBody1 []byte + requestBody1, err = Codec.MarshalJSON(request{ + Name: "testKey1", + }) + require.Nil(t, err) + + var testRequest1 *http.Request + testRequest1, err = http.NewRequest("POST", "/keys/add", bytes.NewBuffer(requestBody1)) + require.Nil(t, err) + + responseRecorder := httptest.NewRecorder() + handler.ServeHTTP(responseRecorder, testRequest1) + require.Equal(t, http.StatusOK, responseRecorder.Code) + + response1 := getResponse(responseRecorder.Body.Bytes()) + require.Nil(t, response1.Error) + require.Equal(t, true, response1.Success) + + // create account with mnemonic + var requestBody2 []byte + requestBody2, err = Codec.MarshalJSON(request{ + Name: "testKey2", + Mnemonic: "wage thunder live sense resemble foil apple course spin horse glass mansion midnight laundry acoustic rhythm loan scale talent push green direct brick please", + }) + require.Nil(t, err) + + var testRequest2 *http.Request + testRequest2, err = http.NewRequest("POST", "/keys/add", bytes.NewBuffer(requestBody2)) + require.Nil(t, err) + + responseRecorder = httptest.NewRecorder() + handler.ServeHTTP(responseRecorder, testRequest2) + require.Equal(t, responseRecorder.Code, http.StatusOK) + + response2 := getResponse(responseRecorder.Body.Bytes()) + require.Nil(t, response2.Error) + require.Equal(t, true, response2.Success) + + // invalid mnemonic + var requestBody3 []byte + requestBody3, err = Codec.MarshalJSON(request{ + Name: "testKey3", + Mnemonic: "wage brick please", + }) + require.Nil(t, err) + + var testRequest3 *http.Request + testRequest3, err = http.NewRequest("POST", "/keys/add", bytes.NewBuffer(requestBody3)) + require.Nil(t, err) + + responseRecorder = httptest.NewRecorder() + handler.ServeHTTP(responseRecorder, testRequest3) + require.Equal(t, http.StatusInternalServerError, responseRecorder.Code) + require.Equal(t, `{"error":"invalid mnemonic"}`, responseRecorder.Body.String()) + + // invalid request + testRequest4, err := http.NewRequest("POST", "/keys/add", bytes.NewBuffer([]byte{})) + require.Nil(t, err) + + responseRecorder = httptest.NewRecorder() + handler.ServeHTTP(responseRecorder, testRequest4) + require.Equal(t, http.StatusBadRequest, responseRecorder.Code) + + // Retry adding same account + var requestBody5 []byte + requestBody5, err = Codec.MarshalJSON(request{ + Name: "testKey1", + }) + require.Nil(t, err) + + var testRequest5 *http.Request + testRequest5, err = http.NewRequest("POST", "/keys/add", bytes.NewBuffer(requestBody5)) + require.Nil(t, err) + + responseRecorder = httptest.NewRecorder() + handler.ServeHTTP(responseRecorder, testRequest5) + require.Equal(t, http.StatusInternalServerError, responseRecorder.Code) + require.Equal(t, `{"error":"Account for keyname testKey1 already exists"}`, responseRecorder.Body.String()) +} diff --git a/utilities/rest/keys/add/request.go b/utilities/rest/keys/add/request.go new file mode 100644 index 000000000..75a0dc87f --- /dev/null +++ b/utilities/rest/keys/add/request.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package add + +import ( + "github.com/asaskevich/govalidator" + + "github.com/AssetMantle/modules/schema/helpers" +) + +type request struct { + Name string `json:"name" valid:"required~required field to missing, matches(.+?)~invalid field name"` + Mnemonic string `json:"mnemonic" valid:"optional"` +} + +var _ helpers.Request = request{} + +func (request request) Validate() error { + _, err := govalidator.ValidateStruct(request) + return err +} diff --git a/utilities/rest/keys/add/request_test.go b/utilities/rest/keys/add/request_test.go new file mode 100644 index 000000000..7d8032a5e --- /dev/null +++ b/utilities/rest/keys/add/request_test.go @@ -0,0 +1,14 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package add + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func Test_Add_Request(t *testing.T) { + require.Equal(t, nil, request{Name: "name", Mnemonic: "mnemonic"}.Validate()) +} diff --git a/utilities/rest/keys/add/response.go b/utilities/rest/keys/add/response.go index a814d79e0..65272b2fa 100644 --- a/utilities/rest/keys/add/response.go +++ b/utilities/rest/keys/add/response.go @@ -1,19 +1,18 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package add import ( - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/cosmos/cosmos-sdk/crypto/keys" + + "github.com/AssetMantle/modules/schema/helpers" ) type response struct { - Success bool `json:"success"` - Error error `json:"error"` - KeyOutput keyring.KeyOutput `json:"keyOutput"` + Success bool `json:"success"` + Error error `json:"error"` + KeyOutput keys.KeyOutput `json:"keyOutput"` } var _ helpers.Response = response{} @@ -24,7 +23,7 @@ func (response response) IsSuccessful() bool { func (response response) GetError() error { return response.Error } -func newResponse(keyOutput keyring.KeyOutput, error error) helpers.Response { +func newResponse(keyOutput keys.KeyOutput, error error) helpers.Response { success := true if error != nil { success = false diff --git a/utilities/rest/keys/add/response_test.go b/utilities/rest/keys/add/response_test.go index 840e6588f..0c13d4030 100644 --- a/utilities/rest/keys/add/response_test.go +++ b/utilities/rest/keys/add/response_test.go @@ -1,25 +1,24 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package add import ( - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/persistenceOne/persistenceSDK/constants/errors" - "github.com/stretchr/testify/require" "testing" + + "github.com/cosmos/cosmos-sdk/crypto/keys" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" ) func Test_Add_Response(t *testing.T) { - - testKeyOutput := keyring.NewKeyOutput("name", "keyType", "address", "pubkey") + testKeyOutput := keys.NewKeyOutput("name", "keyType", "address", "pubkey") testResponse := newResponse(testKeyOutput, nil) require.Equal(t, response{Success: true, Error: nil, KeyOutput: testKeyOutput}, testResponse) require.Equal(t, true, testResponse.IsSuccessful()) require.Equal(t, nil, testResponse.GetError()) - testResponse2 := newResponse(testKeyOutput, errors.IncorrectFormat) + testResponse2 := newResponse(testKeyOutput, constants.IncorrectFormat) require.Equal(t, false, testResponse2.IsSuccessful()) - require.Equal(t, errors.IncorrectFormat, testResponse2.GetError()) + require.Equal(t, constants.IncorrectFormat, testResponse2.GetError()) } diff --git a/utilities/rest/queuing/configurations.go b/utilities/rest/queuing/configurations.go new file mode 100755 index 000000000..ee7995304 --- /dev/null +++ b/utilities/rest/queuing/configurations.go @@ -0,0 +1,26 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +import ( + "os" + "time" +) + +// sleepTimer : the time the kafka messages are to be taken in +const sleepTimer = time.Duration(1000000000) + +// sleepRoutine : the time the kafka messages are to be taken in +const sleepRoutine = time.Duration(2500000000) + +// defaultCLIHome : is the home path +var defaultCLIHome = os.ExpandEnv("$HOME/.kafka") + +const partition = int32(0) +const offset = int64(0) + +// topics : is list of topics +var topics = []string{ + "Topic", +} diff --git a/utilities/rest/queuing/init.go b/utilities/rest/queuing/init.go new file mode 100644 index 000000000..e6d73ae81 --- /dev/null +++ b/utilities/rest/queuing/init.go @@ -0,0 +1,22 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +import ( + "time" + + "github.com/cosmos/cosmos-sdk/client/context" +) + +func InitializeKafka(nodeList []string, cliContext context.CLIContext) { + KafkaState = *NewKafkaState(nodeList) + if KafkaState.IsEnabled { + go func() { + for { + kafkaConsumerMessages(cliContext) + time.Sleep(sleepRoutine) + } + }() + } +} diff --git a/utilities/rest/queuing/kafkaAdmin.go b/utilities/rest/queuing/kafkaAdmin.go new file mode 100755 index 000000000..0e13fef11 --- /dev/null +++ b/utilities/rest/queuing/kafkaAdmin.go @@ -0,0 +1,21 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +import ( + "github.com/Shopify/sarama" +) + +// kafkaAdmin : is admin to create topics +func kafkaAdmin(kafkaNodes []string) sarama.ClusterAdmin { + config := sarama.NewConfig() + config.Version = sarama.V0_11_0_0 // hardcoded + + admin, err := sarama.NewClusterAdmin(kafkaNodes, config) + if err != nil { + panic(err) + } + + return admin +} diff --git a/utilities/rest/queuing/kafkaConsumer.go b/utilities/rest/queuing/kafkaConsumer.go new file mode 100755 index 000000000..a0da3c19f --- /dev/null +++ b/utilities/rest/queuing/kafkaConsumer.go @@ -0,0 +1,49 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +import ( + "github.com/Shopify/sarama" + "github.com/cosmos/cosmos-sdk/codec" +) + +// newConsumer : is a consumer which is needed to create child consumers to consume topics +func newConsumer(kafkaNodes []string) sarama.Consumer { + config := sarama.NewConfig() + + consumer, err := sarama.NewConsumer(kafkaNodes, config) + if err != nil { + panic(err) + } + + return consumer +} + +// partitionConsumers : is a child consumer +func partitionConsumers(consumer sarama.Consumer, topic string) sarama.PartitionConsumer { + // partition and offset defined in configurations.go + partitionConsumer, err := consumer.ConsumePartition(topic, partition, offset) + if err != nil { + panic(err) + } + + return partitionConsumer +} + +// kafkaTopicConsumer : Takes a consumer and makes it consume a topic message at a time +func kafkaTopicConsumer(topic string, consumers map[string]sarama.PartitionConsumer, cdc *codec.Codec) kafkaMsg { + partitionConsumer := consumers[topic] + + if len(partitionConsumer.Messages()) == 0 { + return kafkaMsg{Msg: nil} + } + + var consumedKafkaMsg kafkaMsg + err := cdc.UnmarshalJSON((<-partitionConsumer.Messages()).Value, &consumedKafkaMsg) + if err != nil { + panic(err) + } + + return consumedKafkaMsg +} diff --git a/utilities/rest/queuing/kafkaConsumerMsgs.go b/utilities/rest/queuing/kafkaConsumerMsgs.go new file mode 100755 index 000000000..00ee7da78 --- /dev/null +++ b/utilities/rest/queuing/kafkaConsumerMsgs.go @@ -0,0 +1,60 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +import ( + "time" + + "github.com/cosmos/cosmos-sdk/client/context" +) + +// kafkaConsumerMessages : messages to consume 5-second delay +func kafkaConsumerMessages(cliCtx context.CLIContext) { + quit := make(chan bool) + + var kafkaMsgList []kafkaMsg + + go func() { + var msg kafkaMsg + + for { + select { + case <-quit: + return + default: + msg = kafkaTopicConsumer("Topic", KafkaState.Consumers, cliCtx.Codec) + if msg.Msg != nil { + kafkaMsgList = append(kafkaMsgList, msg) + } + } + } + }() + + time.Sleep(sleepTimer) + quit <- true + + if len(kafkaMsgList) == 0 { + return + } + + output, err := signAndBroadcastMultiple(kafkaMsgList, cliCtx) + if err != nil { + jsonError, e := cliCtx.Codec.MarshalJSON(struct { + Error string `json:"error"` + }{Error: err.Error()}) + if e != nil { + panic(e) + } + + for _, kafkaMsg := range kafkaMsgList { + addResponseToDB(kafkaMsg.TicketID, jsonError, KafkaState.KafkaDB, cliCtx.Codec) + } + + return + } + + for _, kafkaMsg := range kafkaMsgList { + addResponseToDB(kafkaMsg.TicketID, output, KafkaState.KafkaDB, cliCtx.Codec) + } +} diff --git a/utilities/rest/queuing/kafkaConsumer_test.go b/utilities/rest/queuing/kafkaConsumer_test.go new file mode 100644 index 000000000..109ec1b18 --- /dev/null +++ b/utilities/rest/queuing/kafkaConsumer_test.go @@ -0,0 +1,61 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +import ( + "testing" + + "github.com/Shopify/sarama" + "github.com/cosmos/cosmos-sdk/codec" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema" +) + +func TestKafkaTopicConsumer(t *testing.T) { + testConsumers := []string{"testConsumers"} + + var Codec = codec.New() + + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + + require.Panics(t, func() { + testKafkaState := NewKafkaState(testConsumers) + partitionConsumer := testKafkaState.Consumers["Topic"] + + var kafkaStore kafkaMsg + if len(partitionConsumer.Messages()) == 0 { + kafkaStore = kafkaMsg{Msg: nil} + } + + kafkaMsg := <-partitionConsumer.Messages() + + err := Codec.UnmarshalJSON(kafkaMsg.Value, &kafkaStore) + if err != nil { + panic(err) + } + + require.Equal(t, kafkaTopicConsumer("Topic", testKafkaState.Consumers, Codec), kafkaStore) + }) +} + +func TestNewConsumer(t *testing.T) { + consumers := []string{"testConsumers"} + config := sarama.NewConfig() + + consumer, _ := sarama.NewConsumer(consumers, config) + + // TODO: Add test cases. + // require.Nil(t, err, "should not happened. err %v", err) + + require.Panics(t, func() { + require.Equal(t, newConsumer(consumers), consumer) + }) +} diff --git a/utilities/rest/queuing/kafkaDB.go b/utilities/rest/queuing/kafkaDB.go new file mode 100755 index 000000000..4341434ba --- /dev/null +++ b/utilities/rest/queuing/kafkaDB.go @@ -0,0 +1,84 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +import ( + "fmt" + "net/http" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/gorilla/mux" + dbm "github.com/tendermint/tm-db" +) + +// setTicketIDtoDB : initiates TicketID in Database +func setTicketIDtoDB(ticket TicketID, kafkaDB *dbm.GoLevelDB, cdc *codec.Codec, msg []byte) { + ticketID, err := cdc.MarshalJSON(ticket) + if err != nil { + panic(err) + } + + if err := kafkaDB.Set(ticketID, msg); err != nil { + panic(err) + } +} + +// addResponseToDB : Updates response to DB +func addResponseToDB(ticket TicketID, response []byte, kafkaDB *dbm.GoLevelDB, cdc *codec.Codec) { + ticketID, err := cdc.MarshalJSON(ticket) + if err != nil { + panic(err) + } + + err = kafkaDB.SetSync(ticketID, response) + if err != nil { + panic(err) + } +} + +// getResponseFromDB : gives the response from DB +func getResponseFromDB(ticket TicketID, kafkaDB *dbm.GoLevelDB, cdc *codec.Codec) []byte { + ticketID, err := cdc.MarshalJSON(ticket) + if err != nil { + panic(err) + } + + val, _ := kafkaDB.Get(ticketID) + + return val +} + +// queryDB : REST outputs info from DB +func queryDB(cdc *codec.Codec) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + + vars := mux.Vars(r) + + ticketIDBytes, err := cdc.MarshalJSON(vars["TicketID"]) + if err != nil { + panic(err) + } + + var response []byte + + check, _ := KafkaState.KafkaDB.Has(ticketIDBytes) + if check { + response = getResponseFromDB(TicketID(vars["TicketID"]), KafkaState.KafkaDB, cdc) + } else { + output, err := cdc.MarshalJSON("The ticket ID does not exist, it must have been deleted, Query the chain to know") + if err != nil { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(fmt.Sprintf("ticket ID does not exist. Error: %s", err.Error()))) + return + } + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write(output) + return + } + + w.WriteHeader(http.StatusAccepted) + _, _ = w.Write(response) + } +} diff --git a/utilities/rest/queuing/kafkaDB_test.go b/utilities/rest/queuing/kafkaDB_test.go new file mode 100644 index 000000000..5cc2b4e7d --- /dev/null +++ b/utilities/rest/queuing/kafkaDB_test.go @@ -0,0 +1,35 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/stretchr/testify/require" + dbm "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/schema" + baseIDs "github.com/AssetMantle/modules/schema/ids/base" + "github.com/AssetMantle/modules/utilities/random" +) + +func Test_Kafka_DB(t *testing.T) { + require.Panics(t, func() { + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + ticketID := TicketID(random.GenerateUniqueIdentifier("name")) + kafkaDB, _ := dbm.NewGoLevelDB("KafkaDB", defaultCLIHome) + setTicketIDtoDB(ticketID, kafkaDB, Codec, []byte{}) + addResponseToDB(ticketID, baseIDs.NewStringID("").Bytes(), kafkaDB, Codec) + require.Equal(t, baseIDs.NewStringID("").Bytes(), getResponseFromDB(ticketID, kafkaDB, Codec)) + }) +} diff --git a/utilities/rest/queuing/kafkaProducer.go b/utilities/rest/queuing/kafkaProducer.go new file mode 100755 index 000000000..081a6b94a --- /dev/null +++ b/utilities/rest/queuing/kafkaProducer.go @@ -0,0 +1,75 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +import ( + "github.com/Shopify/sarama" + + "github.com/cosmos/cosmos-sdk/codec" +) + +// newProducer is a producer to send messages to kafka +func newProducer(kafkaNodes []string) sarama.SyncProducer { + producer, err := sarama.NewSyncProducer(kafkaNodes, nil) + if err != nil { + panic(err) + } + + return producer +} + +// kafkaProducerDeliverMessage : delivers messages to kafka +func kafkaProducerDeliverMessage(kafkaMsg kafkaMsg, topic string, producer sarama.SyncProducer, codec *codec.Codec) error { + kafkaStoreBytes, err := codec.MarshalJSON(kafkaMsg) + if err != nil { + panic(err) + } + + sendMsg := sarama.ProducerMessage{ + Topic: topic, + Value: sarama.ByteEncoder(kafkaStoreBytes), + } + + _, _, err = producer.SendMessage(&sendMsg) + if err != nil { + return err + } + + return nil +} + +// SendToKafka : handles sending message to kafka +func SendToKafka(kafkaMsg kafkaMsg, codec *codec.Codec) []byte { + var jsonResponse []byte + + err := kafkaProducerDeliverMessage(kafkaMsg, "Topic", KafkaState.Producer, codec) + if err != nil { + jsonResponse, err = codec.MarshalJSON(struct { + Response string `json:"response"` + }{Response: "Something is up with kafka server, restart rest and kafka."}) + if err != nil { + panic(err) + } + + setTicketIDtoDB(kafkaMsg.TicketID, KafkaState.KafkaDB, codec, jsonResponse) + } else { + jsonResponse, err = codec.MarshalJSON(struct { + Error string `json:"error"` + }{Error: "Request in process, wait and try after some time"}) + if err != nil { + panic(err) + } + + setTicketIDtoDB(kafkaMsg.TicketID, KafkaState.KafkaDB, codec, jsonResponse) + } + + jsonResponse, err = codec.MarshalJSON(struct { + TicketID TicketID `json:"TicketID"` + }{TicketID: kafkaMsg.TicketID}) + if err != nil { + panic(err) + } + + return jsonResponse +} diff --git a/utilities/rest/queuing/kafkaProducer_test.go b/utilities/rest/queuing/kafkaProducer_test.go new file mode 100644 index 000000000..16c08b374 --- /dev/null +++ b/utilities/rest/queuing/kafkaProducer_test.go @@ -0,0 +1,50 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +import ( + "testing" + + "github.com/Shopify/sarama" + "github.com/cosmos/cosmos-sdk/codec" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema" +) + +func TestKafkaProducerDeliverMessage(t *testing.T) { + testProducer := []string{"testProducer"} + var Codec = codec.New() + require.Panics(t, func() { + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + + testKafkaMessage := kafkaMsg{Msg: nil} + + producer, _ := sarama.NewSyncProducer(testProducer, nil) + // TODO: Add test cases. + // require.Nil(t, err) + + require.Equal(t, kafkaProducerDeliverMessage(testKafkaMessage, "Topic", producer, Codec), nil) + }) + +} + +func TestNewProducer(t *testing.T) { + testProducer := []string{"testProducer"} + + producer, _ := sarama.NewSyncProducer(testProducer, nil) + + // TODO: Add test cases. + // require.Nil(t, err, "should not happened. err %v", err) + + require.Panics(t, func() { + require.Equal(t, newProducer(testProducer), producer) + }) +} diff --git a/utilities/rest/queuing/kafkaTypes.go b/utilities/rest/queuing/kafkaTypes.go new file mode 100755 index 000000000..c13011758 --- /dev/null +++ b/utilities/rest/queuing/kafkaTypes.go @@ -0,0 +1,129 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +import ( + "github.com/Shopify/sarama" + "github.com/cosmos/cosmos-sdk/client/context" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/rest" + dbm "github.com/tendermint/tm-db" +) + +// TicketID : is a type that implements string +type TicketID string + +// kafkaMsg : is a store that can be stored in kafka queues +type kafkaMsg struct { + Msg sdk.Msg `json:"msg"` + TicketID TicketID `json:"TicketID"` + BaseRequest rest.BaseReq `json:"base_req"` + KafkaCliCtx kafkaCliCtx `json:"kafkaCliCtx"` +} + +// NewKafkaMsgFromRest : makes a msg to send to kafka queue +func NewKafkaMsgFromRest(msg sdk.Msg, ticketID TicketID, baseRequest rest.BaseReq, cliCtx context.CLIContext) kafkaMsg { + kafkaCtx := kafkaCliCtx{ + OutputFormat: cliCtx.OutputFormat, + ChainID: cliCtx.ChainID, + Height: cliCtx.Height, + HomeDir: cliCtx.HomeDir, + NodeURI: cliCtx.NodeURI, + From: cliCtx.From, + TrustNode: cliCtx.TrustNode, + UseLedger: cliCtx.UseLedger, + BroadcastMode: cliCtx.BroadcastMode, + Simulate: cliCtx.Simulate, + GenerateOnly: cliCtx.GenerateOnly, + FromAddress: cliCtx.FromAddress, + FromName: cliCtx.FromName, + Indent: cliCtx.Indent, + SkipConfirm: cliCtx.SkipConfirm, + } + + // TODO return pointer + return kafkaMsg{ + Msg: msg, + TicketID: ticketID, + BaseRequest: baseRequest, + KafkaCliCtx: kafkaCtx, + } +} + +// cliCtxFromKafkaMsg : sets the transaction and cli contexts again to consume +func cliCtxFromKafkaMsg(kafkaMsg kafkaMsg, cliContext context.CLIContext) context.CLIContext { + cliContext.OutputFormat = kafkaMsg.KafkaCliCtx.OutputFormat + cliContext.ChainID = kafkaMsg.KafkaCliCtx.ChainID + cliContext.Height = kafkaMsg.KafkaCliCtx.Height + cliContext.HomeDir = kafkaMsg.KafkaCliCtx.HomeDir + cliContext.NodeURI = kafkaMsg.KafkaCliCtx.NodeURI + cliContext.From = kafkaMsg.KafkaCliCtx.From + cliContext.TrustNode = kafkaMsg.KafkaCliCtx.TrustNode + cliContext.UseLedger = kafkaMsg.KafkaCliCtx.UseLedger + cliContext.BroadcastMode = kafkaMsg.KafkaCliCtx.BroadcastMode + cliContext.Simulate = kafkaMsg.KafkaCliCtx.Simulate + cliContext.GenerateOnly = kafkaMsg.KafkaCliCtx.GenerateOnly + cliContext.FromAddress = kafkaMsg.KafkaCliCtx.FromAddress + cliContext.FromName = kafkaMsg.KafkaCliCtx.FromName + cliContext.Indent = kafkaMsg.KafkaCliCtx.Indent + cliContext.SkipConfirm = kafkaMsg.KafkaCliCtx.SkipConfirm + + return cliContext +} + +// kafkaCliCtx : client tx without codec +type kafkaCliCtx struct { + FromAddress sdk.AccAddress + OutputFormat string + ChainID string + HomeDir string + NodeURI string + From string + BroadcastMode string + FromName string + Height int64 + TrustNode bool + UseLedger bool + Simulate bool + GenerateOnly bool + Offline bool + Indent bool + SkipConfirm bool +} + +// kafkaState : is a struct showing the state of kafka +type kafkaState struct { + KafkaDB *dbm.GoLevelDB + Admin sarama.ClusterAdmin + Consumer sarama.Consumer + Consumers map[string]sarama.PartitionConsumer + Producer sarama.SyncProducer + Topics []string + IsEnabled bool +} + +// NewKafkaState : returns a kafka state +func NewKafkaState(nodeList []string) *kafkaState { + kafkaDB, _ := dbm.NewGoLevelDB("KafkaDB", defaultCLIHome) + admin := kafkaAdmin(nodeList) + producer := newProducer(nodeList) + consumer := newConsumer(nodeList) + + var consumers = make(map[string]sarama.PartitionConsumer) + + for _, topic := range topics { + partitionConsumer := partitionConsumers(consumer, topic) + consumers[topic] = partitionConsumer + } + + return &kafkaState{ + KafkaDB: kafkaDB, + Admin: admin, + Consumer: consumer, + Consumers: consumers, + Producer: producer, + Topics: topics, + IsEnabled: true, + } +} diff --git a/utilities/rest/queuing/kafkaTypes_test.go b/utilities/rest/queuing/kafkaTypes_test.go new file mode 100644 index 000000000..19450528b --- /dev/null +++ b/utilities/rest/queuing/kafkaTypes_test.go @@ -0,0 +1,58 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/rest" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/utilities/random" +) + +func Test_Kafka_Types(t *testing.T) { + + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + Codec.Seal() + cliContext := context.NewCLIContext().WithCodec(Codec) + + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} + + testMessage := sdkTypes.NewTestMsg() + + ticketID := TicketID(random.GenerateUniqueIdentifier("name")) + testKafkaMsg := NewKafkaMsgFromRest(testMessage, ticketID, testBaseReq, cliContext) + kafkaCliCtx := kafkaCliCtx{ + OutputFormat: cliContext.OutputFormat, + ChainID: cliContext.ChainID, + Height: cliContext.Height, + HomeDir: cliContext.HomeDir, + NodeURI: cliContext.NodeURI, + From: cliContext.From, + TrustNode: cliContext.TrustNode, + UseLedger: cliContext.UseLedger, + BroadcastMode: cliContext.BroadcastMode, + Simulate: cliContext.Simulate, + GenerateOnly: cliContext.GenerateOnly, + FromAddress: cliContext.FromAddress, + FromName: cliContext.FromName, + Indent: cliContext.Indent, + SkipConfirm: cliContext.SkipConfirm, + } + require.Equal(t, kafkaMsg{Msg: testMessage, TicketID: ticketID, BaseRequest: testBaseReq, KafkaCliCtx: kafkaCliCtx}, testKafkaMsg) + require.Equal(t, cliContext, cliCtxFromKafkaMsg(testKafkaMsg, cliContext)) + // require +} diff --git a/utilities/rest/queuing/kafka_test.go b/utilities/rest/queuing/kafka_test.go new file mode 100644 index 000000000..18f35660d --- /dev/null +++ b/utilities/rest/queuing/kafka_test.go @@ -0,0 +1,74 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/rest" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" + "github.com/AssetMantle/modules/utilities/random" +) + +type testMessage struct { + Name string `json:"name"` +} + +var _ sdkTypes.Msg = testMessage{} + +func (message testMessage) Route() string { return "testModule" } +func (message testMessage) Type() string { return "" } +func (message testMessage) ValidateBasic() error { + return nil +} +func (message testMessage) GetSignBytes() []byte { + return []byte{} +} +func (message testMessage) GetSigners() []sdkTypes.AccAddress { + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, _ := sdkTypes.AccAddressFromBech32(fromAddress) + return []sdkTypes.AccAddress{fromAccAddress} +} +func (testMessage) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, testMessage{}) +} + +func Test_Kafka(t *testing.T) { + + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) + codec.RegisterEvidences(Codec) + vesting.RegisterCodec(Codec) + + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + fromAccAddress, err := sdkTypes.AccAddressFromBech32(fromAddress) + require.Nil(t, err) + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test"} + ticketID := TicketID(random.GenerateUniqueIdentifier("ticket")) + kafkaPorts := []string{"localhost:9092"} + require.Panics(t, func() { + testKafkaState := NewKafkaState(kafkaPorts) + bank.RegisterCodec(Codec) + message := bank.NewMsgSend(fromAccAddress, fromAccAddress, sdkTypes.NewCoins(sdkTypes.NewCoin("stake", sdkTypes.NewInt(123)))) + cliContext := context.NewCLIContext().WithCodec(Codec) + + testKafkaMsg := NewKafkaMsgFromRest(message, ticketID, testBaseReq, cliContext) + SendToKafka(testKafkaMsg, Codec) + + kafkaMsg := kafkaTopicConsumer("Topic", testKafkaState.Consumers, Codec) + require.Equal(t, testKafkaMsg.TicketID, kafkaMsg.TicketID) + require.Equal(t, testKafkaMsg.BaseRequest, kafkaMsg.BaseRequest) + }) + +} diff --git a/utilities/rest/queuing/routes.go b/utilities/rest/queuing/routes.go index 06cf652fd..a69cd72e8 100644 --- a/utilities/rest/queuing/routes.go +++ b/utilities/rest/queuing/routes.go @@ -1,10 +1,13 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + package queuing import ( - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/gorilla/mux" ) -func RegisterRoutes(cliContext client.Context, router *mux.Router) { +func RegisterRoutes(cliContext context.CLIContext, router *mux.Router) { router.HandleFunc("/response/{TicketID}", queryDB(cliContext.Codec)).Methods("GET") } diff --git a/utilities/rest/queuing/signAndBroadcast.go b/utilities/rest/queuing/signAndBroadcast.go index bffeaab5a..885393386 100755 --- a/utilities/rest/queuing/signAndBroadcast.go +++ b/utilities/rest/queuing/signAndBroadcast.go @@ -1,14 +1,12 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package queuing import ( "strings" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/keys" cryptoKeys "github.com/cosmos/cosmos-sdk/crypto/keys" @@ -20,7 +18,7 @@ import ( "github.com/spf13/viper" ) -func signAndBroadcastMultiple(kafkaMsgList []kafkaMsg, cliContext client.Context) ([]byte, error) { +func signAndBroadcastMultiple(kafkaMsgList []kafkaMsg, cliContext context.CLIContext) ([]byte, error) { var stdTxs types.StdTx var txBytes []byte diff --git a/utilities/rest/queuing/state.go b/utilities/rest/queuing/state.go new file mode 100644 index 000000000..7ec9d71d3 --- /dev/null +++ b/utilities/rest/queuing/state.go @@ -0,0 +1,6 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package queuing + +var KafkaState kafkaState diff --git a/utilities/rest/queuing/utils.go b/utilities/rest/queuing/utils.go index 6231438f1..cb39e6b63 100755 --- a/utilities/rest/queuing/utils.go +++ b/utilities/rest/queuing/utils.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package queuing @@ -27,7 +25,7 @@ func parseGasAdjustment(s string) (float64, error) { return n, nil } -func simulationResponse(cdc *codec.LegacyAmino, gas uint64) ([]byte, error) { +func simulationResponse(cdc *codec.Codec, gas uint64) ([]byte, error) { gasEst := rest.GasEstimateResponse{GasEstimate: gas} resp, err := cdc.MarshalJSON(gasEst) diff --git a/utilities/rest/queuing/utils_test.go b/utilities/rest/queuing/utils_test.go index b5926309b..9f5fd4534 100644 --- a/utilities/rest/queuing/utils_test.go +++ b/utilities/rest/queuing/utils_test.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package queuing @@ -15,7 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/stretchr/testify/require" - "github.com/persistenceOne/persistenceSDK/schema" + "github.com/AssetMantle/modules/schema" ) func Test_Rest_Utils(t *testing.T) { @@ -31,10 +29,10 @@ func Test_Rest_Utils(t *testing.T) { require.Equal(t, 0.3, value3) require.Equal(t, nil, error3) - var Codec = codec.NewLegacyAmino() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + var Codec = codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) vesting.RegisterCodec(Codec) Codec.Seal() diff --git a/utilities/rest/sign/handler.go b/utilities/rest/sign/handler.go new file mode 100644 index 000000000..81e17f5cb --- /dev/null +++ b/utilities/rest/sign/handler.go @@ -0,0 +1,94 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package sign + +import ( + "bytes" + "fmt" + "net/http" + "strings" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/types/rest" + authClient "github.com/cosmos/cosmos-sdk/x/auth/client/utils" + "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/gorilla/mux" + "github.com/spf13/viper" +) + +func handler(cliContext context.CLIContext) http.HandlerFunc { + return func(responseWriter http.ResponseWriter, httpRequest *http.Request) { + var request request + if !rest.ReadRESTReq(responseWriter, httpRequest, cliContext.Codec, &request) { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, "") + return + } + + if request.BaseRequest.ChainID == "" { + request.BaseRequest.ChainID = viper.GetString(flags.FlagChainID) + if request.BaseRequest.ChainID == "" { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, "Chain-ID required but not specified") + return + } + } + + fromAddress, fromName, err := context.GetFromFields(strings.NewReader(keys.DefaultKeyPass), request.BaseRequest.From, false) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) + return + } + + txBuilder := types.NewTxBuilder( + authClient.GetTxEncoder(cliContext.Codec), request.BaseRequest.AccountNumber, request.BaseRequest.Sequence, 0, 0, + request.BaseRequest.Simulate, request.BaseRequest.ChainID, request.BaseRequest.Memo, request.BaseRequest.Fees, request.BaseRequest.GasPrices, + ) + + accountNumber, sequence, err := types.NewAccountRetriever(cliContext).GetAccountNumberSequence(fromAddress) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) + return + } + + txBuilder = txBuilder.WithAccountNumber(accountNumber) + txBuilder = txBuilder.WithSequence(sequence) + + stdSignature, err := types.MakeSignature(txBuilder.Keybase(), fromName, keys.DefaultKeyPass, types.StdSignMsg{ + ChainID: txBuilder.ChainID(), + AccountNumber: txBuilder.AccountNumber(), + Sequence: txBuilder.Sequence(), + Fee: request.StdTx.Fee, + Msgs: request.StdTx.GetMsgs(), + Memo: request.StdTx.GetMemo(), + }) + if err != nil { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, err.Error()) + return + } + + signers := request.StdTx.GetSigners() + request.StdTx.Signatures = append(request.StdTx.Signatures, stdSignature) + pubicKeys := request.StdTx.GetPubKeys() + + if len(pubicKeys) > len(signers) { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, "cannot add more signatures than signers") + return + } + + for i, publicKey := range pubicKeys { + if !bytes.Equal(publicKey.Address(), signers[i]) { + rest.WriteErrorResponse(responseWriter, http.StatusBadRequest, + fmt.Sprintf("pubKey does not match signer address %s with signer index: %d", signers[i], i)) + return + } + } + + rest.PostProcessResponse(responseWriter, cliContext, newResponse(request.StdTx, nil)) + } +} + +func RegisterRESTRoutes(cliContext context.CLIContext, router *mux.Router) { + router.HandleFunc("/sign", handler(cliContext)).Methods("POST") +} diff --git a/utilities/rest/sign/handler_test.go b/utilities/rest/sign/handler_test.go new file mode 100644 index 000000000..c39250612 --- /dev/null +++ b/utilities/rest/sign/handler_test.go @@ -0,0 +1,105 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package sign + +import ( + "bytes" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/codec" + cryptoKeys "github.com/cosmos/cosmos-sdk/crypto/keys" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/rest" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/gorilla/mux" + "github.com/spf13/viper" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/utilities/test/schema/helpers/base" +) + +func TestHandler(t *testing.T) { + Codec := codec.New() + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + Codec.RegisterConcrete(request{}, "request", nil) + Codec.RegisterConcrete(response{}, "response", nil) + base.TestMessagePrototype().RegisterCodec(Codec) + + clientContext := context.NewCLIContext().WithCodec(Codec) + + handler := handler(clientContext) + viper.Set(flags.FlagKeyringBackend, cryptoKeys.BackendTest) + + keyring, err := cryptoKeys.NewKeyring(sdk.KeyringServiceName(), cryptoKeys.BackendTest, viper.GetString(flags.FlagHome), strings.NewReader("")) + require.NoError(t, err) + + router := mux.NewRouter() + RegisterRESTRoutes(clientContext, router) + + t.Cleanup(func() { + _ = keyring.Delete("keyName1", "", true) + _ = keyring.Delete("keyName2", "", true) + _ = keyring.Delete("keyName3", "", true) + }) + _, err = keyring.CreateAccount("keyName1", "wage thunder live sense resemble foil apple course spin horse glass mansion midnight laundry acoustic rhythm loan scale talent push green direct brick please", + cryptoKeys.DefaultBIP39Passphrase, keys.DefaultKeyPass, sdkTypes.FullFundraiserPath, cryptoKeys.Secp256k1) + require.Nil(t, err) + + address := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + + var sdkAddress sdkTypes.AccAddress + sdkAddress, err = sdkTypes.AccAddressFromBech32(address) + + // signWithout chainID + requestBody1, err := Codec.MarshalJSON(request{ + BaseRequest: rest.BaseReq{From: address}, + Type: "cosmos-sdk/StdTx", + StdTx: auth.NewStdTx([]sdkTypes.Msg{base.NewTestMessage(sdkAddress, "id")}, auth.NewStdFee(10, sdkTypes.NewCoins()), nil, ""), + }) + require.Nil(t, err) + testRequest1, err := http.NewRequest("POST", "/sign", bytes.NewBuffer(requestBody1)) + require.Nil(t, err) + responseRecorder := httptest.NewRecorder() + handler.ServeHTTP(responseRecorder, testRequest1) + require.Equal(t, responseRecorder.Code, http.StatusBadRequest) + require.Equal(t, `{"error":"Chain-ID required but not specified"}`, responseRecorder.Body.String()) + + // with wrong key + requestBody2, err := Codec.MarshalJSON(request{ + BaseRequest: rest.BaseReq{From: "address", ChainID: "test"}, + Type: "cosmos-sdk/StdTx", + StdTx: auth.NewStdTx([]sdkTypes.Msg{base.NewTestMessage(sdkAddress, "id")}, auth.NewStdFee(20, sdkTypes.NewCoins()), nil, ""), + }) + require.Nil(t, err) + testRequest2, err := http.NewRequest("POST", "/sign", bytes.NewBuffer(requestBody2)) + require.Nil(t, err) + responseRecorder = httptest.NewRecorder() + handler.ServeHTTP(responseRecorder, testRequest2) + require.Equal(t, responseRecorder.Code, http.StatusBadRequest) + require.Equal(t, `{"error":"The specified item could not be found in the keyring"}`, responseRecorder.Body.String()) + + // RPC client offline + requestBody3, err := Codec.MarshalJSON(request{ + BaseRequest: rest.BaseReq{From: address, ChainID: "test"}, + Type: "cosmos-sdk/StdTx", + StdTx: auth.NewStdTx([]sdkTypes.Msg{base.NewTestMessage(sdkAddress, "id")}, auth.NewStdFee(30, sdkTypes.NewCoins()), nil, ""), + }) + require.Nil(t, err) + testRequest3, err := http.NewRequest("POST", "/sign", bytes.NewBuffer(requestBody3)) + require.Nil(t, err) + responseRecorder = httptest.NewRecorder() + handler.ServeHTTP(responseRecorder, testRequest3) + require.Equal(t, responseRecorder.Code, http.StatusBadRequest) + require.Equal(t, `{"error":"no RPC client is defined in offline mode"}`, responseRecorder.Body.String()) + +} diff --git a/utilities/rest/sign/request.go b/utilities/rest/sign/request.go new file mode 100644 index 000000000..138076103 --- /dev/null +++ b/utilities/rest/sign/request.go @@ -0,0 +1,25 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package sign + +import ( + "github.com/asaskevich/govalidator" + "github.com/cosmos/cosmos-sdk/types/rest" + authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" + + "github.com/AssetMantle/modules/schema/helpers" +) + +type request struct { + BaseRequest rest.BaseReq `json:"baseReq"` + Type string `json:"type" valid:"required~required field to missing, matches(^.*$)~invalid field type"` + StdTx authTypes.StdTx `json:"value"` +} + +var _ helpers.Request = request{} + +func (request request) Validate() error { + _, err := govalidator.ValidateStruct(request) + return err +} diff --git a/utilities/rest/sign/request_test.go b/utilities/rest/sign/request_test.go new file mode 100644 index 000000000..e16312e35 --- /dev/null +++ b/utilities/rest/sign/request_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package sign + +import ( + "testing" + + sdkTypes "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/rest" + authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/stretchr/testify/require" +) + +func Test_SignTx_Request(t *testing.T) { + fromAddress := "cosmos1pkkayn066msg6kn33wnl5srhdt3tnu2vzasz9c" + + testBaseReq := rest.BaseReq{From: fromAddress, ChainID: "test", Fees: sdkTypes.NewCoins()} + + testFee := authTypes.NewStdFee(12, sdkTypes.NewCoins()) + + testStdTx := authTypes.NewStdTx([]sdkTypes.Msg{}, testFee, []authTypes.StdSignature{}, "") + require.Equal(t, nil, request{BaseRequest: testBaseReq, Type: "type", StdTx: testStdTx}.Validate()) +} diff --git a/utilities/rest/sign/response.go b/utilities/rest/sign/response.go new file mode 100644 index 000000000..7f7135641 --- /dev/null +++ b/utilities/rest/sign/response.go @@ -0,0 +1,38 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package sign + +import ( + authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" + + "github.com/AssetMantle/modules/schema/helpers" +) + +type response struct { + Success bool `json:"success"` + Error error `json:"error"` + StdTx authTypes.StdTx `json:"tx"` +} + +var _ helpers.Response = response{} + +func (response response) IsSuccessful() bool { + return response.Success +} +func (response response) GetError() error { + return response.Error +} + +func newResponse(stdTx authTypes.StdTx, error error) helpers.Response { + success := true + if error != nil { + success = false + } + + return response{ + Success: success, + Error: error, + StdTx: stdTx, + } +} diff --git a/utilities/rest/sign/response_test.go b/utilities/rest/sign/response_test.go new file mode 100644 index 000000000..5df914c69 --- /dev/null +++ b/utilities/rest/sign/response_test.go @@ -0,0 +1,24 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package sign + +import ( + "testing" + + sdkTypes "github.com/cosmos/cosmos-sdk/types" + authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/stretchr/testify/require" + + "github.com/AssetMantle/modules/schema/errors/constants" +) + +func Test_SignTx_Response(t *testing.T) { + testFee := authTypes.NewStdFee(12, sdkTypes.NewCoins()) + + testStdTx := authTypes.NewStdTx([]sdkTypes.Msg{}, testFee, []authTypes.StdSignature{}, "") + require.Equal(t, response{Success: true, Error: nil, StdTx: testStdTx}, newResponse(testStdTx, nil)) + testResponse := newResponse(testStdTx, constants.IncorrectFormat) + require.Equal(t, false, testResponse.IsSuccessful()) + require.Equal(t, constants.IncorrectFormat, testResponse.GetError()) +} diff --git a/utilities/string/constants.go b/utilities/string/constants.go new file mode 100644 index 000000000..8122a4089 --- /dev/null +++ b/utilities/string/constants.go @@ -0,0 +1,3 @@ +package string + +const listStringSeparator = "," diff --git a/utilities/string/list.go b/utilities/string/list.go new file mode 100644 index 000000000..a19f14bc4 --- /dev/null +++ b/utilities/string/list.go @@ -0,0 +1,14 @@ +package string + +import ( + "strings" +) + +// TODO write testcase for empty and singular input +func JoinListStrings(listStrings ...string) string { + return strings.Join(listStrings, listStringSeparator) +} + +func SplitListString(listString string) []string { + return strings.Split(listString, listStringSeparator) +} diff --git a/utilities/test/schema/helpers/base/auxiliary.go b/utilities/test/schema/helpers/base/auxiliary.go new file mode 100644 index 000000000..a1341c514 --- /dev/null +++ b/utilities/test/schema/helpers/base/auxiliary.go @@ -0,0 +1,28 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package base + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/helpers" +) + +type testAuxiliaryKeeper struct { + mapper helpers.Mapper +} + +var _ helpers.AuxiliaryKeeper = (*testAuxiliaryKeeper)(nil) + +func (t testAuxiliaryKeeper) Help(_ sdkTypes.Context, _ helpers.AuxiliaryRequest) helpers.AuxiliaryResponse { + return nil +} + +func (t testAuxiliaryKeeper) Initialize(mapper helpers.Mapper, _ helpers.Parameters, _ []interface{}) helpers.Keeper { + return testAuxiliaryKeeper{mapper: mapper} +} + +func TestAuxiliaryKeeperPrototype() helpers.AuxiliaryKeeper { + return testAuxiliaryKeeper{} +} diff --git a/utilities/test/schema/helpers/base/mapper.go b/utilities/test/schema/helpers/base/mapper.go index a683c618b..8773cf8ab 100644 --- a/utilities/test/schema/helpers/base/mapper.go +++ b/utilities/test/schema/helpers/base/mapper.go @@ -1,25 +1,23 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base import ( "bytes" - cryptoCodec "github.com/cosmos/cosmos-sdk/crypto/codec" - vestingTypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" "testing" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/schema" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" "github.com/stretchr/testify/require" + abciTypes "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" - tmProto "github.com/tendermint/tendermint/proto/tendermint/types" tendermintDB "github.com/tendermint/tm-db" + + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" ) func SetupTest(t *testing.T) (sdkTypes.Context, *sdkTypes.KVStoreKey, *sdkTypes.TransientStoreKey) { @@ -32,24 +30,24 @@ func SetupTest(t *testing.T) (sdkTypes.Context, *sdkTypes.KVStoreKey, *sdkTypes. commitMultiStore.MountStoreWithDB(storeKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsStoreKey, sdkTypes.StoreTypeIAVL, memDB) commitMultiStore.MountStoreWithDB(paramsTransientStoreKeys, sdkTypes.StoreTypeTransient, memDB) - Error := commitMultiStore.LoadLatestVersion() - require.Nil(t, Error) + err := commitMultiStore.LoadLatestVersion() + require.Nil(t, err) - context := sdkTypes.NewContext(commitMultiStore, tmProto.Header{ + context := sdkTypes.NewContext(commitMultiStore, abciTypes.Header{ ChainID: "test", }, false, log.NewNopLogger()) return context, storeKey, paramsTransientStoreKeys } -func MakeCodec() *codec.LegacyAmino { - var Codec = codec.NewLegacyAmino() +func MakeCodec() *codec.Codec { + var Codec = codec.New() - schema.RegisterLegacyAminoCodec(Codec) - sdkTypes.RegisterLegacyAminoCodec(Codec) - cryptoCodec.RegisterCrypto(Codec) + schema.RegisterCodec(Codec) + sdkTypes.RegisterCodec(Codec) + codec.RegisterCrypto(Codec) codec.RegisterEvidences(Codec) - vestingTypes.RegisterLegacyAminoCodec(Codec) + vesting.RegisterCodec(Codec) return Codec } @@ -61,19 +59,15 @@ type testKey struct { var _ helpers.Key = (*testKey)(nil) -func (t testKey) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) { - panic("implement me") -} - -func (t testKey) GetStructReference() codec.ProtoMarshaler { - panic("implement me") +func (t testKey) String() string { + return t.ID } func (t testKey) GenerateStoreKeyBytes() []byte { return append([]byte{0x11}, []byte(t.ID)...) } -func (t testKey) RegisterCodec(codec *codec.LegacyAmino) { +func (t testKey) RegisterCodec(codec *codec.Codec) { codec.RegisterConcrete(testKey{}, "test/testKey", nil) } @@ -101,50 +95,14 @@ type testMappable struct { var _ helpers.Mappable = (*testMappable)(nil) -func (t testMappable) RegisterLegacyAminoCodec(codec *codec.LegacyAmino) { - codec.RegisterConcrete(testMappable{}, "test/testMappable", nil) -} - -func (t testMappable) Size() int { - panic("implement me") -} - -func (t testMappable) MarshalTo(data []byte) (int, error) { - panic("implement me") -} - -func (t testMappable) Unmarshal(dAtA []byte) error { - panic("implement me") -} - -func (t testMappable) Reset() { - panic("implement me") -} - -func (t testMappable) String() string { - panic("implement me") -} - -func (t testMappable) ProtoMessage() { - panic("implement me") -} - -func (t testMappable) Marshal() ([]byte, error) { - panic("implement me") -} - -func (t testMappable) MarshalToSizedBuffer(i []byte) (int, error) { - panic("implement me") -} - -func (t testMappable) GetStructReference() codec.ProtoMarshaler { - panic("implement me") -} - func (t testMappable) GetKey() helpers.Key { return NewKey(t.ID) } +func (t testMappable) RegisterCodec(c *codec.Codec) { + c.RegisterConcrete(testMappable{}, "test/testMappable", nil) +} + func NewMappable(id string, value string) helpers.Mappable { return testMappable{ID: id, Value: value} } diff --git a/utilities/test/schema/helpers/base/message.go b/utilities/test/schema/helpers/base/message.go index 8ccef2fc2..0b7d60167 100644 --- a/utilities/test/schema/helpers/base/message.go +++ b/utilities/test/schema/helpers/base/message.go @@ -1,7 +1,5 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base @@ -11,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers" ) // TestMessage msg type for testing @@ -42,7 +40,7 @@ func (message TestMessage) ValidateBasic() error { return nil } func (message TestMessage) GetSigners() []sdkTypes.AccAddress { return []sdkTypes.AccAddress{message.From} } -func (message TestMessage) RegisterCodec(codec *codec.LegacyAmino) { +func (message TestMessage) RegisterCodec(codec *codec.Codec) { codec.RegisterConcrete(TestMessage{}, "test/TestMessage", nil) } diff --git a/utilities/test/schema/helpers/base/query.go b/utilities/test/schema/helpers/base/query.go index cd0d359f8..d55ec09d5 100644 --- a/utilities/test/schema/helpers/base/query.go +++ b/utilities/test/schema/helpers/base/query.go @@ -1,17 +1,15 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base import ( "encoding/json" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" sdkTypes "github.com/cosmos/cosmos-sdk/types" - "github.com/persistenceOne/persistenceSDK/schema/helpers" + "github.com/AssetMantle/modules/schema/helpers" ) type TestQueryKeeper struct { @@ -41,23 +39,23 @@ type testQueryRequest struct { var _ helpers.QueryRequest = (*testQueryRequest)(nil) -func (t testQueryRequest) Validate() error { +func (testQueryRequest testQueryRequest) Validate() error { return nil } -func (t testQueryRequest) FromCLI(_ helpers.CLICommand, _ client.Context) helpers.QueryRequest { - return t +func (testQueryRequest testQueryRequest) FromCLI(_ helpers.CLICommand, _ context.CLIContext) (helpers.QueryRequest, error) { + return testQueryRequest, nil } -func (t testQueryRequest) FromMap(_ map[string]string) helpers.QueryRequest { - return t +func (testQueryRequest testQueryRequest) FromMap(_ map[string]string) (helpers.QueryRequest, error) { + return testQueryRequest, nil } -func (t testQueryRequest) LegacyAminoEncode() ([]byte, error) { - return json.Marshal(t) +func (testQueryRequest testQueryRequest) Encode() ([]byte, error) { + return json.Marshal(testQueryRequest) } -func (t testQueryRequest) LegacyAminoDecode(bytes []byte) (helpers.QueryRequest, error) { +func (testQueryRequest) Decode(bytes []byte) (helpers.QueryRequest, error) { var queryRequest testQueryRequest err := json.Unmarshal(bytes, &queryRequest) @@ -83,11 +81,11 @@ func (t testQueryResponse) GetError() error { return t.Error } -func (t testQueryResponse) LegacyAminoEncode() ([]byte, error) { +func (t testQueryResponse) Encode() ([]byte, error) { return json.Marshal(t) } -func (t testQueryResponse) LegacyAminoDecode(bytes []byte) (helpers.QueryResponse, error) { +func (t testQueryResponse) Decode(bytes []byte) (helpers.QueryResponse, error) { var queryResponse testQueryResponse err := json.Unmarshal(bytes, &queryResponse) diff --git a/utilities/test/schema/helpers/base/transaction.go b/utilities/test/schema/helpers/base/transaction.go index 32929f47e..314ec0482 100644 --- a/utilities/test/schema/helpers/base/transaction.go +++ b/utilities/test/schema/helpers/base/transaction.go @@ -1,20 +1,18 @@ -/* - Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the persistenceSDK contributors - SPDX-License-Identifier: Apache-2.0 -*/ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 package base import ( "encoding/json" - "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/codec" sdkTypes "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/persistenceOne/persistenceSDK/schema/helpers" - codecUtilities "github.com/persistenceOne/persistenceSDK/utilities/codec" + "github.com/AssetMantle/modules/schema/helpers" + codecUtilities "github.com/AssetMantle/modules/utilities/codec" ) type TransactionRequest struct { @@ -27,7 +25,7 @@ var _ helpers.TransactionRequest = (*TransactionRequest)(nil) func (transactionRequest TransactionRequest) Validate() error { return nil } -func (transactionRequest TransactionRequest) FromCLI(_ helpers.CLICommand, _ client.Context) (helpers.TransactionRequest, error) { +func (transactionRequest TransactionRequest) FromCLI(_ helpers.CLICommand, _ context.CLIContext) (helpers.TransactionRequest, error) { return transactionRequest, nil } func (transactionRequest TransactionRequest) FromJSON(rawMessage json.RawMessage) (helpers.TransactionRequest, error) { @@ -43,8 +41,8 @@ func (transactionRequest TransactionRequest) GetBaseReq() rest.BaseReq { func (transactionRequest TransactionRequest) MakeMsg() (sdkTypes.Msg, error) { return NewTestMessage(sdkTypes.AccAddress(transactionRequest.BaseReq.From), transactionRequest.ID), nil } -func (TransactionRequest) RegisterCodec(codec *codec.LegacyAmino) { - codecUtilities.RegisterLegacyAminoXPRTConcrete(codec, "test/TransactionRequest", TransactionRequest{}) +func (TransactionRequest) RegisterCodec(codec *codec.Codec) { + codecUtilities.RegisterModuleConcrete(codec, TransactionRequest{}) } func TestTransactionRequestPrototype() helpers.TransactionRequest { return TransactionRequest{} diff --git a/utilities/test/schema/helpers/block.go b/utilities/test/schema/helpers/block.go new file mode 100644 index 000000000..d100dfee0 --- /dev/null +++ b/utilities/test/schema/helpers/block.go @@ -0,0 +1,34 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package helpers + +import ( + sdkTypes "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/AssetMantle/modules/schema/helpers" +) + +type block struct { + mapper helpers.Mapper + parameters helpers.Parameters +} + +var _ helpers.Block = (*block)(nil) + +func (b block) Begin(_ sdkTypes.Context, _ abci.RequestBeginBlock) { + +} + +func (b block) End(_ sdkTypes.Context, _ abci.RequestEndBlock) { + +} + +func (b block) Initialize(mapper helpers.Mapper, parameters helpers.Parameters, _ ...interface{}) helpers.Block { + return block{mapper, parameters} +} + +func TestBlockPrototype() helpers.Block { + return block{} +} diff --git a/utilities/transaction/codec.go b/utilities/transaction/codec.go new file mode 100644 index 000000000..c7a25189e --- /dev/null +++ b/utilities/transaction/codec.go @@ -0,0 +1,20 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transaction + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/AssetMantle/modules/schema" + "github.com/AssetMantle/modules/schema/helpers" +) + +func RegisterCodec(messagePrototype func() helpers.Message) *codec.Codec { + Codec := codec.New() + messagePrototype().RegisterCodec(Codec) + schema.RegisterCodec(Codec) + Codec.Seal() + + return Codec +} diff --git a/utilities/transaction/codec_test.go b/utilities/transaction/codec_test.go new file mode 100644 index 000000000..8df8ac53a --- /dev/null +++ b/utilities/transaction/codec_test.go @@ -0,0 +1,16 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package transaction + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRegisterCodec(t *testing.T) { + require.Panics(t, func() { + require.Equal(t, RegisterCodec(nil), nil) + }) +} diff --git a/utilities/wasm/customEncoder.go b/utilities/wasm/customEncoder.go new file mode 100644 index 000000000..2184c9961 --- /dev/null +++ b/utilities/wasm/customEncoder.go @@ -0,0 +1,42 @@ +// Copyright [2021] - [2022], AssetMantle Pte. Ltd. and the code contributors +// SPDX-License-Identifier: Apache-2.0 + +package wasm + +import ( + "encoding/json" + "strings" + + "github.com/CosmWasm/wasmd/x/wasm" + sdkTypes "github.com/cosmos/cosmos-sdk/types" + + "github.com/AssetMantle/modules/schema/errors/constants" + "github.com/AssetMantle/modules/schema/helpers" + baseHelpers "github.com/AssetMantle/modules/schema/helpers/base" +) + +func CustomEncoder(moduleList ...helpers.Module) wasm.CustomEncoder { + return func(sender sdkTypes.AccAddress, rawMessage json.RawMessage) ([]sdkTypes.Msg, error) { + wasmMessage := baseHelpers.WasmMessagePrototype() + + err := json.Unmarshal(rawMessage, &wasmMessage) + if err != nil { + return nil, constants.IncorrectMessage + } + + path := strings.Split(wasmMessage.GetType(), "/") + + for _, module := range moduleList { + if module.Name() == path[0] { + msg, err := module.DecodeModuleTransactionRequest(path[1], wasmMessage.GetRawMessage()) + if err != nil { + return nil, err + } + + return []sdkTypes.Msg{msg}, nil + } + } + + return nil, constants.IncorrectMessage + } +}