Compare commits

...

134 Commits

Author SHA1 Message Date
Jędrzej Stuczyński 071e7de44d bugfix: always read values of environmental config options
regardless of whether they have the default values or not
2023-01-11 13:08:14 +00:00
Jon Häggblad b0960091c1 Merge pull request #2764 from nymtech/feature/rust-sdk-initial-version
Initial Rust client SDK
2023-01-11 10:06:15 +01:00
Jon Häggblad b97a12186f rust-fmt: append path in error 2023-01-11 00:32:21 +01:00
Jon Häggblad 36496a519a rust-sdk: add additinal example 2023-01-11 00:13:45 +01:00
Jon Häggblad 87fad25ac3 rust-sdk: implement manualy set/get keys 2023-01-11 00:13:28 +01:00
Jon Häggblad df3d478caa rust-sdk: make new_from_dir return result 2023-01-10 23:28:26 +01:00
Jon Häggblad 751e3ccd27 Merge remote-tracking branch 'origin/develop' into feature/rust-sdk-initial-version 2023-01-10 23:14:24 +01:00
Mark Sinclair 74a4546d72 GitHub Actions: post messages to another channel on job failures 2023-01-10 18:25:42 +00:00
Jędrzej Stuczyński 2587d00b9e feature: reduce staking address capabilities + refactor vesting storage (#2796)
* checks for existing staking account

* removed code for v2 migration

* using stronger types for storage keys

* Added type alias for the storage key and documented each `Map`

* remove the hacky way of storing staker information

* allow the staking address account to perform delegations with the additional msg argument

* new unit tests

* updated client code

* modified migrate msg to explicitly require confirming having performed manual checks

* re-ordered arguments
2023-01-10 17:36:27 +00:00
Fouad cf25c331c0 Upgrade webpack (#2800)
* upgrade webpack and remove unused client lib

* upgrade webpack loaders
2023-01-10 17:08:09 +00:00
Mark Sinclair a24c7e4783 Merge pull request #2813 from nymtech/feature/matrix-messages
Send matrix notification messages
2023-01-10 16:40:38 +00:00
Mark Sinclair 9ea725bf83 GitHub Actions: add matrix env vars to all jobs with notifications 2023-01-10 16:36:50 +00:00
Mark Sinclair fe78d4faf0 GitHub Actions: support sending notification messages to matrix 2023-01-10 16:24:23 +00:00
Jędrzej Stuczyński 0df063f9f6 feature: query for obtaining amount of vesting coins for all accounts (#2791)
* wip

* Introduced paged queries for getting list of all vesting accounts and for amount of vesting coins

* Added the queries to VestingQueryClient trait

* Added default implementations to all trait queries

* Fixed naming for the vesting coins query

* Helper functions for dealing with paging

* Updated changelog
2023-01-10 14:58:40 +00:00
Bogdan-Ștefan Neacşu ad8fdbdddf Feature/configurable dkg signup (#2809)
* Refactored consts to config structure

* Nym-cli generate init for dkg contract
2023-01-10 16:33:16 +02:00
Bogdan-Ștefan Neacşu 8d3aea969e Handle case when changed value is 42 (#2808) 2023-01-10 15:01:57 +02:00
farbanas 078ca0b0d1 Merge resolve 2023-01-10 13:52:00 +01:00
farbanas 273dc41559 feat: update changelogs 2023-01-10 13:43:09 +01:00
farbanas 61bc74148f Update versions 2023-01-10 13:10:24 +01:00
Jędrzej Stuczyński 5b14eecf82 bugfix: for Default config impl generate fresh mnemonic over using a hardcoded one (#2806) 2023-01-10 10:39:58 +00:00
Jon Häggblad 2746cabecc rust-sdk: reorder in client file 2023-01-10 01:43:50 +01:00
Jon Häggblad 666cbcf2cc rust-sdk: extract out builder 2023-01-10 01:36:27 +01:00
Fran Arbanas 30110aff65 Merge pull request #1827 from nymtech/feat/nym-cli-cosmwasm-generate-init-message
nym-cli generate instantiate message for mixnet and vesting contracts
2023-01-09 19:54:28 +01:00
farbanas 1954c49ac2 merge resolve 2023-01-09 19:38:16 +01:00
farbanas 70328ba114 merge resolve 2023-01-09 19:30:25 +01:00
farbanas c43b2dc117 merge resolve 2023-01-09 16:03:42 +01:00
Drazen Urch 4a8a9096dd Save to JSON in addition to printing (#1864)
* Save to JSON in addition to printing

* Save node details to json for mixnode

* Remove Cargo.locks

* Cli ergonomics

* Json output for gateway
2023-01-09 12:51:21 +01:00
Jon Häggblad 96ab4325e3 rust-sdk: tidy 2023-01-09 12:39:23 +01:00
Jon Häggblad 11e2ba33e7 fix compilation after merge in latest develop 2023-01-09 10:44:02 +01:00
Jon Häggblad 95db26c35b changelog: add note 2023-01-09 10:43:42 +01:00
Jon Häggblad aed96b2d44 Merge remote-tracking branch 'origin/develop' into feature/rust-sdk-initial-version 2023-01-09 10:41:10 +01:00
Jon Häggblad 326d5fcec8 rustfmt 2023-01-09 10:02:46 +01:00
Jędrzej Stuczyński 88d813b9c1 Feature/optional set trait (#2773)
* Defined OptionalSet trait

* extended the trait to handle environment

* sample implementation for the gateway

* implementation for mixnode

* Added the same feature to nym-api config + made some config types stricter

* fixed compilation and linter issues

* keeping track of parsing error

* attempt at using the trait for the client configs

* Streamlined more arguments

* Removed deprecation on setters

* fixed incorrect test constructor

* missed rebase fixes
2023-01-06 18:13:25 +00:00
Pierre Dommerc e181a1cfb1 feat(wallet-buy): pass wallet address as url param (#2780) 2023-01-06 09:38:30 +01:00
Jon Häggblad afae6fc9a5 rust-sdk: move Keys to its own file 2023-01-05 17:44:03 +01:00
Jon Häggblad 23c13a409a rust-sdk: rename key_paths to paths 2023-01-05 17:06:21 +01:00
Dave Hrycyszyn 29091aab8e Feature/rename nymd to nyxd (#2696)
* Renaming all instances of nymd to nyxd

* Might as well get the changelogs too

* Making it clearer that an ApiClient is a NymApiClient

* Lining up config templates with struct keys on gateway

* Changed the last references to validator_urls to nyxd_urls

* Fixed up a few type errors after refactoring

* Changed the changelog

* Fixed typo in changelog

* Further instances of renaming 'nymd' + introducing additional clap aliases

* updated environmental variables and allowed usage of deprecated variants

* missing occurences of coconut-locked environmental variables

Co-authored-by: Jędrzej Stuczyński <jedrzej.stuczynski@gmail.com>
2023-01-05 15:35:47 +00:00
Jon Häggblad 1d522143a2 rust-sdk: remove more unwraps 2023-01-05 16:18:39 +01:00
Jon Häggblad 775ce0f95d rust-sdk: fix some issues identified during draft review 2023-01-05 16:18:39 +01:00
Jon Häggblad b019786c5a rust-sdk: replace a bunch of unwrap with error return 2023-01-05 16:18:39 +01:00
Jon Häggblad 9b9c01fb8f rust-sdk: initial version 2023-01-05 16:18:39 +01:00
Dave Hrycyszyn 6c857b5daf wip 2023-01-05 16:18:39 +01:00
Dave Hrycyszyn 5ea084d286 Starting with Rust sdk 2023-01-05 16:18:39 +01:00
Pierre Dommerc fdbe3a1f6a fix(explorer,explorer-api): mixnode location (#2763)
* chore(explorer-api): remove useless route (/terms)

* feat(explorer-api-geoip): add coordinates lat&lon

* fix(explorer): mixnode location

* fix: typo

* fix: clippy
2023-01-05 15:53:15 +01:00
Fouad 5b15ed6f15 merge resolve 2022-12-22 15:48:40 +01:00
Gala 57703af642 Merge pull request #2746 from nymtech/revert-1519-339-net-switch-bttn
Revert "NE: Switch button to change the explorer network"
2022-12-22 14:21:24 +01:00
Gala 9dd4c5d871 Revert "NE: Switch button to change the explorer network" 2022-12-22 14:20:21 +01:00
farbanas 4813cf6c18 feat: release v1.1.5 of nym-wallet 2022-12-22 12:14:01 +01:00
benedetta davico 83b76c6b37 Merge pull request #1519 from nymtech/339-net-switch-bttn
NE: Switch button to change the explorer network
2022-12-22 11:23:00 +01:00
Gala 4120234155 fix build problem 2022-12-22 11:09:55 +01:00
Gala 42b444ddf8 Merge branch '339-net-switch-bttn' of github.com:nymtech/nym into 339-net-switch-bttn 2022-12-22 10:55:03 +01:00
Gala acd832d8e5 cleaning 2022-12-22 10:54:26 +01:00
Gala 75a726ebbe some styles 2022-12-22 10:54:12 +01:00
Gala b9fbab6024 adding button on mov nav and make it smaller 2022-12-22 10:54:12 +01:00
Gala 06ed8716a1 adding a switch between networks 2022-12-22 10:54:12 +01:00
benedetta davico beddd3dcee Merge pull request #2742 from nymtech/feat/2130-tables-update-rebase
Feat/2130 tables update rebase
2022-12-22 10:37:53 +01:00
benedetta davico 4d02dfb899 Merge pull request #2741 from nymtech/fix/explorer-gateway-bond-decimals
fix(explorer): set gateway bond 6 decimals
2022-12-21 18:10:47 +01:00
Gala 80d6cb5c12 last small touch 2022-12-21 17:34:26 +01:00
Gala 7422ab69ba Merge branch 'feat/2130-tables-update-rebase' of github.com:nymtech/nym into feat/2130-tables-update-rebase 2022-12-21 17:30:26 +01:00
Gala 60c8185bea cleaning 2022-12-21 17:26:34 +01:00
Gala 9d3c7c0be8 refactor from PR request 2022-12-21 17:26:34 +01:00
Gala d6048fae52 refactor 2022-12-21 17:26:22 +01:00
Gala ddb7b0e872 delegations layout and tooltip when delegate with vesting 2022-12-21 17:26:22 +01:00
Gala 4995dde705 bond table changes 2022-12-21 17:25:09 +01:00
Gala 63bfe4246f fix parameters settings layout 2022-12-21 17:24:23 +01:00
Gala 4654b360e0 cleaning 2022-12-21 17:23:52 +01:00
Gala 7c5c19986a refactor from PR request 2022-12-21 17:23:52 +01:00
Gala 46edca0bd4 refactor 2022-12-21 17:23:52 +01:00
Gala b03a1f922d refactor 2022-12-21 17:23:52 +01:00
Gala 9616c90433 delegations layout and tooltip when delegate with vesting 2022-12-21 17:23:52 +01:00
Gala ea49f0a265 delegations table changes wip 2022-12-21 17:23:52 +01:00
Gala 2470c8b9b5 tidying up 2022-12-21 17:23:52 +01:00
Gala 7d001965ec change date order to dd/mm/yy 2022-12-21 17:22:26 +01:00
Gala 11b1089d83 removing epoch on settings and fixing divider position 2022-12-21 17:22:26 +01:00
Gala 52699d7598 bond table changes 2022-12-21 17:21:51 +01:00
benedetta davico 87443dd624 Merge pull request #2743 from nymtech/feat/2161-ne-gate-version
Feat/2161 ne gate version
2022-12-21 15:25:07 +01:00
Gala e0f2fa6705 fix indentation 2022-12-21 14:45:14 +01:00
Gala 7949b07213 Merge branch 'feat/2161-ne-gate-version' of github.com:nymtech/nym into feat/2161-ne-gate-version 2022-12-21 14:07:16 +01:00
Gala bd20fd0b1f remove console log 2022-12-21 14:06:32 +01:00
Gala 57d3d6fd0f sdding version number on the gateways list and details 2022-12-21 14:06:32 +01:00
Gala 06eff652dd wip adding gt version 2022-12-21 14:06:32 +01:00
Gala 246decac4a remove console log 2022-12-21 14:01:53 +01:00
Gala a14ae298ae sdding version number on the gateways list and details 2022-12-21 13:59:23 +01:00
Gala 43188051d3 Merge branch 'feat/2130-tables-update-rebase' of github.com:nymtech/nym into feat/2130-tables-update-rebase 2022-12-21 12:48:46 +01:00
Gala 8aa15fa467 fix parameters settings layout 2022-12-21 12:41:12 +01:00
benedetta davico f77b037ef7 Merge pull request #2704 from nymtech/feature/nym-connect-display-info
NymConnect - Display service info in tooltip **1.1.5 Release**
2022-12-21 12:39:44 +01:00
Gala 75dbc5d790 Merge branch 'release/v1.1.5' into feat/2130-tables-update-rebase 2022-12-21 12:20:42 +01:00
Gala e6bcd706ff cleaning 2022-12-21 12:03:46 +01:00
Gala 9a077a0928 refactor from PR request 2022-12-21 12:03:46 +01:00
Gala 11fd42e187 refactor 2022-12-21 12:03:46 +01:00
Gala 6e499e5996 refactor 2022-12-21 12:03:46 +01:00
Gala f98cc73a1f delegations layout and tooltip when delegate with vesting 2022-12-21 12:03:46 +01:00
Gala db9bf4d3fa delegations table changes wip 2022-12-21 12:03:46 +01:00
Gala b30628529d tidying up 2022-12-21 12:03:46 +01:00
Gala 3be615f74f change date order to dd/mm/yy 2022-12-21 12:03:46 +01:00
Gala a8ccd2ec17 removing epoch on settings and fixing divider position 2022-12-21 12:03:46 +01:00
Gala 2d71caf50a bond table changes 2022-12-21 12:03:46 +01:00
Gala 4d08d62fc2 wip adding gt version 2022-12-21 11:54:41 +01:00
pierre 40e5595d65 fix(explorer): set gateway bond 6 decimals 2022-12-21 11:46:12 +01:00
Gala 6780d58a98 cleaning 2022-12-21 11:19:50 +01:00
Gala ccbf06f179 refactor from PR request 2022-12-21 11:19:50 +01:00
Gala e6ecf71cc3 refactor 2022-12-21 11:19:50 +01:00
Gala c66312ee96 refactor 2022-12-21 11:19:50 +01:00
Gala 808802aeb4 delegations layout and tooltip when delegate with vesting 2022-12-21 11:19:50 +01:00
Gala fb38f24e5c delegations table changes wip 2022-12-21 11:19:50 +01:00
Gala 65f148a5ad tidying up 2022-12-21 11:19:50 +01:00
Gala 2bcdc5d11e change date order to dd/mm/yy 2022-12-21 11:19:50 +01:00
Gala 5ecb03ffe9 removing epoch on settings and fixing divider position 2022-12-21 11:19:50 +01:00
Gala 8505989dad bond table changes 2022-12-21 11:19:50 +01:00
benedetta davico ed5e865db7 Merge pull request #2718 from nymtech/feature/wallet-epoch-time-in-unbond-modal
Add epoch info to unbond modal **1.1.5 Release**
2022-12-21 10:37:38 +01:00
benedetta davico ea3194e0c3 Merge pull request #2720 from nymtech/feature/wallet-fix-parameter-input-layout
Fix param input layout **1.1.5 Release**
2022-12-21 10:24:05 +01:00
Gala 190bff4ffe Merge branch 'release/v1.1.5' of github.com:nymtech/nym into release/v1.1.5 2022-12-21 10:21:23 +01:00
fmtabbara c509555d15 fix param input layout 2022-12-21 09:22:01 +01:00
fmtabbara f0d66fdd88 add epoch info to unbond modal 2022-12-21 09:19:39 +01:00
fmtabbara 14847d01b7 remove console.log 2022-12-21 09:17:38 +01:00
fmtabbara f4711902bd display service info in tooltip
trim provider address
2022-12-21 09:17:38 +01:00
farbanas d92d6877a4 Merge branch 'release/v1.1.4' 2022-12-20 12:33:46 +01:00
farbanas 70fcb8c046 feat: added the rest of the generators, updated some fields based on PR comments 2022-12-15 10:07:19 +01:00
farbanas ce676c2bb5 Merge branch 'release/v1.1.3' 2022-12-13 15:18:49 +01:00
farbanas a096f9d54e Merge branch 'release/v1.1.3' 2022-12-13 13:24:01 +01:00
farbanas d9b6823106 Merge branch 'release/v1.1.2' 2022-12-07 12:37:14 +01:00
farbanas 89bcb5649b changed ubuntu-latest on GH actions to ubuntu-20.04 2022-12-06 17:23:08 +01:00
farbanas 53444cf55a fix: rewarding denom was unyxt by default, it should be unymt 2022-12-05 13:22:21 +01:00
farbanas f2e460a96b chore: import cleanup 2022-12-01 12:17:46 +01:00
farbanas b5b7b7255b feat: add vesting contract instatiate message generation 2022-12-01 11:41:03 +01:00
farbanas 894a46688a chore: formatting 2022-12-01 10:21:00 +01:00
farbanas 5d3550a569 fix: remove the debug output for instantiate message as it incorrectly escapes strings 2022-12-01 10:16:36 +01:00
farbanas b43dab4f83 chore: added a couple of debug messages to parseOptionalAccount 2022-11-30 17:24:25 +01:00
farbanas 1bdb58571d feat: refactor cosmwasm nym-cli command a bit to support multiple tiers. Add a generator for mixnet contract instantiate messages 2022-11-30 16:01:35 +01:00
Gala a74a99d81d cleaning 2022-08-10 16:38:56 +02:00
Gala c09d3af92f Merge branch 'develop' into 340-ne-content 2022-08-10 16:35:38 +02:00
Gala 76773c58d7 some styles 2022-08-10 16:34:30 +02:00
Gala fd90175e87 adding button on mov nav and make it smaller 2022-08-10 15:43:42 +02:00
Gala 0eb859467e adding a switch between networks 2022-08-10 15:09:44 +02:00
341 changed files with 5552 additions and 17671 deletions
+1 -1
View File
@@ -14,7 +14,7 @@ GEOIPUPDATE_LICENSE_KEY=xxx
# List of space-separated database edition IDs. Edition IDs may
# consist of letters, digits, and dashes. For example, GeoIP2-City
# would download the GeoIP2 City database (GeoIP2-City).
GEOIPUPDATE_EDITION_IDS=GeoLite2-Country
GEOIPUPDATE_EDITION_IDS=GeoLite2-City
# The number of hours between geoipupdate runs. If this is not set
# or is set to 0, geoipupdate will run once and exit.
GEOIPUPDATE_FREQUENCY=72
+5
View File
@@ -47,6 +47,11 @@ jobs:
KEYBASE_NYMBOT_PAPERKEY: "${{ secrets.KEYBASE_NYMBOT_PAPERKEY }}"
KEYBASE_NYMBOT_TEAM: "${{ secrets.KEYBASE_NYMBOT_TEAM }}"
KEYBASE_NYM_CHANNEL: "security"
MATRIX_SERVER: "${{ secrets.MATRIX_SERVER }}"
MATRIX_ROOM: "${{ secrets.MATRIX_ROOM }}"
MATRIX_USER_ID: "${{ secrets.MATRIX_USER_ID }}"
MATRIX_TOKEN: "${{ secrets.MATRIX_TOKEN }}"
MATRIX_DEVICE_ID: "${{ secrets.MATRIX_DEVICE_ID }}"
uses: docker://keybaseio/client:stable-node
with:
args: .github/workflows/support-files/notifications/entry_point.sh
+5
View File
@@ -58,6 +58,11 @@ jobs:
KEYBASE_NYMBOT_TEAM: "${{ secrets.KEYBASE_NYMBOT_TEAM }}"
KEYBASE_NYM_CHANNEL: "ci-ts-packages"
IS_SUCCESS: "${{ job.status == 'success' }}"
MATRIX_SERVER: "${{ secrets.MATRIX_SERVER }}"
MATRIX_ROOM: "${{ secrets.MATRIX_ROOM }}"
MATRIX_USER_ID: "${{ secrets.MATRIX_USER_ID }}"
MATRIX_TOKEN: "${{ secrets.MATRIX_TOKEN }}"
MATRIX_DEVICE_ID: "${{ secrets.MATRIX_DEVICE_ID }}"
uses: docker://keybaseio/client:stable-node
with:
args: .github/workflows/support-files/notifications/entry_point.sh
+1 -1
View File
@@ -11,7 +11,7 @@ on:
jobs:
build:
runs-on: [ self-hosted, custom-linux ]
# Enable sccache via environment variable
# Enable sccache via environment variable
env:
RUSTC_WRAPPER: /home/ubuntu/.cargo/bin/sccache
steps:
+5
View File
@@ -73,6 +73,11 @@ jobs:
KEYBASE_NYMBOT_TEAM: "${{ secrets.KEYBASE_NYMBOT_TEAM }}"
KEYBASE_NYM_CHANNEL: "ci-network-explorer"
IS_SUCCESS: "${{ job.status == 'success' }}"
MATRIX_SERVER: "${{ secrets.MATRIX_SERVER }}"
MATRIX_ROOM: "${{ secrets.MATRIX_ROOM }}"
MATRIX_USER_ID: "${{ secrets.MATRIX_USER_ID }}"
MATRIX_TOKEN: "${{ secrets.MATRIX_TOKEN }}"
MATRIX_DEVICE_ID: "${{ secrets.MATRIX_DEVICE_ID }}"
uses: docker://keybaseio/client:stable-node
with:
args: .github/workflows/support-files/notifications/entry_point.sh
+5
View File
@@ -183,6 +183,11 @@ jobs:
KEYBASE_NYMBOT_TEAM: "${{ secrets.KEYBASE_NYMBOT_TEAM }}"
KEYBASE_NYM_CHANNEL: "ci-nightly"
IS_SUCCESS: "${{ env.WORKFLOW_CONCLUSION == 'success' }}"
MATRIX_SERVER: "${{ secrets.MATRIX_SERVER }}"
MATRIX_ROOM: "${{ secrets.MATRIX_ROOM }}"
MATRIX_USER_ID: "${{ secrets.MATRIX_USER_ID }}"
MATRIX_TOKEN: "${{ secrets.MATRIX_TOKEN }}"
MATRIX_DEVICE_ID: "${{ secrets.MATRIX_DEVICE_ID }}"
uses: docker://keybaseio/client:stable-node
with:
args: .github/workflows/support-files/notifications/entry_point.sh
@@ -198,6 +198,11 @@ jobs:
KEYBASE_NYMBOT_TEAM: "${{ secrets.KEYBASE_NYMBOT_TEAM }}"
KEYBASE_NYM_CHANNEL: "ci-nightly-release"
IS_SUCCESS: "${{ env.WORKFLOW_CONCLUSION == 'success' }}"
MATRIX_SERVER: "${{ secrets.MATRIX_SERVER }}"
MATRIX_ROOM: "${{ secrets.MATRIX_ROOM }}"
MATRIX_USER_ID: "${{ secrets.MATRIX_USER_ID }}"
MATRIX_TOKEN: "${{ secrets.MATRIX_TOKEN }}"
MATRIX_DEVICE_ID: "${{ secrets.MATRIX_DEVICE_ID }}"
uses: docker://keybaseio/client:stable-node
with:
args: .github/workflows/support-files/notifications/entry_point.sh
@@ -198,6 +198,11 @@ jobs:
KEYBASE_NYMBOT_TEAM: "${{ secrets.KEYBASE_NYMBOT_TEAM }}"
KEYBASE_NYM_CHANNEL: "ci-nightly-release"
IS_SUCCESS: "${{ env.WORKFLOW_CONCLUSION == 'success' }}"
MATRIX_SERVER: "${{ secrets.MATRIX_SERVER }}"
MATRIX_ROOM: "${{ secrets.MATRIX_ROOM }}"
MATRIX_USER_ID: "${{ secrets.MATRIX_USER_ID }}"
MATRIX_TOKEN: "${{ secrets.MATRIX_TOKEN }}"
MATRIX_DEVICE_ID: "${{ secrets.MATRIX_DEVICE_ID }}"
uses: docker://keybaseio/client:stable-node
with:
args: .github/workflows/support-files/notifications/entry_point.sh
+5
View File
@@ -54,6 +54,11 @@ jobs:
KEYBASE_NYMBOT_TEAM: "${{ secrets.KEYBASE_NYMBOT_TEAM }}"
KEYBASE_NYM_CHANNEL: "ci-nym-connect"
IS_SUCCESS: "${{ job.status == 'success' }}"
MATRIX_SERVER: "${{ secrets.MATRIX_SERVER }}"
MATRIX_ROOM: "${{ secrets.MATRIX_ROOM }}"
MATRIX_USER_ID: "${{ secrets.MATRIX_USER_ID }}"
MATRIX_TOKEN: "${{ secrets.MATRIX_TOKEN }}"
MATRIX_DEVICE_ID: "${{ secrets.MATRIX_DEVICE_ID }}"
uses: docker://keybaseio/client:stable-node
with:
args: .github/workflows/support-files/notifications/entry_point.sh
@@ -50,6 +50,11 @@ jobs:
KEYBASE_NYMBOT_TEAM: "${{ secrets.KEYBASE_NYMBOT_TEAM }}"
KEYBASE_NYM_CHANNEL: "ci-nym-wallet"
IS_SUCCESS: "${{ job.status == 'success' }}"
MATRIX_SERVER: "${{ secrets.MATRIX_SERVER }}"
MATRIX_ROOM: "${{ secrets.MATRIX_ROOM }}"
MATRIX_USER_ID: "${{ secrets.MATRIX_USER_ID }}"
MATRIX_TOKEN: "${{ secrets.MATRIX_TOKEN }}"
MATRIX_DEVICE_ID: "${{ secrets.MATRIX_DEVICE_ID }}"
uses: docker://keybaseio/client:stable-node
with:
args: .github/workflows/support-files/notifications/entry_point.sh
@@ -2,6 +2,13 @@ KEYBASE_NYM_CHANNEL=
KEYBASE_NYMBOT_USERNAME=
KEYBASE_NYMBOT_PAPERKEY=
MATRIX_SERVER=
MATRIX_ROOM=
MATRIX_ROOM_OF_SHAME=
MATRIX_USER_ID=
MATRIX_TOKEN=
MATRIX_DEVICE_ID=
NYM_NOTIFICATION_KIND=nightly
NYM_PROJECT_NAME=Nightly Build
+3 -1
View File
@@ -2,4 +2,6 @@ node_modules
.idea
# don't commit the lock file to avoid cross-platform issues
package-lock.json
package-lock.json
scratch
@@ -1,6 +1,7 @@
require('dotenv').config();
const Bot = require('keybase-bot');
const { sendMatrixMessage } = require('./send_message_to_matrix');
let context = {
kinds: ['nym-wallet', 'ts-packages', 'network-explorer', 'nightly', 'nym-connect','security'],
@@ -38,6 +39,28 @@ function validateContext() {
'Paperkey is not defined. Please set env var KEYBASE_NYMBOT_PAPERKEY',
);
}
if (context.env.MATRIX_ROOM) {
if (!context.env.MATRIX_SERVER) {
throw new Error(
'Matrix server is not defined. Please set env var MATRIX_SERVER',
);
}
if (!context.env.MATRIX_USER_ID) {
throw new Error(
'Matrix user id is not defined. Please set env var MATRIX_USER_ID',
);
}
if (!context.env.MATRIX_TOKEN) {
throw new Error(
'Matrix token is not defined. Please set env var MATRIX_TOKEN',
);
}
if (!context.env.MATRIX_DEVICE_ID) {
throw new Error(
'Matrix device id is not defined. Please set env var MATRIX_DEVICE_ID',
);
}
}
}
/**
@@ -147,6 +170,13 @@ async function main() {
console.log('-----------------------------------------');
}
await sendKeybaseMessage(messageBody);
if(context.env.MATRIX_ROOM) {
await sendMatrixMessage(context, messageBody, context.env.MATRIX_ROOM)
}
if(context.env.MATRIX_ROOM_OF_SHAME && context.env.IS_SUCCESS !== 'true') {
// when a job fails
await sendMatrixMessage(context, messageBody, context.env.MATRIX_ROOM_OF_SHAME)
}
}
// call main function and let NodeJS handle the promise
@@ -0,0 +1,80 @@
const sdk = require('matrix-js-sdk');
global.Olm = require('olm');
const { LocalStorage } = require('node-localstorage');
const localStorage = new LocalStorage('./scratch');
const {
LocalStorageCryptoStore,
} = require('matrix-js-sdk/lib/crypto/store/localStorage-crypto-store');
const vfile = require('to-vfile');
const unified = require('unified');
const remarkParse = require('remark-parse');
const remarkHtml = require('remark-html');
const emoji = require('remark-emoji');
// hide all matrix client output
console.error = (error) => console.log('❌ error: ', error);
process.stderr.write = () => {};
process.stdout.write = () => {};
function createClient(context, room, message) {
const server = context.env.MATRIX_SERVER;
const token = context.env.MATRIX_TOKEN;
const deviceId = context.env.MATRIX_DEVICE_ID;
const userId = context.env.MATRIX_USER_ID;
const client = sdk.createClient({
baseUrl: server,
accessToken: token,
userId,
deviceId,
sessionStore: new sdk.WebStorageSessionStore(localStorage),
cryptoStore: new LocalStorageCryptoStore(localStorage),
});
client.on('sync', async function(state, prevState, res) {
if (state !== 'PREPARED') return;
client.setGlobalErrorOnUnknownDevices(false);
try {
await client.joinRoom(room);
await client.sendEvent(
room,
'm.room.message',
{
msgtype: 'm.text',
format: 'org.matrix.custom.html',
body: message,
formatted_body: message,
},
'',
);
} catch (error) {
console.error('Job failed: ' + error.message);
}
client.stopClient();
process.exit(0);
});
return client;
}
async function markdownToHtml(messageAsMarkdown) {
const file = await unified()
.use(emoji)
.use(remarkParse)
.use(remarkHtml)
.process(await vfile({ path: 'test.md', contents: messageAsMarkdown}));
return String(file);
}
async function sendMatrixMessage(contextArg, messageAsMarkdown, roomId) {
const messageAsHtml = await markdownToHtml(messageAsMarkdown);
const client = createClient(contextArg, roomId, messageAsHtml);
await client.initCrypto();
await client.startClient({ initialSyncLimit: 1 });
}
module.exports = {
sendMatrixMessage,
};
+9 -1
View File
@@ -11,7 +11,15 @@
"dotenv": "^16.0.0",
"handlebars": "^4.7.7",
"keybase-bot": "^3.6.1",
"octokit": "^1.7.1"
"matrix-js-sdk": "^9.3.0",
"node-localstorage": "^2.1.6",
"octokit": "^1.7.1",
"olm": "https://packages.matrix.org/npm/olm/olm-3.2.1.tgz",
"remark-emoji": "^2.2.0",
"remark-html": "^13.0.2",
"remark-parse": "^9.0.0",
"to-vfile": "^6.1.0",
"unified": "^9.2.2"
},
"devDependencies": {
"prettier": "2.3.2"
+3 -1
View File
@@ -38,4 +38,6 @@ validator-config
validator-api-config.toml
dist
storybook-static
envs/qwerty.env
envs/qwerty.env
Cargo.lock
nym-connect/Cargo.lock
+7 -5
View File
@@ -1,6 +1,8 @@
{
"mainnet":[{
"nymd_url":"https://rpc.nyx.nodes.guru/",
"api_url":"https://api.nyx.nodes.guru/"
}]
}
"mainnet": [
{
"nyxd_url": "https://rpc.nyx.nodes.guru/",
"api_url": "https://api.nyx.nodes.guru/"
}
]
}
+29 -14
View File
@@ -6,24 +6,39 @@ Post 1.0.0 release, the changelog format is based on [Keep a Changelog](https://
### Added
- socks5: send status message for service ready, and network-requester error response
- nym-sdk: added initial version of a Rust client sdk
### Changed
- all-binaries: improved error logging ([#2686])
- native client: bring shutdown logic up to the same level as socks5-client
- nym-api, coconut-dkg contract: automatic, time-based dkg epoch state advancement ([#2670])
- renamed all references to validator_api to nym_api
- renamed all references to nymd to nyxd
- all-binaries: standarised argument names (note: old names should still be accepted) ([#2762]
### Fixed
- nym-api: should now correctly use `rewarding.enabled` config flag ([#2753])
[#2686]: https://github.com/nymtech/nym/pull/2686
[#2670]: https://github.com/nymtech/nym/pull/2670
[#2753]: https://github.com/nymtech/nym/pull/2753
[#2762]: https://github.com/nymtech/nym/pull/2762
## [v1.1.5] (2022-01-10)
### Added
- socks5: send status message for service ready, and network-requester error response in https://github.com/nymtech/nym/pull/2715
### Changed
- all-binaries: improved error logging in https://github.com/nymtech/nym/pull/2686
- native client: bring shutdown logic up to the same level as socks5-client in https://github.com/nymtech/nym/pull/2695
- nym-api, coconut-dkg contract: automatic, time-based dkg epoch state advancement in https://github.com/nymtech/nym/pull/2670
- DKG resharing unit test by @neacsu in https://github.com/nymtech/nym/pull/2668
- Renaming validator-api to nym-api by @futurechimp in https://github.com/nymtech/nym/pull/1863
- Modify wasm specific make targets by @neacsu in https://github.com/nymtech/nym/pull/2693
- client: create websocket handler builder by @octol in https://github.com/nymtech/nym/pull/2700
- Outfox and Lion by @durch in https://github.com/nymtech/nym/pull/2730
- Feature/multi surb transmission lanes by @jstuczyn in https://github.com/nymtech/nym/pull/2723
## [v1.1.4] (2022-12-20)
This release adds multiple Single Use Reply Blocks (SURBs) to allow arbitrarily-sized anonymized replies.
@@ -45,7 +60,7 @@ The release also include some additional work for distributed key generation in
### Changed
- validator-api: can recover from shutdown during DKG process ([#1872])
- clients: deduplicate gateway inititialization, part of work towards a rust-sdk
- clients: deduplicate gateway initialization, part of work towards a rust-sdk
- clients: keep all transmission lanes going at all times by making priority probabilistic
- clients: ability to use multi-reply SURBs to send arbitrarily long messages fully anonymously whilst requesting additional reply blocks whenever they're about to run out ([#1796], [#1801], [#1804], [#1835], [#1858], [#1883]))
@@ -120,7 +135,7 @@ The release also include some additional work for distributed key generation in
- native-client/socks5-client/wasm-client: `use_extended_packet_size` Debug config option to make the client use 'ExtendedPacketSize' for its traffic (32kB as opposed to 2kB in 1.0.2) ([#1671])
- network-requester: added additional Blockstream Green wallet endpoint to `example.allowed.list` ([#1611])
- validator-api: add `interval_operating_cost` and `profit_margin_percent` to compute reward estimation endpoint
- validator-client: added `query_contract_smart` and `query_contract_raw` on `NymdClient` ([#1558])
- validator-client: added `query_contract_smart` and `query_contract_raw` on `NyxdClient` ([#1558])
- wasm-client: uses updated wasm-compatible `client-core` so that it's now capable of packet retransmission, cover traffic and poisson delay (among other things!) ([#1673])
### Fixed
@@ -215,7 +230,7 @@ The release also include some additional work for distributed key generation in
- All binaries and cosmwasm blobs are configured at runtime now; binaries are configured using environment variables or .env files and contracts keep the configuration parameters in storage ([#1463])
- gateway, network-statistics: include gateway id in the sent statistical data ([#1478])
- network explorer: tweak how active set probability is shown ([#1503])
- validator-api: rewarder set update fails without panicking on possible nymd queries ([#1520])
- validator-api: rewarder set update fails without panicking on possible nyxd queries ([#1520])
- network-requester, socks5 client (nym-connect): send and receive respectively a message error to be displayed about filter check failure ([#1576])
[#1249]: https://github.com/nymtech/nym/pull/1249
@@ -588,14 +603,14 @@ The release also include some additional work for distributed key generation in
- Feature/update wallet with stake rates [\#739](https://github.com/nymtech/nym/pull/739) ([neacsu](https://github.com/neacsu))
- Add stake reward rates and bump version of client [\#738](https://github.com/nymtech/nym/pull/738) ([neacsu](https://github.com/neacsu))
- Bump next from 10.1.3 to 11.1.0 in /wallet-web [\#737](https://github.com/nymtech/nym/pull/737) ([dependabot[bot]](https://github.com/apps/dependabot))
- Feature/nymd client integration [\#736](https://github.com/nymtech/nym/pull/736) ([jstuczyn](https://github.com/jstuczyn))
- Feature/nyxd client integration [\#736](https://github.com/nymtech/nym/pull/736) ([jstuczyn](https://github.com/jstuczyn))
- Bug/fix parking lot on wasm [\#735](https://github.com/nymtech/nym/pull/735) ([neacsu](https://github.com/neacsu))
- Explorer API: add new HTTP resource to decorate mix nodes with geoip locations [\#734](https://github.com/nymtech/nym/pull/734) ([mmsinclair](https://github.com/mmsinclair))
- Feature/completing nymd client api [\#732](https://github.com/nymtech/nym/pull/732) ([jstuczyn](https://github.com/jstuczyn))
- Feature/completing nyxd client api [\#732](https://github.com/nymtech/nym/pull/732) ([jstuczyn](https://github.com/jstuczyn))
- Explorer API - add port check and node description/stats proxy [\#731](https://github.com/nymtech/nym/pull/731) ([mmsinclair](https://github.com/mmsinclair))
- Feature/nymd client fee handling [\#730](https://github.com/nymtech/nym/pull/730) ([jstuczyn](https://github.com/jstuczyn))
- Feature/nyxd client fee handling [\#730](https://github.com/nymtech/nym/pull/730) ([jstuczyn](https://github.com/jstuczyn))
- Update DelegationCheck.tsx [\#725](https://github.com/nymtech/nym/pull/725) ([jessgess](https://github.com/jessgess))
- Rust nymd/cosmwasm client [\#724](https://github.com/nymtech/nym/pull/724) ([jstuczyn](https://github.com/jstuczyn))
- Rust nyxd/cosmwasm client [\#724](https://github.com/nymtech/nym/pull/724) ([jstuczyn](https://github.com/jstuczyn))
- Removed wasm feature bypassing cyclic dependencies [\#723](https://github.com/nymtech/nym/pull/723) ([jstuczyn](https://github.com/jstuczyn))
- Updated used sphinx dependency to the most recent revision [\#722](https://github.com/nymtech/nym/pull/722) ([jstuczyn](https://github.com/jstuczyn))
- update state management and validation [\#721](https://github.com/nymtech/nym/pull/721) ([fmtabbara](https://github.com/fmtabbara))
@@ -614,7 +629,7 @@ The release also include some additional work for distributed key generation in
- Bond and delegation alerts [\#698](https://github.com/nymtech/nym/pull/698) ([fmtabbara](https://github.com/fmtabbara))
- Bugfix/network monitor version check [\#697](https://github.com/nymtech/nym/pull/697) ([jstuczyn](https://github.com/jstuczyn))
- Feature/other containers [\#692](https://github.com/nymtech/nym/pull/692) ([neacsu](https://github.com/neacsu))
- Using validator API instead of nymd [\#690](https://github.com/nymtech/nym/pull/690) ([futurechimp](https://github.com/futurechimp))
- Using validator API instead of nyxd [\#690](https://github.com/nymtech/nym/pull/690) ([futurechimp](https://github.com/futurechimp))
- Hang coconut issuance off the validator-api [\#679](https://github.com/nymtech/nym/pull/679) ([durch](https://github.com/durch))
- Update hmac and blake3 [\#673](https://github.com/nymtech/nym/pull/673) ([durch](https://github.com/durch))
Generated
+69 -34
View File
@@ -686,7 +686,7 @@ dependencies = [
[[package]]
name = "client-core"
version = "1.1.4"
version = "1.1.5"
dependencies = [
"async-trait",
"client-connections",
@@ -1788,7 +1788,7 @@ dependencies = [
[[package]]
name = "explorer-api"
version = "1.1.1"
version = "1.1.2"
dependencies = [
"chrono",
"clap 4.0.26",
@@ -1970,9 +1970,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]]
name = "futures"
version = "0.3.24"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f21eda599937fba36daeb58a22e8f5cee2d14c4a17b5b7739c7c8e5e3b8230c"
checksum = "38390104763dc37a5145a53c29c63c1290b5d316d6086ec32c293f6736051bb0"
dependencies = [
"futures-channel",
"futures-core",
@@ -1985,9 +1985,9 @@ dependencies = [
[[package]]
name = "futures-channel"
version = "0.3.24"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30bdd20c28fadd505d0fd6712cdfcb0d4b5648baf45faef7f852afb2399bb050"
checksum = "52ba265a92256105f45b719605a571ffe2d1f0fea3807304b522c1d778f79eed"
dependencies = [
"futures-core",
"futures-sink",
@@ -1995,15 +1995,15 @@ dependencies = [
[[package]]
name = "futures-core"
version = "0.3.24"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e5aa3de05362c3fb88de6531e6296e85cde7739cccad4b9dfeeb7f6ebce56bf"
checksum = "04909a7a7e4633ae6c4a9ab280aeb86da1236243a77b694a49eacd659a4bd3ac"
[[package]]
name = "futures-executor"
version = "0.3.24"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ff63c23854bee61b6e9cd331d523909f238fc7636290b96826e9cfa5faa00ab"
checksum = "7acc85df6714c176ab5edf386123fafe217be88c0840ec11f199441134a074e2"
dependencies = [
"futures-core",
"futures-task",
@@ -2023,15 +2023,15 @@ dependencies = [
[[package]]
name = "futures-io"
version = "0.3.24"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbf4d2a7a308fd4578637c0b17c7e1c7ba127b8f6ba00b29f717e9655d85eb68"
checksum = "00f5fb52a06bdcadeb54e8d3671f8888a39697dcb0b81b23b55174030427f4eb"
[[package]]
name = "futures-macro"
version = "0.3.24"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42cd15d1c7456c04dbdf7e88bcd69760d74f3a798d6444e16974b505b0e62f17"
checksum = "bdfb8ce053d86b91919aad980c220b1fb8401a9394410e1c289ed7e66b61835d"
dependencies = [
"proc-macro2",
"quote",
@@ -2040,21 +2040,21 @@ dependencies = [
[[package]]
name = "futures-sink"
version = "0.3.24"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b20ba5a92e727ba30e72834706623d94ac93a725410b6a6b6fbc1b07f7ba56"
checksum = "39c15cf1a4aa79df40f1bb462fb39676d0ad9e366c2a33b590d7c66f4f81fcf9"
[[package]]
name = "futures-task"
version = "0.3.24"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6508c467c73851293f390476d4491cf4d227dbabcd4170f3bb6044959b294f1"
checksum = "2ffb393ac5d9a6eaa9d3fdf37ae2776656b706e200c8e16b1bdb227f5198e6ea"
[[package]]
name = "futures-util"
version = "0.3.24"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44fb6cb1be61cc1d2e43b262516aafcf63b241cffdb1d3fa115f91d9c7b09c90"
checksum = "197676987abd2f9cadff84926f410af1c183608d36641465df73ae8211dc65d6"
dependencies = [
"futures-channel",
"futures-core",
@@ -2085,6 +2085,7 @@ dependencies = [
"nymsphinx",
"pemstore",
"rand 0.7.3",
"serde",
"task",
"thiserror",
"tokio",
@@ -3233,7 +3234,7 @@ dependencies = [
[[package]]
name = "nym-api"
version = "1.1.4"
version = "1.1.5"
dependencies = [
"anyhow",
"async-trait",
@@ -3329,7 +3330,7 @@ dependencies = [
[[package]]
name = "nym-cli"
version = "1.1.4"
version = "1.1.5"
dependencies = [
"anyhow",
"base64",
@@ -3360,14 +3361,18 @@ dependencies = [
"bs58",
"cfg-if 1.0.0",
"clap 4.0.26",
"coconut-bandwidth-contract-common",
"coconut-dkg-common",
"comfy-table",
"cosmrs",
"cosmwasm-std",
"cw-utils",
"handlebars",
"humantime-serde",
"k256",
"log",
"mixnet-contract-common",
"multisig-contract-common",
"network-defaults",
"rand 0.6.5",
"serde",
@@ -3383,7 +3388,7 @@ dependencies = [
[[package]]
name = "nym-client"
version = "1.1.4"
version = "1.1.5"
dependencies = [
"build-information",
"clap 4.0.26",
@@ -3423,10 +3428,11 @@ dependencies = [
[[package]]
name = "nym-gateway"
version = "1.1.4"
version = "1.1.5"
dependencies = [
"anyhow",
"async-trait",
"atty",
"bip39",
"bs58",
"build-information",
@@ -3450,12 +3456,14 @@ dependencies = [
"mixnode-common",
"network-defaults",
"nym-api-requests",
"nym-types",
"nymsphinx",
"once_cell",
"pemstore",
"pretty_env_logger",
"rand 0.7.3",
"serde",
"serde_json",
"sqlx 0.5.11",
"statistics-common",
"subtle-encoding",
@@ -3471,9 +3479,10 @@ dependencies = [
[[package]]
name = "nym-mixnode"
version = "1.1.4"
version = "1.1.5"
dependencies = [
"anyhow",
"atty",
"bs58",
"build-information",
"clap 4.0.26",
@@ -3492,6 +3501,7 @@ dependencies = [
"mixnet-client",
"mixnode-common",
"nonexhaustive-delayqueue",
"nym-types",
"nymsphinx",
"nymsphinx-params",
"nymsphinx-types",
@@ -3500,6 +3510,7 @@ dependencies = [
"rand 0.7.3",
"rocket",
"serde",
"serde_json",
"sysinfo",
"task",
"tokio",
@@ -3513,7 +3524,7 @@ dependencies = [
[[package]]
name = "nym-network-requester"
version = "1.1.4"
version = "1.1.5"
dependencies = [
"async-trait",
"clap 4.0.26",
@@ -3545,7 +3556,7 @@ dependencies = [
[[package]]
name = "nym-network-statistics"
version = "1.1.4"
version = "1.1.5"
dependencies = [
"dirs",
"log",
@@ -3575,9 +3586,33 @@ dependencies = [
"zeroize",
]
[[package]]
name = "nym-sdk"
version = "0.1.0"
dependencies = [
"client-connections",
"client-core",
"crypto",
"futures",
"gateway-client",
"gateway-requests",
"log",
"logging",
"network-defaults",
"nymsphinx",
"pretty_env_logger",
"rand 0.7.3",
"tap",
"task",
"thiserror",
"tokio",
"toml",
"url",
]
[[package]]
name = "nym-socks5-client"
version = "1.1.4"
version = "1.1.5"
dependencies = [
"build-information",
"clap 4.0.26",
@@ -5977,18 +6012,18 @@ checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb"
[[package]]
name = "thiserror"
version = "1.0.37"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e"
checksum = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.37"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb"
checksum = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f"
dependencies = [
"proc-macro2",
"quote",
@@ -6208,9 +6243,9 @@ dependencies = [
[[package]]
name = "toml"
version = "0.5.8"
version = "0.5.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa"
checksum = "1333c76748e868a4d9d1017b5ab53171dfd095f70c712fdb4653a406547f598f"
dependencies = [
"serde",
]
+1
View File
@@ -73,6 +73,7 @@ members = [
"gateway/gateway-requests",
"integrations/bity",
"mixnode",
"sdk/rust/nym-sdk",
"service-providers/network-requester",
"service-providers/network-statistics",
"nym-api",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "client-core"
version = "1.1.4"
version = "1.1.5"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
edition = "2021"
rust-version = "1.66"
@@ -33,12 +33,15 @@ use log::{debug, info};
use nymsphinx::acknowledgements::AckKey;
use nymsphinx::addressing::clients::Recipient;
use nymsphinx::addressing::nodes::NodeIdentity;
use nymsphinx::receiver::ReconstructedMessage;
use std::sync::Arc;
use std::time::Duration;
use tap::TapFallible;
use task::{TaskClient, TaskManager};
use url::Url;
use super::received_buffer::ReceivedBufferMessage;
#[cfg(all(not(target_arch = "wasm32"), feature = "fs-surb-storage"))]
pub mod non_wasm_helpers;
@@ -48,10 +51,30 @@ pub struct ClientInput {
}
pub struct ClientOutput {
pub shared_lane_queue_lengths: LaneQueueLengths,
pub received_buffer_request_sender: ReceivedBufferRequestSender,
}
impl ClientOutput {
pub fn register_receiver(
&mut self,
) -> Result<mpsc::UnboundedReceiver<Vec<ReconstructedMessage>>, ClientCoreError> {
let (reconstructed_sender, reconstructed_receiver) = mpsc::unbounded();
self.received_buffer_request_sender
.unbounded_send(ReceivedBufferMessage::ReceiverAnnounce(
reconstructed_sender,
))
.map_err(|_| ClientCoreError::FailedToRegisterReceiver)?;
Ok(reconstructed_receiver)
}
}
pub struct ClientState {
pub shared_lane_queue_lengths: LaneQueueLengths,
pub reply_controller_sender: ReplyControllerSender,
}
pub enum ClientInputStatus {
AwaitingProducer { client_input: ClientInput },
Connected,
@@ -80,6 +103,32 @@ impl ClientOutputStatus {
}
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum CredentialsToggle {
Enabled,
Disabled,
}
impl CredentialsToggle {
pub fn is_enabled(&self) -> bool {
self == &CredentialsToggle::Enabled
}
pub fn is_disabled(&self) -> bool {
self == &CredentialsToggle::Disabled
}
}
impl From<bool> for CredentialsToggle {
fn from(value: bool) -> Self {
if value {
CredentialsToggle::Enabled
} else {
CredentialsToggle::Disabled
}
}
}
pub struct BaseClientBuilder<'a, B> {
// due to wasm limitations I had to split it like this : (
gateway_config: &'a GatewayEndpointConfig,
@@ -119,13 +168,13 @@ where
key_manager: KeyManager,
bandwidth_controller: Option<BandwidthController>,
reply_storage_backend: B,
disabled_credentials: bool,
credentials_toggle: CredentialsToggle,
nym_api_endpoints: Vec<Url>,
) -> BaseClientBuilder<'a, B> {
BaseClientBuilder {
gateway_config,
debug_config,
disabled_credentials,
disabled_credentials: credentials_toggle.is_disabled(),
nym_api_endpoints,
reply_storage_backend,
bandwidth_controller,
@@ -248,7 +297,7 @@ where
.map_err(ClientCoreError::UnableToCreatePublicKeyFromGatewayId)?;
// disgusting wasm workaround since there's no key persistence there (nor `client init`)
let shared_key = if self.key_manager.gateway_key_set() {
let shared_key = if self.key_manager.is_gateway_key_set() {
Some(self.key_manager.gateway_shared_key())
} else {
None
@@ -475,11 +524,13 @@ where
},
client_output: ClientOutputStatus::AwaitingConsumer {
client_output: ClientOutput {
shared_lane_queue_lengths,
received_buffer_request_sender,
},
},
reply_controller_sender,
client_state: ClientState {
shared_lane_queue_lengths,
reply_controller_sender,
},
task_manager,
})
}
@@ -488,9 +539,7 @@ where
pub struct BaseClient {
pub client_input: ClientInputStatus,
pub client_output: ClientOutputStatus,
// it feels very wrong to put this channel here, but I can't think of any other way of passing it to the native client
pub reply_controller_sender: ReplyControllerSender,
pub client_state: ClientState,
pub task_manager: TaskManager,
}
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
use crate::client::replies::reply_storage::{
fs_backend, CombinedReplyStorage, ReplyStorageBackend,
self, fs_backend, CombinedReplyStorage, ReplyStorageBackend,
};
use crate::config::DebugConfig;
use crate::error::ClientCoreError;
@@ -85,3 +85,10 @@ pub async fn setup_fs_reply_surb_backend<P: AsRef<Path>>(
setup_fresh_backend(db_path, debug_config).await
}
}
pub fn setup_empty_reply_surb_backend(debug_config: &DebugConfig) -> reply_storage::Empty {
reply_storage::Empty {
min_surb_threshold: debug_config.minimum_reply_surb_storage_threshold,
max_surb_threshold: debug_config.maximum_reply_surb_storage_threshold,
}
}
+97 -21
View File
@@ -17,6 +17,7 @@ use std::sync::Arc;
// use the old key after new one was issued.
// Remember that Arc<T> has Deref implementation for T
#[derive(Clone)]
pub struct KeyManager {
/// identity key associated with the client instance.
identity_keypair: Arc<identity::KeyPair>,
@@ -57,16 +58,22 @@ impl KeyManager {
}
}
// this is actually **NOT** dead code
// I have absolutely no idea why the compiler insists it's unused. The call happens during client::init::execute
#[allow(dead_code)]
/// After shared key with the gateway is derived, puts its ownership to this instance of a [`KeyManager`].
pub fn insert_gateway_shared_key(&mut self, gateway_shared_key: Arc<SharedKeys>) {
self.gateway_shared_key = Some(gateway_shared_key)
pub fn from_keys(
id_keypair: identity::KeyPair,
enc_keypair: encryption::KeyPair,
gateway_shared_key: SharedKeys,
ack_key: AckKey,
) -> Self {
Self {
identity_keypair: Arc::new(id_keypair),
encryption_keypair: Arc::new(enc_keypair),
gateway_shared_key: Some(Arc::new(gateway_shared_key)),
ack_key: Arc::new(ack_key),
}
}
/// Loads previously stored keys from the disk.
pub fn load_keys(client_pathfinder: &ClientKeyPathfinder) -> io::Result<Self> {
/// Loads previously stored client keys from the disk.
fn load_client_keys(client_pathfinder: &ClientKeyPathfinder) -> io::Result<Self> {
let identity_keypair: identity::KeyPair =
pemstore::load_keypair(&pemstore::KeyPairPath::new(
client_pathfinder.private_identity_key().to_owned(),
@@ -78,21 +85,51 @@ impl KeyManager {
client_pathfinder.public_encryption_key().to_owned(),
))?;
let gateway_shared_key: SharedKeys =
pemstore::load_key(client_pathfinder.gateway_shared_key())?;
let ack_key: AckKey = pemstore::load_key(client_pathfinder.ack_key())?;
// TODO: ack key is never stored so it is generated now. But perhaps it should be stored
// after all for consistency sake?
Ok(KeyManager {
identity_keypair: Arc::new(identity_keypair),
encryption_keypair: Arc::new(encryption_keypair),
gateway_shared_key: Some(Arc::new(gateway_shared_key)),
gateway_shared_key: None,
ack_key: Arc::new(ack_key),
})
}
/// Loads previously stored keys from the disk. Fails if not all, including the shared gateway
/// key, is available.
pub fn load_keys(client_pathfinder: &ClientKeyPathfinder) -> io::Result<Self> {
let mut key_manager = Self::load_client_keys(client_pathfinder)?;
let gateway_shared_key: SharedKeys =
pemstore::load_key(client_pathfinder.gateway_shared_key())?;
key_manager.gateway_shared_key = Some(Arc::new(gateway_shared_key));
Ok(key_manager)
}
/// Loads previously stored keys from the disk. Fails if client keys are not availabe, but the
/// shared gateway key is optional.
pub fn load_keys_but_gateway_is_optional(
client_pathfinder: &ClientKeyPathfinder,
) -> io::Result<Self> {
let mut key_manager = Self::load_client_keys(client_pathfinder)?;
let gateway_shared_key: Result<SharedKeys, io::Error> =
pemstore::load_key(client_pathfinder.gateway_shared_key());
// It's ok if the gateway key was not found
let gateway_shared_key = match gateway_shared_key {
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
Ok(key) => Ok(Some(key)),
}?;
key_manager.gateway_shared_key = gateway_shared_key.map(Arc::new);
Ok(key_manager)
}
// this is actually **NOT** dead code
// I have absolutely no idea why the compiler insists it's unused. The call happens during client::init::execute
#[allow(dead_code)]
@@ -119,7 +156,7 @@ impl KeyManager {
pemstore::store_key(self.ack_key.as_ref(), client_pathfinder.ack_key())?;
match self.gateway_shared_key.as_ref() {
None => warn!("No gateway shared key available to store!"),
None => debug!("No gateway shared key available to store!"),
Some(gate_key) => {
pemstore::store_key(gate_key.as_ref(), client_pathfinder.gateway_shared_key())?
}
@@ -128,16 +165,60 @@ impl KeyManager {
Ok(())
}
pub fn store_gateway_key(&self, client_pathfinder: &ClientKeyPathfinder) -> io::Result<()> {
match self.gateway_shared_key.as_ref() {
None => {
return Err(io::Error::new(
io::ErrorKind::Other,
"trying to store a non-existing key",
))
}
Some(gate_key) => {
pemstore::store_key(gate_key.as_ref(), client_pathfinder.gateway_shared_key())?
}
}
Ok(())
}
/// Overwrite the existing identity keypair
pub fn set_identity_keypair(&mut self, id_keypair: identity::KeyPair) {
self.identity_keypair = Arc::new(id_keypair);
}
/// Gets an atomically reference counted pointer to [`identity::KeyPair`].
pub fn identity_keypair(&self) -> Arc<identity::KeyPair> {
Arc::clone(&self.identity_keypair)
}
/// Overwrite the existing encryption keypair
pub fn set_encryption_keypair(&mut self, enc_keypair: encryption::KeyPair) {
self.encryption_keypair = Arc::new(enc_keypair);
}
/// Gets an atomically reference counted pointer to [`encryption::KeyPair`].
pub fn encryption_keypair(&self) -> Arc<encryption::KeyPair> {
Arc::clone(&self.encryption_keypair)
}
/// Overwrite the existing ack key
pub fn set_ack_key(&mut self, ack_key: AckKey) {
self.ack_key = Arc::new(ack_key);
}
/// Gets an atomically reference counted pointer to [`AckKey`].
pub fn ack_key(&self) -> Arc<AckKey> {
Arc::clone(&self.ack_key)
}
// this is actually **NOT** dead code
// I have absolutely no idea why the compiler insists it's unused. The call happens during client::init::execute
#[allow(dead_code)]
/// After shared key with the gateway is derived, puts its ownership to this instance of a [`KeyManager`].
pub fn insert_gateway_shared_key(&mut self, gateway_shared_key: Arc<SharedKeys>) {
self.gateway_shared_key = Some(gateway_shared_key)
}
/// Gets an atomically reference counted pointer to [`SharedKey`].
// since this function is not fully public, it is not expected to be used externally and
// hence it's up to us to ensure it's called in correct context
@@ -149,12 +230,7 @@ impl KeyManager {
)
}
pub fn gateway_key_set(&self) -> bool {
pub fn is_gateway_key_set(&self) -> bool {
self.gateway_shared_key.is_some()
}
/// Gets an atomically reference counted pointer to [`AckKey`].
pub fn ack_key(&self) -> Arc<AckKey> {
Arc::clone(&self.ack_key)
}
}
@@ -213,7 +213,11 @@ impl ActionController {
}
// note: when the entry expires it's automatically removed from pending_acks_timers
fn handle_expired_ack_timer(&mut self, expired_ack: Expired<FragmentIdentifier>) {
fn handle_expired_ack_timer(
&mut self,
expired_ack: Expired<FragmentIdentifier>,
task_client: &mut task::TaskClient,
) {
// I'm honestly not sure how to handle it, because getting it means other things in our
// system are already misbehaving. If we ever see this panic, then I guess we should worry
// about it. Perhaps just reschedule it at later point?
@@ -231,9 +235,16 @@ impl ActionController {
// downgrading an arc and then upgrading vs cloning is difference of 30ns vs 15ns
// so it's literally a NO difference while it might prevent us from unnecessarily
// resending data (in maybe 1 in 1 million cases, but it's something)
self.retransmission_sender
if self
.retransmission_sender
.unbounded_send(Arc::downgrade(pending_ack_data))
.unwrap()
.is_err()
{
assert!(
task_client.is_shutdown_poll(),
"Failed to send pending ack for retransmission"
);
}
} else {
// this shouldn't cause any issues but shouldn't have happened to begin with!
error!("An already removed pending ack has expired")
@@ -264,7 +275,7 @@ impl ActionController {
}
},
expired_ack = self.pending_acks_timers.next() => match expired_ack {
Some(expired_ack) => self.handle_expired_ack_timer(expired_ack),
Some(expired_ack) => self.handle_expired_ack_timer(expired_ack, &mut shutdown),
None => {
log::trace!("ActionController: Stopping since ack channel closed");
break;
@@ -275,10 +286,7 @@ impl ActionController {
}
}
}
#[cfg(not(target_arch = "wasm32"))]
tokio::time::timeout(Duration::from_secs(5), shutdown.recv())
.await
.expect("Task stopped without shutdown called");
shutdown.recv_timeout().await;
log::debug!("ActionController: Exiting");
}
}
@@ -535,9 +535,7 @@ where
}
}
}
tokio::time::timeout(Duration::from_secs(5), shutdown.recv())
.await
.expect("Task stopped without shutdown called");
shutdown.recv_timeout().await;
}
#[cfg(target_arch = "wasm32")]
@@ -99,6 +99,24 @@ impl ReplyControllerSender {
}
}
pub struct ReplyQueueLengths {
reply_controller_sender: ReplyControllerSender,
}
impl ReplyQueueLengths {
pub fn new(reply_controller_sender: ReplyControllerSender) -> Self {
Self {
reply_controller_sender,
}
}
pub async fn get_lane_queue_length(&self, connection_id: ConnectionId) -> usize {
self.reply_controller_sender
.get_lane_queue_length(connection_id)
.await
}
}
pub(crate) type ReplyControllerReceiver = mpsc::UnboundedReceiver<ReplyControllerMessage>;
#[derive(Debug)]
@@ -7,6 +7,7 @@ use async_trait::async_trait;
// well, right now we don't have the browser storage : (
// so we keep everything in memory
#[derive(Debug)]
pub struct Backend {
empty: Empty,
}
@@ -19,10 +19,11 @@ pub mod fs_backend;
#[error("no information provided")]
pub struct UndefinedError;
#[derive(Debug)]
pub struct Empty {
// we need to keep 'basic' metadata here to "load" the CombinedReplyStorage
min_surb_threshold: usize,
max_surb_threshold: usize,
pub min_surb_threshold: usize,
pub max_surb_threshold: usize,
}
#[async_trait]
@@ -152,7 +152,7 @@ impl TopologyRefresherConfig {
}
pub struct TopologyRefresher {
validator_client: validator_client::client::ApiClient,
validator_client: validator_client::client::NymApiClient,
client_version: String,
nym_api_urls: Vec<Url>,
@@ -168,7 +168,9 @@ impl TopologyRefresher {
cfg.nym_api_urls.shuffle(&mut thread_rng());
TopologyRefresher {
validator_client: validator_client::client::ApiClient::new(cfg.nym_api_urls[0].clone()),
validator_client: validator_client::client::NymApiClient::new(
cfg.nym_api_urls[0].clone(),
),
client_version: cfg.client_version,
nym_api_urls: cfg.nym_api_urls,
topology_accessor,
+37 -9
View File
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use config::{NymConfig, DB_FILE_NAME};
use config::{NymConfig, OptionalSet, DB_FILE_NAME};
use nymsphinx::params::PacketSize;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
@@ -70,12 +70,15 @@ pub struct Config<T> {
#[serde(default)]
debug: DebugConfig,
}
impl<T> ClientCoreConfigTrait for Config<T> {
fn get_gateway_endpoint(&self) -> &GatewayEndpointConfig {
&self.client.gateway_endpoint
}
}
impl<T> OptionalSet for Config<T> where T: NymConfig {}
impl<T> Config<T> {
pub fn new<S: Into<String>>(id: S) -> Self
where
@@ -160,8 +163,9 @@ impl<T> Config<T> {
changes_made
}
pub fn with_disabled_credentials(&mut self, disabled_credentials_mode: bool) {
pub fn with_disabled_credentials(mut self, disabled_credentials_mode: bool) -> Self {
self.client.disabled_credentials_mode = disabled_credentials_mode;
self
}
pub fn with_gateway_endpoint(&mut self, gateway_endpoint: GatewayEndpointConfig) {
@@ -172,14 +176,31 @@ impl<T> Config<T> {
self.client.gateway_endpoint.gateway_id = id.into();
}
pub fn set_custom_validators(&mut self, validator_urls: Vec<Url>) {
self.client.validator_urls = validator_urls;
pub fn with_custom_nyxd(mut self, urls: Vec<Url>) -> Self {
self.client.nyxd_urls = urls;
self
}
pub fn set_custom_nyxd(&mut self, nyxd_urls: Vec<Url>) {
self.client.nyxd_urls = nyxd_urls;
}
pub fn with_custom_nym_apis(mut self, nym_api_urls: Vec<Url>) -> Self {
self.client.nym_api_urls = nym_api_urls;
self
}
pub fn set_custom_nym_apis(&mut self, nym_api_urls: Vec<Url>) {
self.client.nym_api_urls = nym_api_urls;
}
pub fn with_high_default_traffic_volume(mut self, enabled: bool) -> Self {
if enabled {
self.set_high_default_traffic_volume();
}
self
}
pub fn set_high_default_traffic_volume(&mut self) {
self.debug.average_packet_delay = Duration::from_millis(10);
// basically don't really send cover messages
@@ -188,6 +209,13 @@ impl<T> Config<T> {
self.debug.message_sending_average_delay = Duration::from_millis(4);
}
pub fn with_disabled_cover_traffic(mut self, disabled: bool) -> Self {
if disabled {
self.set_no_cover_traffic()
}
self
}
pub fn set_no_cover_traffic(&mut self) {
self.debug.disable_loop_cover_traffic_stream = true;
self.debug.disable_main_poisson_packet_distribution = true;
@@ -234,7 +262,7 @@ impl<T> Config<T> {
}
pub fn get_validator_endpoints(&self) -> Vec<Url> {
self.client.validator_urls.clone()
self.client.nyxd_urls.clone()
}
pub fn get_nym_api_endpoints(&self) -> Vec<Url> {
@@ -420,9 +448,9 @@ pub struct Client<T> {
#[serde(default)]
disabled_credentials_mode: bool,
/// Addresses to nymd validators via which the client can communicate with the chain.
#[serde(default)]
validator_urls: Vec<Url>,
/// Addresses to nyxd validators via which the client can communicate with the chain.
#[serde(alias = "validator_urls")]
nyxd_urls: Vec<Url>,
/// Addresses to APIs running on validator from which the client gets the view of the network.
#[serde(alias = "validator_api_urls")]
@@ -476,7 +504,7 @@ impl<T: NymConfig> Default for Client<T> {
version: env!("CARGO_PKG_VERSION").to_string(),
id: "".to_string(),
disabled_credentials_mode: true,
validator_urls: vec![],
nyxd_urls: vec![],
nym_api_urls: vec![],
private_identity_key_file: Default::default(),
public_identity_key_file: Default::default(),
@@ -7,12 +7,12 @@ use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct ClientKeyPathfinder {
identity_private_key: PathBuf,
identity_public_key: PathBuf,
encryption_private_key: PathBuf,
encryption_public_key: PathBuf,
gateway_shared_key: PathBuf,
ack_key: PathBuf,
pub identity_private_key: PathBuf,
pub identity_public_key: PathBuf,
pub encryption_private_key: PathBuf,
pub encryption_public_key: PathBuf,
pub gateway_shared_key: PathBuf,
pub ack_key: PathBuf,
}
impl ClientKeyPathfinder {
@@ -22,8 +22,8 @@ impl ClientKeyPathfinder {
ClientKeyPathfinder {
identity_private_key: config_dir.join("private_identity.pem"),
identity_public_key: config_dir.join("public_identity.pem"),
encryption_private_key: config_dir.join("public_encryption.pem"),
encryption_public_key: config_dir.join("private_encryption.pem"),
encryption_private_key: config_dir.join("private_encryption.pem"),
encryption_public_key: config_dir.join("public_encryption.pem"),
gateway_shared_key: config_dir.join("gateway_shared.pem"),
ack_key: config_dir.join("ack_key.pem"),
}
@@ -40,6 +40,28 @@ impl ClientKeyPathfinder {
}
}
pub fn any_file_exists(&self) -> bool {
matches!(self.identity_public_key.try_exists(), Ok(true))
|| matches!(self.identity_private_key.try_exists(), Ok(true))
|| matches!(self.encryption_public_key.try_exists(), Ok(true))
|| matches!(self.encryption_private_key.try_exists(), Ok(true))
|| matches!(self.gateway_shared_key.try_exists(), Ok(true))
|| matches!(self.ack_key.try_exists(), Ok(true))
}
pub fn any_file_exists_and_return(&self) -> Option<PathBuf> {
file_exists(&self.identity_public_key)
.or_else(|| file_exists(&self.identity_private_key))
.or_else(|| file_exists(&self.encryption_public_key))
.or_else(|| file_exists(&self.encryption_private_key))
.or_else(|| file_exists(&self.gateway_shared_key))
.or_else(|| file_exists(&self.ack_key))
}
pub fn gateway_key_file_exists(&self) -> bool {
matches!(self.gateway_shared_key.try_exists(), Ok(true))
}
pub fn private_identity_key(&self) -> &Path {
&self.identity_private_key
}
@@ -64,3 +86,10 @@ impl ClientKeyPathfinder {
&self.ack_key
}
}
fn file_exists(path: &Path) -> Option<PathBuf> {
if matches!(path.try_exists(), Ok(true)) {
return Some(path.to_path_buf());
}
None
}
+3
View File
@@ -55,6 +55,9 @@ pub enum ClientCoreError {
#[error("The address of the gateway is unknown - did you run init?")]
GatwayAddressUnknown,
#[error("failed to register receiver for reconstructed mixnet messages")]
FailedToRegisterReceiver,
#[error("Unexpected exit")]
UnexpectedExit,
}
+5 -12
View File
@@ -10,7 +10,7 @@ use config::NymConfig;
use crypto::asymmetric::identity;
use gateway_client::GatewayClient;
use gateway_requests::registration::handshake::SharedKeys;
use rand::{rngs::OsRng, seq::SliceRandom, thread_rng};
use rand::{seq::SliceRandom, thread_rng};
use std::{sync::Arc, time::Duration};
use tap::TapFallible;
use topology::{filter::VersionFilterable, gateway};
@@ -23,7 +23,7 @@ pub(super) async fn query_gateway_details(
let nym_api = validator_servers
.choose(&mut thread_rng())
.ok_or(ClientCoreError::ListOfNymApisIsEmpty)?;
let validator_client = validator_client::client::ApiClient::new(nym_api.clone());
let validator_client = validator_client::client::NymApiClient::new(nym_api.clone());
log::trace!("Fetching list of gateways from: {}", nym_api);
let gateways = validator_client.get_cached_gateways().await?;
@@ -51,7 +51,7 @@ pub(super) async fn query_gateway_details(
}
}
async fn register_with_gateway(
pub(super) async fn register_with_gateway(
gateway: &gateway::Node,
our_identity: Arc<identity::KeyPair>,
) -> Result<Arc<SharedKeys>, ClientCoreError> {
@@ -74,20 +74,13 @@ async fn register_with_gateway(
Ok(shared_keys)
}
pub(super) async fn register_with_gateway_and_store_keys<T>(
gateway_details: gateway::Node,
pub(super) fn store_keys<T>(
key_manager: &KeyManager,
config: &Config<T>,
) -> Result<(), ClientCoreError>
where
T: NymConfig,
{
let mut rng = OsRng;
let mut key_manager = KeyManager::new(&mut rng);
let shared_keys =
register_with_gateway(&gateway_details, key_manager.identity_keypair()).await?;
key_manager.insert_gateway_shared_key(shared_keys);
let pathfinder = ClientKeyPathfinder::new_from_config(config);
Ok(key_manager
.store_keys(&pathfinder)
+63 -13
View File
@@ -6,23 +6,26 @@
use std::fmt::Display;
use nymsphinx::addressing::{clients::Recipient, nodes::NodeIdentity};
use rand::rngs::OsRng;
use serde::Serialize;
use tap::TapFallible;
use config::NymConfig;
use crypto::asymmetric::{encryption, identity};
use url::Url;
use crate::client::key_manager::KeyManager;
use crate::{
config::{
persistence::key_pathfinder::ClientKeyPathfinder, ClientCoreConfigTrait, Config,
GatewayEndpointConfig,
},
error::ClientCoreError,
init::helpers::{query_gateway_details, register_with_gateway_and_store_keys},
};
mod helpers;
/// Struct describing the results of the client initialization procedure.
#[derive(Debug, Serialize)]
pub struct InitResults {
version: String,
@@ -60,6 +63,12 @@ impl Display for InitResults {
}
}
/// Create a new set of client keys.
pub fn new_client_keys() -> KeyManager {
let mut rng = OsRng;
KeyManager::new(&mut rng)
}
/// Convenience function for setting up the gateway for a client. Depending on the arguments given
/// it will do the sensible thing.
pub async fn setup_gateway<C, T>(
@@ -74,7 +83,7 @@ where
{
let id = config.get_id();
if register_gateway {
register_with_gateway(user_chosen_gateway_id, config).await
register_with_gateway_and_store(user_chosen_gateway_id, config).await
} else if let Some(user_chosen_gateway_id) = user_chosen_gateway_id {
config_gateway_with_existing_keys(user_chosen_gateway_id, config).await
} else {
@@ -82,27 +91,51 @@ where
}
}
/// Get the gateway details by querying the validator-api. Either pick one at random or use
/// the chosen one if it's among the available ones.
pub async fn register_with_gateway(
key_manager: &mut KeyManager,
nym_api_endpoints: Vec<Url>,
chosen_gateway_id: Option<String>,
) -> Result<GatewayEndpointConfig, ClientCoreError> {
// Our identity is derived from our key
let our_identity = key_manager.identity_keypair();
// Get the gateway details of the gateway we will use
let gateway = helpers::query_gateway_details(nym_api_endpoints, chosen_gateway_id).await?;
log::debug!("Querying gateway gives: {}", gateway);
// Establish connection, authenticate and generate keys for talking with the gateway
let shared_keys = helpers::register_with_gateway(&gateway, our_identity).await?;
key_manager.insert_gateway_shared_key(shared_keys);
Ok(gateway.into())
}
/// Get the gateway details by querying the validator-api. Either pick one at random or use
/// the chosen one if it's among the available ones.
/// Saves keys to disk, specified by the paths in `config`.
pub async fn register_with_gateway<T>(
user_chosen_gateway_id: Option<String>,
pub async fn register_with_gateway_and_store<T>(
chosen_gateway_id: Option<String>,
config: &Config<T>,
) -> Result<GatewayEndpointConfig, ClientCoreError>
where
T: NymConfig,
{
println!("Configuring gateway");
let gateway =
query_gateway_details(config.get_nym_api_endpoints(), user_chosen_gateway_id).await?;
log::debug!("Querying gateway gives: {}", gateway);
let mut key_manager = new_client_keys();
// Registering with gateway by setting up and writing shared keys to disk
log::trace!("Registering gateway");
register_with_gateway_and_store_keys(gateway.clone(), config).await?;
let gateway = register_with_gateway(
&mut key_manager,
config.get_nym_api_endpoints(),
chosen_gateway_id,
)
.await?;
helpers::store_keys(&key_manager, config)?;
println!("Saved all generated keys");
Ok(gateway.into())
Ok(gateway)
}
/// Set the gateway using the usual procedue of querying the validator-api, but don't register or
@@ -117,8 +150,11 @@ where
T: NymConfig,
{
println!("Using gateway provided by user, keeping existing keys");
let gateway =
query_gateway_details(config.get_nym_api_endpoints(), Some(user_chosen_gateway_id)).await?;
let gateway = helpers::query_gateway_details(
config.get_nym_api_endpoints(),
Some(user_chosen_gateway_id),
)
.await?;
log::debug!("Querying gateway gives: {}", gateway);
Ok(gateway.into())
}
@@ -143,6 +179,20 @@ where
})
}
/// Get the full client address from the client keys and the gateway identity
pub fn get_client_address(
key_manager: &KeyManager,
gateway_config: &GatewayEndpointConfig,
) -> Recipient {
Recipient::new(
*key_manager.identity_keypair().public_key(),
*key_manager.encryption_keypair().public_key(),
// TODO: below only works under assumption that gateway address == gateway id
// (which currently is true)
NodeIdentity::from_base58_string(&gateway_config.gateway_id).unwrap(),
)
}
/// Get the client address by loading the keys from stored files.
pub fn get_client_address_from_stored_keys<T>(
config: &Config<T>,
+1 -1
View File
@@ -23,7 +23,7 @@ credential-storage = { path = "../../common/credential-storage" }
crypto = { path = "../../common/crypto", features = ["rand", "asymmetric", "symmetric", "aes", "hashing"] }
network-defaults = { path = "../../common/network-defaults" }
pemstore = { path = "../../common/pemstore" }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nymd-client"] }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nyxd-client"] }
[features]
coconut = ["credentials/coconut"]
+11 -11
View File
@@ -6,27 +6,27 @@ use bip39::Mnemonic;
use network_defaults::{NymNetworkDetails, VOUCHER_INFO};
use std::str::FromStr;
use url::Url;
use validator_client::nymd;
use validator_client::nymd::traits::CoconutBandwidthSigningClient;
use validator_client::nymd::{Coin, Fee, NymdClient, SigningNymdClient};
use validator_client::nyxd;
use validator_client::nyxd::traits::CoconutBandwidthSigningClient;
use validator_client::nyxd::{Coin, Fee, NyxdClient, SigningNyxdClient};
pub(crate) struct Client {
nymd_client: NymdClient<SigningNymdClient>,
nyxd_client: NyxdClient<SigningNyxdClient>,
mix_denom_base: String,
}
impl Client {
pub fn new(nymd_url: &str, mnemonic: &str) -> Self {
let nymd_url = Url::from_str(nymd_url).unwrap();
pub fn new(nyxd_url: &str, mnemonic: &str) -> Self {
let nyxd_url = Url::from_str(nyxd_url).unwrap();
let mnemonic = Mnemonic::from_str(mnemonic).unwrap();
let network_details = NymNetworkDetails::new_from_env();
let config = nymd::Config::try_from_nym_network_details(&network_details)
let config = nyxd::Config::try_from_nym_network_details(&network_details)
.expect("failed to construct valid validator client config with the provided network");
let nymd_client =
NymdClient::connect_with_mnemonic(config, nymd_url.as_ref(), mnemonic, None).unwrap();
let nyxd_client =
NyxdClient::connect_with_mnemonic(config, nyxd_url.as_ref(), mnemonic, None).unwrap();
Client {
nymd_client,
nyxd_client,
mix_denom_base: network_details.chain_details.mix_denom.base,
}
}
@@ -40,7 +40,7 @@ impl Client {
) -> Result<String> {
let amount = Coin::new(amount as u128, self.mix_denom_base.clone());
Ok(self
.nymd_client
.nyxd_client
.deposit(
amount,
String::from(VOUCHER_INFO),
+5 -5
View File
@@ -13,7 +13,7 @@ use credentials::coconut::bandwidth::{BandwidthVoucher, TOTAL_ATTRIBUTES};
use credentials::coconut::utils::obtain_aggregate_signature;
use crypto::asymmetric::{encryption, identity};
use network_defaults::{NymNetworkDetails, VOUCHER_INFO};
use validator_client::nymd::tx::Hash;
use validator_client::nyxd::tx::Hash;
use validator_client::{CoconutApiClient, Config};
use crate::client::Client;
@@ -38,9 +38,9 @@ pub(crate) struct Run {
#[clap(long)]
pub(crate) client_home_directory: std::path::PathBuf,
/// The nymd URL that should be used
/// The nyxd URL that should be used
#[clap(long)]
pub(crate) nymd_url: String,
pub(crate) nyxd_url: String,
/// A mnemonic for the account that buys the credential
#[clap(long)]
@@ -51,12 +51,12 @@ pub(crate) struct Run {
pub(crate) amount: u64,
}
pub(crate) async fn deposit(nymd_url: &str, mnemonic: &str, amount: u64) -> Result<State> {
pub(crate) async fn deposit(nyxd_url: &str, mnemonic: &str, amount: u64) -> Result<State> {
let mut rng = OsRng;
let signing_keypair = KeyPair::from(identity::KeyPair::new(&mut rng));
let encryption_keypair = KeyPair::from(encryption::KeyPair::new(&mut rng));
let client = Client::new(nymd_url, mnemonic);
let client = Client::new(nyxd_url, mnemonic);
let tx_hash = client
.deposit(
amount,
+3 -3
View File
@@ -7,15 +7,15 @@ use credential_storage::error::StorageError;
use credentials::error::Error as CredentialError;
use crypto::asymmetric::encryption::KeyRecoveryError;
use crypto::asymmetric::identity::Ed25519RecoveryError;
use validator_client::nymd::error::NymdError;
use validator_client::nyxd::error::NyxdError;
use validator_client::ValidatorClientError;
pub type Result<T> = std::result::Result<T, CredentialClientError>;
#[derive(Error, Debug)]
pub enum CredentialClientError {
#[error("Nymd error: {0}")]
Nymd(#[from] NymdError),
#[error("Nyxd error: {0}")]
Nyxd(#[from] NyxdError),
#[error("Validator client error: {0}")]
ValidatorClientError(#[from] ValidatorClientError),
+1 -1
View File
@@ -39,7 +39,7 @@ cfg_if::cfg_if! {
let db_path = r.client_home_directory.join(DATA_DIR).join(DB_FILE_NAME);
let shared_storage = credential_storage::initialise_storage(db_path).await;
let state = deposit(&r.nymd_url, &r.mnemonic, r.amount).await?;
let state = deposit(&r.nyxd_url, &r.mnemonic, r.amount).await?;
get_credential(&state, shared_storage).await?;
}
Command::Completions(c) => c.generate(&mut crate::Cli::command(), bin_name),
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-client"
version = "1.1.4"
version = "1.1.5"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>", "Jędrzej Stuczyński <andrew@nymtech.net>"]
description = "Implementation of the Nym Client"
edition = "2021"
@@ -51,7 +51,7 @@ nymsphinx = { path = "../../common/nymsphinx" }
pemstore = { path = "../../common/pemstore" }
task = { path = "../../common/task" }
topology = { path = "../../common/topology" }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nymd-client"] }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nyxd-client"] }
version-checker = { path = "../../common/version-checker" }
websocket-requests = { path = "websocket-requests" }
+58 -2
View File
@@ -2,12 +2,15 @@
// SPDX-License-Identifier: Apache-2.0
use crate::client::config::template::config_template;
pub use client_core::config::Config as BaseConfig;
pub use client_core::config::MISSING_VALUE;
use client_core::config::{ClientCoreConfigTrait, Config as BaseConfig, DebugConfig};
use client_core::config::{ClientCoreConfigTrait, DebugConfig};
use config::defaults::DEFAULT_WEBSOCKET_LISTENING_PORT;
use config::NymConfig;
use config::{NymConfig, OptionalSet};
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::path::PathBuf;
use std::str::FromStr;
mod template;
@@ -92,6 +95,15 @@ impl Config {
self
}
pub fn with_disabled_socket(mut self, disabled: bool) -> Self {
if disabled {
self.socket.socket_type = SocketType::None;
} else {
self.socket.socket_type = SocketType::WebSocket;
}
self
}
pub fn with_port(mut self, port: u16) -> Self {
self.socket.listening_port = port;
self
@@ -121,6 +133,50 @@ impl Config {
pub fn get_listening_port(&self) -> u16 {
self.socket.listening_port
}
// poor man's 'builder' method
pub fn with_base<F, T>(mut self, f: F, val: T) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
{
self.base = f(self.base, val);
self
}
// helper methods to use `OptionalSet` trait. Those are defined due to very... ehm. 'specific' structure of this config
// (plz, lets refactor it)
pub fn with_optional_ext<F, T>(mut self, f: F, val: Option<T>) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
{
self.base = self.base.with_optional(f, val);
self
}
pub fn with_optional_env_ext<F, T>(mut self, f: F, val: Option<T>, env_var: &str) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
T: FromStr,
<T as FromStr>::Err: Debug,
{
self.base = self.base.with_optional_env(f, val, env_var);
self
}
pub fn with_optional_custom_env_ext<F, T, G>(
mut self,
f: F,
val: Option<T>,
env_var: &str,
parser: G,
) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
G: Fn(&str) -> T,
{
self.base = self.base.with_optional_custom_env(f, val, env_var, parser);
self
}
}
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
+3 -3
View File
@@ -23,9 +23,9 @@ id = '{{ client.id }}'
# to claim bandwidth without presenting bandwidth credentials.
disabled_credentials_mode = {{ client.disabled_credentials_mode }}
# Addresses to nymd validators via which the client can communicate with the chain.
validator_urls = [
{{#each client.validator_urls }}
# Addresses to nyxd validators via which the client can communicate with the chain.
nyxd_urls = [
{{#each client.nyxd_urls }}
'{{this}}',
{{/each}}
]
+12 -8
View File
@@ -8,12 +8,11 @@ use crate::error::ClientError;
use crate::websocket;
use client_connections::TransmissionLane;
use client_core::client::base_client::{
non_wasm_helpers, BaseClientBuilder, ClientInput, ClientOutput,
non_wasm_helpers, BaseClientBuilder, ClientInput, ClientOutput, ClientState,
};
use client_core::client::inbound_messages::InputMessage;
use client_core::client::key_manager::KeyManager;
use client_core::client::received_buffer::{ReceivedBufferMessage, ReconstructedMessagesReceiver};
use client_core::client::replies::reply_controller::requests::ReplyControllerSender;
use client_core::config::persistence::key_pathfinder::ClientKeyPathfinder;
use futures::channel::mpsc;
use gateway_client::bandwidth::BandwidthController;
@@ -52,18 +51,18 @@ impl SocketClient {
let mut client_config =
validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config");
let nymd_url = config
let nyxd_url = config
.get_base()
.get_validator_endpoints()
.pop()
.expect("No nymd validator endpoint provided");
.expect("No nyxd validator endpoint provided");
let api_url = config
.get_base()
.get_nym_api_endpoints()
.pop()
.expect("No validator api endpoint provided");
// overwrite env configuration with config URLs
client_config = client_config.with_urls(nymd_url, api_url);
client_config = client_config.with_urls(nyxd_url, api_url);
let client = validator_client::Client::new_query(client_config)
.expect("Could not construct query client");
let coconut_api_clients =
@@ -87,8 +86,8 @@ impl SocketClient {
config: &Config,
client_input: ClientInput,
client_output: ClientOutput,
client_state: ClientState,
self_address: &Recipient,
reply_controller_sender: ReplyControllerSender,
shutdown: task::TaskClient,
) {
info!("Starting websocket listener...");
@@ -99,10 +98,14 @@ impl SocketClient {
} = client_input;
let ClientOutput {
shared_lane_queue_lengths,
received_buffer_request_sender,
} = client_output;
let ClientState {
shared_lane_queue_lengths,
reply_controller_sender,
} = client_state;
let websocket_handler = websocket::HandlerBuilder::new(
input_sender,
connection_command_sender,
@@ -151,13 +154,14 @@ impl SocketClient {
let mut started_client = base_builder.start_base().await?;
let client_input = started_client.client_input.register_producer();
let client_output = started_client.client_output.register_consumer();
let client_state = started_client.client_state;
Self::start_websocket_listener(
&self.config,
client_input,
client_output,
client_state,
&self_address,
started_client.reply_controller_sender,
started_client.task_manager.subscribe(),
);
+4 -4
View File
@@ -29,10 +29,10 @@ pub(crate) struct Init {
#[clap(long)]
force_register_gateway: bool,
/// Comma separated list of rest endpoints of the nymd validators
/// Comma separated list of rest endpoints of the nyxd validators
#[cfg(feature = "coconut")]
#[clap(long, value_delimiter = ',')]
nymd_validators: Option<Vec<url::Url>>,
#[clap(long, alias = "nymd_validators", value_delimiter = ',')]
nyxd_urls: Option<Vec<url::Url>>,
/// Comma separated list of rest endpoints of the API validators
#[clap(long, alias = "api_validators", value_delimiter = ',')]
@@ -77,7 +77,7 @@ impl From<Init> for OverrideConfig {
no_cover: init_config.no_cover,
#[cfg(feature = "coconut")]
nymd_validators: init_config.nymd_validators,
nyxd_urls: init_config.nyxd_urls,
#[cfg(feature = "coconut")]
enabled_credentials_mode: init_config.enabled_credentials_mode,
}
+26 -40
View File
@@ -1,11 +1,12 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::client::config::{Config, SocketType};
use crate::client::config::{BaseConfig, Config};
use build_information::BinaryBuildInformation;
use clap::CommandFactory;
use clap::{Parser, Subcommand};
use completions::{fig_generate, ArgShell};
use config::OptionalSet;
use lazy_static::lazy_static;
use std::error::Error;
@@ -59,7 +60,7 @@ pub(crate) struct OverrideConfig {
no_cover: bool,
#[cfg(feature = "coconut")]
nymd_validators: Option<Vec<url::Url>>,
nyxd_urls: Option<Vec<url::Url>>,
#[cfg(feature = "coconut")]
enabled_credentials_mode: bool,
}
@@ -78,46 +79,31 @@ pub(crate) async fn execute(args: &Cli) -> Result<(), Box<dyn Error + Send + Syn
}
pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Config {
if let Some(nym_apis) = args.nym_apis {
config.get_base_mut().set_custom_nym_apis(nym_apis);
} else if std::env::var(network_defaults::var_names::CONFIGURED).is_ok() {
let raw_validators = std::env::var(network_defaults::var_names::API_VALIDATOR)
.expect("api validator not set");
config
.get_base_mut()
.set_custom_nym_apis(config::parse_urls(&raw_validators));
}
if args.disable_socket {
config = config.with_socket(SocketType::None);
}
if let Some(port) = args.port {
config = config.with_port(port);
}
config = config
.with_disabled_socket(args.disable_socket)
.with_base(BaseConfig::with_high_default_traffic_volume, args.fastmode)
.with_base(BaseConfig::with_disabled_cover_traffic, args.no_cover)
.with_optional(Config::with_port, args.port)
.with_optional_custom_env_ext(
BaseConfig::with_custom_nym_apis,
args.nym_apis,
network_defaults::var_names::NYM_API,
config::parse_urls,
);
#[cfg(feature = "coconut")]
{
if let Some(nymd_validators) = args.nymd_validators {
config.get_base_mut().set_custom_validators(nymd_validators);
} else if std::env::var(network_defaults::var_names::CONFIGURED).is_ok() {
let raw_validators = std::env::var(network_defaults::var_names::NYMD_VALIDATOR)
.expect("nymd validator not set");
config
.get_base_mut()
.set_custom_validators(config::parse_urls(&raw_validators));
}
if args.enabled_credentials_mode {
config.get_base_mut().with_disabled_credentials(false)
}
}
if args.fastmode {
config.get_base_mut().set_high_default_traffic_volume();
}
if args.no_cover {
config.get_base_mut().set_no_cover_traffic();
config = config
.with_optional_custom_env_ext(
BaseConfig::with_custom_nyxd,
args.nyxd_urls,
network_defaults::var_names::NYXD,
config::parse_urls,
)
.with_base(
BaseConfig::with_disabled_credentials,
!args.enabled_credentials_mode,
);
}
config
+4 -4
View File
@@ -21,10 +21,10 @@ pub(crate) struct Run {
#[clap(long)]
id: String,
/// Comma separated list of rest endpoints of the nymd validators
/// Comma separated list of rest endpoints of the nyxd validators
#[cfg(feature = "coconut")]
#[clap(long, value_delimiter = ',')]
nymd_validators: Option<Vec<url::Url>>,
#[clap(long, alias = "nymd_validators", value_delimiter = ',')]
nyxd_urls: Option<Vec<url::Url>>,
/// Comma separated list of rest endpoints of the API validators
#[clap(long, alias = "api_validators", value_delimiter = ',')]
@@ -70,7 +70,7 @@ impl From<Run> for OverrideConfig {
no_cover: run_config.no_cover,
#[cfg(feature = "coconut")]
nymd_validators: run_config.nymd_validators,
nyxd_urls: run_config.nyxd_urls,
#[cfg(feature = "coconut")]
enabled_credentials_mode: run_config.enabled_credentials_mode,
}
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "nym-socks5-client"
version = "1.1.4"
version = "1.1.5"
authors = ["Dave Hrycyszyn <futurechimp@users.noreply.github.com>"]
description = "A SOCKS5 localhost proxy that converts incoming messages to Sphinx and sends them to a Nym address"
edition = "2021"
@@ -47,7 +47,7 @@ proxy-helpers = { path = "../../common/socks5/proxy-helpers" }
socks5-requests = { path = "../../common/socks5/requests" }
task = { path = "../../common/task" }
topology = { path = "../../common/topology" }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nymd-client"] }
validator-client = { path = "../../common/client-libs/validator-client", features = ["nyxd-client"] }
version-checker = { path = "../../common/version-checker" }
[features]
+49 -2
View File
@@ -2,13 +2,16 @@
// SPDX-License-Identifier: Apache-2.0
use crate::client::config::template::config_template;
pub use client_core::config::Config as BaseConfig;
pub use client_core::config::MISSING_VALUE;
use client_core::config::{ClientCoreConfigTrait, Config as BaseConfig, DebugConfig};
use client_core::config::{ClientCoreConfigTrait, DebugConfig};
use config::defaults::DEFAULT_SOCKS5_LISTENING_PORT;
use config::NymConfig;
use config::{NymConfig, OptionalSet};
use nymsphinx::addressing::clients::Recipient;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::path::PathBuf;
use std::str::FromStr;
mod template;
@@ -127,6 +130,50 @@ impl Config {
pub fn get_per_request_surbs(&self) -> u32 {
self.socks5_debug.per_request_surbs
}
// poor man's 'builder' method
pub fn with_base<F, T>(mut self, f: F, val: T) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
{
self.base = f(self.base, val);
self
}
// helper methods to use `OptionalSet` trait. Those are defined due to very... ehm. 'specific' structure of this config
// (plz, lets refactor it)
pub fn with_optional_ext<F, T>(mut self, f: F, val: Option<T>) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
{
self.base = self.base.with_optional(f, val);
self
}
pub fn with_optional_env_ext<F, T>(mut self, f: F, val: Option<T>, env_var: &str) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
T: FromStr,
<T as FromStr>::Err: Debug,
{
self.base = self.base.with_optional_env(f, val, env_var);
self
}
pub fn with_optional_custom_env_ext<F, T, G>(
mut self,
f: F,
val: Option<T>,
env_var: &str,
parser: G,
) -> Self
where
F: Fn(BaseConfig<Self>, T) -> BaseConfig<Self>,
G: Fn(&str) -> T,
{
self.base = self.base.with_optional_custom_env(f, val, env_var, parser);
self
}
}
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
+3 -3
View File
@@ -23,9 +23,9 @@ id = '{{ client.id }}'
# to claim bandwidth without presenting bandwidth credentials.
disabled_credentials_mode = {{ client.disabled_credentials_mode }}
# Addresses to nymd validators via which the client can communicate with the chain.
validator_urls = [
{{#each client.validator_urls }}
# Addresses to nyxd validators via which the client can communicate with the chain.
nyxd_urls = [
{{#each client.nyxd_urls }}
'{{this}}',
{{/each}}
]
+12 -5
View File
@@ -9,7 +9,7 @@ use crate::socks::{
server::SphinxSocksServer,
};
use client_core::client::base_client::{
non_wasm_helpers, BaseClientBuilder, ClientInput, ClientOutput,
non_wasm_helpers, BaseClientBuilder, ClientInput, ClientOutput, ClientState,
};
use client_core::client::key_manager::KeyManager;
use client_core::config::persistence::key_pathfinder::ClientKeyPathfinder;
@@ -60,18 +60,18 @@ impl NymClient {
let mut client_config =
validator_client::Config::try_from_nym_network_details(&details)
.expect("failed to construct validator client config");
let nymd_url = config
let nyxd_url = config
.get_base()
.get_validator_endpoints()
.pop()
.expect("No nymd validator endpoint provided");
.expect("No nyxd validator endpoint provided");
let api_url = config
.get_base()
.get_nym_api_endpoints()
.pop()
.expect("No validator api endpoint provided");
// overwrite env configuration with config URLs
client_config = client_config.with_urls(nymd_url, api_url);
client_config = client_config.with_urls(nyxd_url, api_url);
let client = validator_client::Client::new_query(client_config)
.expect("Could not construct query client");
let coconut_api_clients =
@@ -95,6 +95,7 @@ impl NymClient {
config: &Config,
client_input: ClientInput,
client_output: ClientOutput,
client_status: ClientState,
self_address: Recipient,
shutdown: TaskClient,
) {
@@ -108,10 +109,14 @@ impl NymClient {
} = client_input;
let ClientOutput {
shared_lane_queue_lengths,
received_buffer_request_sender,
} = client_output;
let ClientState {
shared_lane_queue_lengths,
reply_controller_sender: _,
} = client_status;
let authenticator = Authenticator::new(auth_methods, allowed_users);
let mut sphinx_socks = SphinxSocksServer::new(
config.get_listening_port(),
@@ -218,11 +223,13 @@ impl NymClient {
let mut started_client = base_builder.start_base().await?;
let client_input = started_client.client_input.register_producer();
let client_output = started_client.client_output.register_consumer();
let client_state = started_client.client_state;
Self::start_socks5_listener(
&self.config,
client_input,
client_output,
client_state,
self_address,
started_client.task_manager.subscribe(),
);
+4 -4
View File
@@ -42,10 +42,10 @@ pub(crate) struct Init {
#[clap(long)]
force_register_gateway: bool,
/// Comma separated list of rest endpoints of the nymd validators
/// Comma separated list of rest endpoints of the nyxd validators
#[cfg(feature = "coconut")]
#[clap(long, value_delimiter = ',')]
nymd_validators: Option<Vec<url::Url>>,
#[clap(long, alias = "nymd_validators", value_delimiter = ',')]
nyxd_urls: Option<Vec<url::Url>>,
/// Comma separated list of rest endpoints of the API validators
#[clap(long, alias = "api_validators", value_delimiter = ',')]
@@ -86,7 +86,7 @@ impl From<Init> for OverrideConfig {
no_cover: init_config.no_cover,
#[cfg(feature = "coconut")]
nymd_validators: init_config.nymd_validators,
nyxd_urls: init_config.nyxd_urls,
#[cfg(feature = "coconut")]
enabled_credentials_mode: init_config.enabled_credentials_mode,
}
+25 -38
View File
@@ -1,12 +1,12 @@
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::client::config::Config;
use crate::client::config::{BaseConfig, Config};
use build_information::BinaryBuildInformation;
use clap::CommandFactory;
use clap::{Parser, Subcommand};
use completions::{fig_generate, ArgShell};
use config::parse_urls;
use config::OptionalSet;
use lazy_static::lazy_static;
use std::error::Error;
@@ -62,7 +62,7 @@ pub(crate) struct OverrideConfig {
no_cover: bool,
#[cfg(feature = "coconut")]
nymd_validators: Option<Vec<url::Url>>,
nyxd_urls: Option<Vec<url::Url>>,
#[cfg(feature = "coconut")]
enabled_credentials_mode: bool,
}
@@ -81,44 +81,31 @@ pub(crate) async fn execute(args: &Cli) -> Result<(), Box<dyn Error + Send + Syn
}
pub(crate) fn override_config(mut config: Config, args: OverrideConfig) -> Config {
if let Some(nym_apis) = args.nym_apis {
config.get_base_mut().set_custom_nym_apis(nym_apis);
} else if let Ok(raw_validators) = std::env::var(network_defaults::var_names::API_VALIDATOR) {
config
.get_base_mut()
.set_custom_nym_apis(parse_urls(&raw_validators));
}
if args.use_anonymous_replies {
config = config.with_anonymous_replies(true)
}
if let Some(port) = args.port {
config = config.with_port(port);
}
config = config
.with_base(BaseConfig::with_high_default_traffic_volume, args.fastmode)
.with_base(BaseConfig::with_disabled_cover_traffic, args.no_cover)
.with_anonymous_replies(args.use_anonymous_replies)
.with_optional(Config::with_port, args.port)
.with_optional_custom_env_ext(
BaseConfig::with_custom_nym_apis,
args.nym_apis,
network_defaults::var_names::NYM_API,
config::parse_urls,
);
#[cfg(feature = "coconut")]
{
if let Some(nymd_validators) = args.nymd_validators {
config.get_base_mut().set_custom_validators(nymd_validators);
} else if let Ok(raw_validators) =
std::env::var(network_defaults::var_names::NYMD_VALIDATOR)
{
config
.get_base_mut()
.set_custom_validators(parse_urls(&raw_validators));
}
if args.enabled_credentials_mode {
config.get_base_mut().with_disabled_credentials(false)
}
}
if args.fastmode {
config.get_base_mut().set_high_default_traffic_volume();
}
if args.no_cover {
config.get_base_mut().set_no_cover_traffic();
config = config
.with_optional_custom_env_ext(
BaseConfig::with_custom_nyxd,
args.nyxd_urls,
network_defaults::var_names::NYXD,
config::parse_urls,
)
.with_base(
BaseConfig::with_disabled_credentials,
!args.enabled_credentials_mode,
);
}
config
+4 -4
View File
@@ -42,10 +42,10 @@ pub(crate) struct Run {
#[clap(long)]
gateway: Option<identity::PublicKey>,
/// Comma separated list of rest endpoints of the nymd validators
/// Comma separated list of rest endpoints of the nyxd validators
#[cfg(feature = "coconut")]
#[clap(long, value_delimiter = ',')]
nymd_validators: Option<Vec<url::Url>>,
#[clap(long, alias = "nymd_validators", value_delimiter = ',')]
nyxd_urls: Option<Vec<url::Url>>,
/// Comma separated list of rest endpoints of the Nym APIs
#[clap(long, value_delimiter = ',')]
@@ -81,7 +81,7 @@ impl From<Run> for OverrideConfig {
no_cover: run_config.no_cover,
#[cfg(feature = "coconut")]
nymd_validators: run_config.nymd_validators,
nyxd_urls: run_config.nyxd_urls,
#[cfg(feature = "coconut")]
enabled_credentials_mode: run_config.enabled_credentials_mode,
}
+1 -6
View File
@@ -1,5 +1,3 @@
use std::time::Duration;
use futures::channel::mpsc;
use futures::StreamExt;
use log::*;
@@ -116,10 +114,7 @@ impl MixnetResponseListener {
}
}
}
#[cfg(not(target_arch = "wasm32"))]
tokio::time::timeout(Duration::from_secs(5), self.shutdown.recv())
.await
.expect("Task stopped without shutdown called");
self.shutdown.recv_timeout().await;
log::debug!("MixnetResponseListener: Exiting");
}
}
+14 -14
View File
@@ -85,7 +85,7 @@ export default class ValidatorClient implements INymClient {
static async connect(
mnemonic: string,
nymdUrl: string,
nyxdUrl: string,
nymApiUrl: string,
prefix: string,
mixnetContract: string,
@@ -94,19 +94,19 @@ export default class ValidatorClient implements INymClient {
): Promise<ValidatorClient> {
const wallet = await ValidatorClient.buildWallet(mnemonic, prefix);
const signingClient = await SigningClient.connectWithNymSigner(wallet, nymdUrl, nymApiUrl, prefix, denom);
const signingClient = await SigningClient.connectWithNymSigner(wallet, nyxdUrl, nymApiUrl, prefix, denom);
return new ValidatorClient(signingClient, prefix, mixnetContract, vestingContract, denom);
}
static async connectForQuery(
nymdUrl: string,
nyxdUrl: string,
nymApiUrl: string,
prefix: string,
mixnetContract: string,
vestingContract: string,
denom: string,
): Promise<ValidatorClient> {
const queryClient = await QueryClient.connectWithNym(nymdUrl, nymApiUrl);
const queryClient = await QueryClient.connectWithNym(nyxdUrl, nymApiUrl);
return new ValidatorClient(queryClient, prefix, mixnetContract, vestingContract, denom);
}
@@ -191,11 +191,11 @@ export default class ValidatorClient implements INymClient {
return this.client.getIntervalRewardPercent(this.mixnetContract);
}
public async getAllNymdMixnodes(): Promise<MixNodeBond[]> {
public async getAllNyxdMixnodes(): Promise<MixNodeBond[]> {
let mixNodes: MixNodeBond[] = [];
const limit = 50;
let startAfter;
for (;;) {
for (; ;) {
// eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedMixnodeResponse = await this.client.getMixNodesPaged(this.mixnetContract, limit);
mixNodes = mixNodes.concat(pagedResponse.nodes);
@@ -209,11 +209,11 @@ export default class ValidatorClient implements INymClient {
return mixNodes;
}
public async getAllNymdGateways(): Promise<GatewayBond[]> {
public async getAllNyxdGateways(): Promise<GatewayBond[]> {
let gateways: GatewayBond[] = [];
const limit = 50;
let startAfter;
for (;;) {
for (; ;) {
// eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedGatewayResponse = await this.client.getGatewaysPaged(this.mixnetContract, limit);
gateways = gateways.concat(pagedResponse.nodes);
@@ -232,11 +232,11 @@ export default class ValidatorClient implements INymClient {
*
* @param mixIdentity identity of the node to which the delegation was sent
*/
public async getAllNymdSingleMixnodeDelegations(mixIdentity: string): Promise<Delegation[]> {
public async getAllNyxdSingleMixnodeDelegations(mixIdentity: string): Promise<Delegation[]> {
let delegations: Delegation[] = [];
const limit = 250;
let startAfter;
for (;;) {
for (; ;) {
// eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedMixDelegationsResponse = await this.client.getMixNodeDelegationsPaged(
this.mixnetContract,
@@ -255,11 +255,11 @@ export default class ValidatorClient implements INymClient {
return delegations;
}
public async getAllNymdDelegatorDelegations(delegator: string): Promise<Delegation[]> {
public async getAllNyxdDelegatorDelegations(delegator: string): Promise<Delegation[]> {
let delegations: Delegation[] = [];
const limit = 250;
let startAfter;
for (;;) {
for (; ;) {
// eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedDelegatorDelegationsResponse = await this.client.getDelegatorDelegationsPaged(
this.mixnetContract,
@@ -278,11 +278,11 @@ export default class ValidatorClient implements INymClient {
return delegations;
}
public async getAllNymdNetworkDelegations(): Promise<Delegation[]> {
public async getAllNyxdNetworkDelegations(): Promise<Delegation[]> {
let delegations: Delegation[] = [];
const limit = 250;
let startAfter;
for (;;) {
for (; ;) {
// eslint-disable-next-line no-await-in-loop
const pagedResponse: PagedAllDelegationsResponse = await this.client.getAllNetworkDelegationsPaged(
this.mixnetContract,
@@ -5,7 +5,7 @@
import { JsonObject } from '@cosmjs/cosmwasm-stargate';
// eslint-disable-next-line import/no-cycle
import { INymdQuery } from './query-client';
import { INyxdQuery } from './query-client';
import {
ContractStateParams,
Delegation,
@@ -25,7 +25,7 @@ interface SmartContractQuery {
queryContractSmart(address: string, queryMsg: Record<string, unknown>): Promise<JsonObject>;
}
export default class NymdQuerier implements INymdQuery {
export default class NyxdQuerier implements INyxdQuery {
client: SmartContractQuery;
constructor(client: SmartContractQuery) {
+23 -23
View File
@@ -12,7 +12,7 @@ import {
} from '@cosmjs/stargate';
import { Code, CodeDetails, Contract, ContractCodeHistoryEntry } from '@cosmjs/cosmwasm-stargate/build/cosmwasmclient';
// eslint-disable-next-line import/no-cycle
import NymdQuerier from './nymd-querier';
import NyxdQuerier from './nyxd-querier';
import {
ContractStateParams,
Delegation,
@@ -52,7 +52,7 @@ export interface ICosmWasmQuery {
queryContractSmart(address: string, queryMsg: Record<string, unknown>): Promise<JsonObject>;
}
export interface INymdQuery {
export interface INyxdQuery {
// nym-specific implemented inside NymQuerier
getContractVersion(mixnetContractAddress: string): Promise<MixnetContractVersion>;
@@ -93,46 +93,46 @@ export interface INymdQuery {
): Promise<RewardingStatus>;
}
export interface IQueryClient extends ICosmWasmQuery, INymdQuery, INymApiQuery { }
export interface IQueryClient extends ICosmWasmQuery, INyxdQuery, INymApiQuery { }
export default class QueryClient extends CosmWasmClient implements IQueryClient {
private nymdQuerier: NymdQuerier;
private nyxdQuerier: NyxdQuerier;
private nymApiQuerier: NymApiQuerier;
private constructor(tmClient: Tendermint34Client, nymApiUrl: string) {
super(tmClient);
this.nymdQuerier = new NymdQuerier(this);
this.nyxdQuerier = new NyxdQuerier(this);
this.nymApiQuerier = new NymApiQuerier(nymApiUrl);
}
public static async connectWithNym(nymdUrl: string, nymApiUrl: string): Promise<QueryClient> {
const tmClient = await Tendermint34Client.connect(nymdUrl);
public static async connectWithNym(nyxdUrl: string, nymApiUrl: string): Promise<QueryClient> {
const tmClient = await Tendermint34Client.connect(nyxdUrl);
return new QueryClient(tmClient, nymApiUrl);
}
getContractVersion(mixnetContractAddress: string): Promise<MixnetContractVersion> {
return this.nymdQuerier.getContractVersion(mixnetContractAddress);
return this.nyxdQuerier.getContractVersion(mixnetContractAddress);
}
getMixNodesPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedMixnodeResponse> {
return this.nymdQuerier.getMixNodesPaged(mixnetContractAddress, limit, startAfter);
return this.nyxdQuerier.getMixNodesPaged(mixnetContractAddress, limit, startAfter);
}
getGatewaysPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedGatewayResponse> {
return this.nymdQuerier.getGatewaysPaged(mixnetContractAddress, limit, startAfter);
return this.nyxdQuerier.getGatewaysPaged(mixnetContractAddress, limit, startAfter);
}
ownsMixNode(mixnetContractAddress: string, address: string): Promise<MixOwnershipResponse> {
return this.nymdQuerier.ownsMixNode(mixnetContractAddress, address);
return this.nyxdQuerier.ownsMixNode(mixnetContractAddress, address);
}
ownsGateway(mixnetContractAddress: string, address: string): Promise<GatewayOwnershipResponse> {
return this.nymdQuerier.ownsGateway(mixnetContractAddress, address);
return this.nyxdQuerier.ownsGateway(mixnetContractAddress, address);
}
getStateParams(mixnetContractAddress: string): Promise<ContractStateParams> {
return this.nymdQuerier.getStateParams(mixnetContractAddress);
return this.nyxdQuerier.getStateParams(mixnetContractAddress);
}
getAllNetworkDelegationsPaged(
@@ -140,7 +140,7 @@ export default class QueryClient extends CosmWasmClient implements IQueryClient
limit?: number,
startAfter?: [string, string],
): Promise<PagedAllDelegationsResponse> {
return this.nymdQuerier.getAllNetworkDelegationsPaged(mixnetContractAddress, limit, startAfter);
return this.nyxdQuerier.getAllNetworkDelegationsPaged(mixnetContractAddress, limit, startAfter);
}
getMixNodeDelegationsPaged(
@@ -149,7 +149,7 @@ export default class QueryClient extends CosmWasmClient implements IQueryClient
limit?: number,
startAfter?: string,
): Promise<PagedMixDelegationsResponse> {
return this.nymdQuerier.getMixNodeDelegationsPaged(mixnetContractAddress, mixIdentity, limit, startAfter);
return this.nyxdQuerier.getMixNodeDelegationsPaged(mixnetContractAddress, mixIdentity, limit, startAfter);
}
getDelegatorDelegationsPaged(
@@ -158,31 +158,31 @@ export default class QueryClient extends CosmWasmClient implements IQueryClient
limit?: number,
startAfter?: string,
): Promise<PagedDelegatorDelegationsResponse> {
return this.nymdQuerier.getDelegatorDelegationsPaged(mixnetContractAddress, delegator, limit, startAfter);
return this.nyxdQuerier.getDelegatorDelegationsPaged(mixnetContractAddress, delegator, limit, startAfter);
}
getDelegationDetails(mixnetContractAddress: string, mixIdentity: string, delegator: string): Promise<Delegation> {
return this.nymdQuerier.getDelegationDetails(mixnetContractAddress, mixIdentity, delegator);
return this.nyxdQuerier.getDelegationDetails(mixnetContractAddress, mixIdentity, delegator);
}
getLayerDistribution(mixnetContractAddress: string): Promise<LayerDistribution> {
return this.nymdQuerier.getLayerDistribution(mixnetContractAddress);
return this.nyxdQuerier.getLayerDistribution(mixnetContractAddress);
}
getRewardPool(mixnetContractAddress: string): Promise<string> {
return this.nymdQuerier.getRewardPool(mixnetContractAddress);
return this.nyxdQuerier.getRewardPool(mixnetContractAddress);
}
getCirculatingSupply(mixnetContractAddress: string): Promise<string> {
return this.nymdQuerier.getCirculatingSupply(mixnetContractAddress);
return this.nyxdQuerier.getCirculatingSupply(mixnetContractAddress);
}
getIntervalRewardPercent(mixnetContractAddress: string): Promise<number> {
return this.nymdQuerier.getIntervalRewardPercent(mixnetContractAddress);
return this.nyxdQuerier.getIntervalRewardPercent(mixnetContractAddress);
}
getSybilResistancePercent(mixnetContractAddress: string): Promise<number> {
return this.nymdQuerier.getSybilResistancePercent(mixnetContractAddress);
return this.nyxdQuerier.getSybilResistancePercent(mixnetContractAddress);
}
getRewardingStatus(
@@ -190,7 +190,7 @@ export default class QueryClient extends CosmWasmClient implements IQueryClient
mixIdentity: string,
rewardingIntervalNonce: number,
): Promise<RewardingStatus> {
return this.nymdQuerier.getRewardingStatus(mixnetContractAddress, mixIdentity, rewardingIntervalNonce);
return this.nyxdQuerier.getRewardingStatus(mixnetContractAddress, mixIdentity, rewardingIntervalNonce);
}
getCachedGateways(): Promise<GatewayBond[]> {
+21 -21
View File
@@ -14,7 +14,7 @@ import { ChangeAdminResult } from '@cosmjs/cosmwasm-stargate/build/signingcosmwa
import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
import { nymGasPrice } from './stargate-helper';
import { IQueryClient } from './query-client';
import NymdQuerier from './nymd-querier';
import NyxdQuerier from './nyxd-querier';
import {
ContractStateParams,
Delegation,
@@ -197,7 +197,7 @@ export interface ISigningClient extends IQueryClient, ICosmWasmSigning, INymSign
}
export default class SigningClient extends SigningCosmWasmClient implements ISigningClient {
private nymdQuerier: NymdQuerier;
private nyxdQuerier: NyxdQuerier;
private nymApiQuerier: NymApiQuerier;
@@ -212,13 +212,13 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
) {
super(tmClient, wallet, signerOptions);
this.clientAddress = clientAddress;
this.nymdQuerier = new NymdQuerier(this);
this.nyxdQuerier = new NyxdQuerier(this);
this.nymApiQuerier = new NymApiQuerier(nymApiUrl);
}
public static async connectWithNymSigner(
wallet: DirectSecp256k1HdWallet,
nymdUrl: string,
nyxdUrl: string,
nymApiUrl: string,
prefix: string,
denom: string,
@@ -228,34 +228,34 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
prefix,
gasPrice: nymGasPrice(denom),
};
const tmClient = await Tendermint34Client.connect(nymdUrl);
const tmClient = await Tendermint34Client.connect(nyxdUrl);
return new SigningClient(address, nymApiUrl, tmClient, wallet, signerOptions);
}
// query related:
getContractVersion(mixnetContractAddress: string): Promise<MixnetContractVersion> {
return this.nymdQuerier.getContractVersion(mixnetContractAddress);
return this.nyxdQuerier.getContractVersion(mixnetContractAddress);
}
getMixNodesPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedMixnodeResponse> {
return this.nymdQuerier.getMixNodesPaged(mixnetContractAddress, limit, startAfter);
return this.nyxdQuerier.getMixNodesPaged(mixnetContractAddress, limit, startAfter);
}
getGatewaysPaged(mixnetContractAddress: string, limit?: number, startAfter?: string): Promise<PagedGatewayResponse> {
return this.nymdQuerier.getGatewaysPaged(mixnetContractAddress, limit, startAfter);
return this.nyxdQuerier.getGatewaysPaged(mixnetContractAddress, limit, startAfter);
}
ownsMixNode(mixnetContractAddress: string, address: string): Promise<MixOwnershipResponse> {
return this.nymdQuerier.ownsMixNode(mixnetContractAddress, address);
return this.nyxdQuerier.ownsMixNode(mixnetContractAddress, address);
}
ownsGateway(mixnetContractAddress: string, address: string): Promise<GatewayOwnershipResponse> {
return this.nymdQuerier.ownsGateway(mixnetContractAddress, address);
return this.nyxdQuerier.ownsGateway(mixnetContractAddress, address);
}
getStateParams(mixnetContractAddress: string): Promise<ContractStateParams> {
return this.nymdQuerier.getStateParams(mixnetContractAddress);
return this.nyxdQuerier.getStateParams(mixnetContractAddress);
}
getAllNetworkDelegationsPaged(
@@ -263,7 +263,7 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
limit?: number,
startAfter?: [string, string],
): Promise<PagedAllDelegationsResponse> {
return this.nymdQuerier.getAllNetworkDelegationsPaged(mixnetContractAddress, limit, startAfter);
return this.nyxdQuerier.getAllNetworkDelegationsPaged(mixnetContractAddress, limit, startAfter);
}
getMixNodeDelegationsPaged(
@@ -272,7 +272,7 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
limit?: number,
startAfter?: string,
): Promise<PagedMixDelegationsResponse> {
return this.nymdQuerier.getMixNodeDelegationsPaged(mixnetContractAddress, mixIdentity, limit, startAfter);
return this.nyxdQuerier.getMixNodeDelegationsPaged(mixnetContractAddress, mixIdentity, limit, startAfter);
}
getDelegatorDelegationsPaged(
@@ -281,31 +281,31 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
limit?: number,
startAfter?: string,
): Promise<PagedDelegatorDelegationsResponse> {
return this.nymdQuerier.getDelegatorDelegationsPaged(mixnetContractAddress, delegator, limit, startAfter);
return this.nyxdQuerier.getDelegatorDelegationsPaged(mixnetContractAddress, delegator, limit, startAfter);
}
getDelegationDetails(mixnetContractAddress: string, mixIdentity: string, delegator: string): Promise<Delegation> {
return this.nymdQuerier.getDelegationDetails(mixnetContractAddress, mixIdentity, delegator);
return this.nyxdQuerier.getDelegationDetails(mixnetContractAddress, mixIdentity, delegator);
}
getLayerDistribution(mixnetContractAddress: string): Promise<LayerDistribution> {
return this.nymdQuerier.getLayerDistribution(mixnetContractAddress);
return this.nyxdQuerier.getLayerDistribution(mixnetContractAddress);
}
getRewardPool(mixnetContractAddress: string): Promise<string> {
return this.nymdQuerier.getRewardPool(mixnetContractAddress);
return this.nyxdQuerier.getRewardPool(mixnetContractAddress);
}
getCirculatingSupply(mixnetContractAddress: string): Promise<string> {
return this.nymdQuerier.getCirculatingSupply(mixnetContractAddress);
return this.nyxdQuerier.getCirculatingSupply(mixnetContractAddress);
}
getIntervalRewardPercent(mixnetContractAddress: string): Promise<number> {
return this.nymdQuerier.getIntervalRewardPercent(mixnetContractAddress);
return this.nyxdQuerier.getIntervalRewardPercent(mixnetContractAddress);
}
getSybilResistancePercent(mixnetContractAddress: string): Promise<number> {
return this.nymdQuerier.getSybilResistancePercent(mixnetContractAddress);
return this.nyxdQuerier.getSybilResistancePercent(mixnetContractAddress);
}
getRewardingStatus(
@@ -313,7 +313,7 @@ export default class SigningClient extends SigningCosmWasmClient implements ISig
mixIdentity: string,
rewardingIntervalNonce: number,
): Promise<RewardingStatus> {
return this.nymdQuerier.getRewardingStatus(mixnetContractAddress, mixIdentity, rewardingIntervalNonce);
return this.nyxdQuerier.getRewardingStatus(mixnetContractAddress, mixIdentity, rewardingIntervalNonce);
}
getCachedGateways(): Promise<GatewayBond[]> {
@@ -1,24 +0,0 @@
#!/usr/bin/env node
const { spawn } = require("child_process");
const fs = require("fs");
let folderName = '.';
if (process.argv.length >= 3) {
folderName = process.argv[2];
if (!fs.existsSync(folderName)) {
fs.mkdirSync(folderName);
}
}
const clone = spawn("git", ["clone", "https://github.com/rustwasm/create-wasm-app.git", folderName]);
clone.on("close", code => {
if (code !== 0) {
console.error("cloning the template failed!")
process.exit(code);
} else {
console.log("🦀 Rust + 🕸 Wasm = ❤");
}
});
@@ -1,2 +0,0 @@
node_modules
dist
@@ -1,5 +0,0 @@
language: node_js
node_js: "10"
script:
- ./node_modules/.bin/webpack
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
-28
View File
@@ -1,28 +0,0 @@
# Nym Sphinx Wasm Demo
This example application demonstrates how to use WebAssembly to create Sphinx packets, in the browser, and forward them to a Nym gateway.
## 🚴 Usage
Build the WASM package for bundling:
```
wasm-pack build --scope nymproject --target no-modules
```
in the `clients/webassembly` directory (one up).
Start the webpack dev server:
```
npm install # set up dependencies
npm run start # starts a web server at http://localhost:8001
```
Check your dev console for output.
### Rebuild after Rust source changes
Install `wasm-pack`. Instruction are at the [Rust WASM tutorial](https://rustwasm.github.io/docs/book/game-of-life/hello-world.html).
`wasm-pack build --scope nymproject --target no-modules` in the `clients/webassembly` directory (one up) will rebuild the wasm package if you make changes to the Rust source. That will be automatically picked up (and reloaded, if need be) by the npm dev server.
-5
View File
@@ -1,5 +0,0 @@
// A dependency graph that contains any wasm must all be imported
// asynchronously. This `bootstrap.js` file does the single async import, so
// that no one else needs to worry about it again.
import('./index.js')
.catch(e => console.error('Error importing `index.js`:', e));
-36
View File
@@ -1,36 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nym WebAssembly Demo</title>
</head>
<body>
<p>
<label>Sender: </label><input disabled="true" size="85" type="text" id="sender" value="">
</p>
<p>
<label>Recipient: </label><input size="85" type="text" id="recipient" value="">
</p>
<p>
<label>Message: </label><input type="text" id="message" value="Hello mixnet!">
</p>
<p>
<button id="send-button">Send</button>
</p>
<p>Send messages from your browser, through the mixnet, and to the recipient using the "send" button.</p>
<p><span style='color: blue;'>Sent</span> messages show in blue, <span style='color: green;'>received</span>
messages show in green.</p>
<hr>
<p>
<span id="output"></div>
</p>
<script src="./bootstrap.js"></script>
</body>
</html>
-128
View File
@@ -1,128 +0,0 @@
// Copyright 2020-2022 Nym Technologies SA
//
// 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.
class WebWorkerClient {
worker = null;
constructor() {
this.worker = new Worker('./worker.js');
this.worker.onmessage = (ev) => {
if (ev.data && ev.data.kind) {
switch (ev.data.kind) {
case 'Ready':
const { selfAddress } = ev.data.args;
displaySenderAddress(selfAddress);
break;
case 'ReceiveMessage':
const { message } = ev.data.args;
displayReceived(message);
break;
}
}
};
}
sendMessage = (message, recipient) => {
if (!this.worker) {
console.error('Could not send message because worker does not exist');
return;
}
this.worker.postMessage({
kind: 'SendMessage',
args: {
message, recipient,
},
});
};
}
let client = null;
async function main() {
client = new WebWorkerClient();
const sendButton = document.querySelector('#send-button');
sendButton.onclick = function() {
sendMessageTo();
};
}
/**
* Create a Sphinx packet and send it to the mixnet through the gateway node.
*
* Message and recipient are taken from the values in the user interface.
*
*/
async function sendMessageTo() {
const message = document.getElementById('message').value;
const recipient = document.getElementById('recipient').value;
await client.sendMessage(message, recipient);
displaySend(message);
}
/**
* Display messages that have been sent up the websocket. Colours them blue.
*
* @param {string} message
*/
function displaySend(message) {
let timestamp = new Date().toISOString().substr(11, 12);
let sendDiv = document.createElement('div');
let paragraph = document.createElement('p');
paragraph.setAttribute('style', 'color: blue');
let paragraphContent = document.createTextNode(timestamp + ' sent >>> ' + message);
paragraph.appendChild(paragraphContent);
sendDiv.appendChild(paragraph);
document.getElementById('output').appendChild(sendDiv);
}
/**
* Display received text messages in the browser. Colour them green.
*
* @param {Uint8Array} raw
*/
function displayReceived(raw, sender_tag) {
const content = new TextDecoder().decode(raw);
if (sender_tag !== undefined) {
console.log("this message also contained some surbs from", sender_tag)
}
let timestamp = new Date().toISOString().substr(11, 12);
let receivedDiv = document.createElement('div');
let paragraph = document.createElement('p');
paragraph.setAttribute('style', 'color: green');
let paragraphContent = document.createTextNode(timestamp + ' received >>> ' + content);
// let paragraphContent = document.createTextNode(timestamp + " received >>> " + content + ((replySurb != null) ? "Reply SURB was attached here (but we can't do anything with it yet" : " (NO REPLY-SURB AVAILABLE)"))
paragraph.appendChild(paragraphContent);
receivedDiv.appendChild(paragraph);
document.getElementById('output').appendChild(receivedDiv);
}
/**
* Display the nymClient's sender address in the user interface
*
* @param {String} address
*/
function displaySenderAddress(address) {
document.getElementById('sender').value = address;
}
// Let's get started!
main();
File diff suppressed because it is too large Load Diff
@@ -1,39 +0,0 @@
{
"name": "create-wasm-app",
"version": "0.1.0",
"description": "create an app to consume rust-generated wasm packages",
"main": "index.js",
"bin": {
"create-wasm-app": ".bin/create-wasm-app.js"
},
"scripts": {
"build": "webpack --config webpack.config.js",
"start": "webpack-dev-server --port 8001"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rustwasm/create-wasm-app.git"
},
"keywords": [
"webassembly",
"wasm",
"rust",
"webpack"
],
"author": "Dave Hrycyszyn <futurechimp@users.noreply.github.com>",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/nymtech/nym/issues"
},
"homepage": "https://nymtech.net/docs",
"devDependencies": {
"copy-webpack-plugin": "^10.2.4",
"hello-wasm-pack": "^0.1.0",
"webpack": "^5.70.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
},
"dependencies": {
"@nymproject/nym-client-wasm": "file:../pkg"
}
}
@@ -1,33 +0,0 @@
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');
module.exports = {
performance: {
hints: false,
maxEntrypointSize: 512000,
maxAssetSize: 512000
},
entry: {
bootstrap: './bootstrap.js',
worker: './worker.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
},
// mode: 'development',
mode: 'production',
plugins: [
new CopyWebpackPlugin({
patterns: [
'index.html',
{
from: 'node_modules/@nymproject/nym-client-wasm/*.(js|wasm)',
to: '[name][ext]',
},
],
}),
],
experiments: { syncWebAssembly: true },
};
-101
View File
@@ -1,101 +0,0 @@
// Copyright 2020-2022 Nym Technologies SA
//
// 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.
importScripts('nym_client_wasm.js');
console.log('Initializing worker');
// wasm_bindgen creates a global variable (with the exports attached) that is in scope after `importScripts`
const { default_debug, NymClientBuilder, set_panic_hook, Config, GatewayEndpointConfig } = wasm_bindgen;
let client = null;
async function main() {
// load WASM package
await wasm_bindgen('nym_client_wasm_bg.wasm');
console.log('Loaded WASM');
// sets up better stack traces in case of in-rust panics
set_panic_hook();
// validator server we will use to get topology from
const validator = 'https://qwerty-validator-api.qa.nymte.ch/api';
const gatewayId = 'EVupP2tRUeZo5Y6RpBHAbm8kSntpgNyZNL6yCr7BDEoG';
const gatewayOwner = 'n1rmlew3euapuq7rs4s4j9apv00whrsazr764kl7';
const gatewayListener = 'ws://176.58.120.72:9000';
const gatewayEndpoint = new GatewayEndpointConfig(gatewayId, gatewayOwner, gatewayListener)
// only really useful if you want to adjust some settings like traffic rate
// (if not needed you can just pass a null)
const debug = default_debug();
debug.disable_main_poisson_packet_distribution = true;
debug.disable_loop_cover_traffic_stream = true;
debug.use_extended_packet_size = true;
// debug.average_packet_delay_ms = BigInt(10);
// debug.average_ack_delay_ms = BigInt(10);
// debug.ack_wait_addition_ms = BigInt(3000);
// debug.ack_wait_multiplier = 10;
debug.topology_refresh_rate_ms = BigInt(60000)
const config = new Config('my-awesome-wasm-client', validator, gatewayEndpoint, debug);
const onMessageHandler = (message) => {
self.postMessage({
kind: 'ReceiveMessage',
args: {
message,
},
});
};
console.log('Instantiating WASM client...');
let clientBuilder = new NymClientBuilder(config, onMessageHandler)
console.log('Web worker creating WASM client...');
let local_client = await clientBuilder.start_client();
console.log('WASM client running!');
const selfAddress = local_client.self_address();
// set the global (I guess we don't have to anymore?)
client = local_client;
console.log(`Client address is ${selfAddress}`);
self.postMessage({
kind: 'Ready',
args: {
selfAddress,
},
});
// Set callback to handle messages passed to the worker.
self.onmessage = async event => {
if (event.data && event.data.kind) {
switch (event.data.kind) {
case 'SendMessage': {
const { message, recipient } = event.data.args;
let uint8Array = new TextEncoder().encode(message);
await client.send_regular_message(uint8Array, recipient);
}
}
}
};
}
// Let's get started!
main();
+10 -2
View File
@@ -5,7 +5,9 @@ use self::config::Config;
use crate::client::helpers::InputSender;
use crate::client::response_pusher::ResponsePusher;
use client_connections::TransmissionLane;
use client_core::client::base_client::{BaseClientBuilder, ClientInput, ClientOutput};
use client_core::client::base_client::{
BaseClientBuilder, ClientInput, ClientOutput, CredentialsToggle,
};
use client_core::client::replies::reply_storage::browser_backend;
use client_core::client::{inbound_messages::InputMessage, key_manager::KeyManager};
use gateway_client::bandwidth::BandwidthController;
@@ -92,13 +94,19 @@ impl NymClientBuilder {
future_to_promise(async move {
console_log!("Starting the wasm client");
let disabled_credentials = if self.disabled_credentials {
CredentialsToggle::Disabled
} else {
CredentialsToggle::Enabled
};
let base_builder = BaseClientBuilder::new(
&self.config.gateway_endpoint,
&self.config.debug,
self.key_manager,
self.bandwidth_controller,
self.reply_surb_storage_backend,
self.disabled_credentials,
disabled_credentials,
vec![self.config.nym_api_url.clone()],
);
+1 -1
View File
@@ -6,7 +6,7 @@ use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub async fn get_gateway(api_server: String, preferred: Option<String>) -> GatewayEndpointConfig {
let validator_client = validator_client::client::ApiClient::new(api_server.parse().unwrap());
let validator_client = validator_client::client::NymApiClient::new(api_server.parse().unwrap());
let gateways = match validator_client.get_cached_gateways().await {
Err(err) => panic!("failed to obtain list of all gateways - {err}"),
@@ -27,6 +27,7 @@ nymsphinx = { path = "../../nymsphinx" }
pemstore = { path = "../../pemstore" }
validator-client = { path = "../validator-client", optional = true }
task = { path = "../../task" }
serde = { version = "1.0", features = ["derive"]}
[dependencies.tungstenite]
@@ -31,7 +31,7 @@ coconut-interface = { path = "../../coconut-interface" }
network-defaults = { path = "../../network-defaults" }
nym-api-requests = { path = "../../../nym-api/nym-api-requests", features = ["coconut"] }
# required for nymd-client
# required for nyxd-client
# at some point it might be possible to make it wasm-compatible
# perhaps after https://github.com/cosmos/cosmos-rust/pull/97 is resolved (and tendermint-rs is updated)
async-trait = { version = "0.1.51", optional = true }
@@ -50,7 +50,7 @@ execute = { path = "../../execute" }
ts-rs = "6.1.2"
[features]
nymd-client = [
nyxd-client = [
"async-trait",
"bip39",
"config",
@@ -15,41 +15,41 @@ use nym_api_requests::models::{
RewardEstimationResponse, StakeSaturationResponse,
};
#[cfg(feature = "nymd-client")]
use crate::nymd::traits::{DkgQueryClient, MixnetQueryClient, MultisigQueryClient};
#[cfg(feature = "nymd-client")]
use crate::nymd::{self, CosmWasmClient, NymdClient, QueryNymdClient, SigningNymdClient};
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use crate::nyxd::traits::{DkgQueryClient, MixnetQueryClient, MultisigQueryClient};
#[cfg(feature = "nyxd-client")]
use crate::nyxd::{self, CosmWasmClient, NyxdClient, QueryNyxdClient, SigningNyxdClient};
#[cfg(feature = "nyxd-client")]
use coconut_dkg_common::{
dealer::ContractDealing, types::DealerDetails, verification_key::ContractVKShare,
};
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use coconut_interface::Base58;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use cw3::ProposalResponse;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use mixnet_contract_common::{
families::{Family, FamilyHead},
mixnode::MixNodeBond,
pending_events::{PendingEpochEvent, PendingIntervalEvent},
Delegation, IdentityKey, RewardedSetNodeStatus, UnbondedMixnode,
};
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use network_defaults::NymNetworkDetails;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use nym_api_requests::models::MixNodeBondAnnotated;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
use std::str::FromStr;
use url::Url;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
#[must_use]
#[derive(Debug, Clone)]
pub struct Config {
api_url: Url,
nymd_url: Url,
nyxd_url: Url,
nymd_config: nymd::Config,
nyxd_config: nyxd::Config,
mixnode_page_limit: Option<u32>,
gateway_page_limit: Option<u32>,
@@ -60,7 +60,7 @@ pub struct Config {
proposals_page_limit: Option<u32>,
}
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
impl Config {
pub fn try_from_nym_network_details(
details: &NymNetworkDetails,
@@ -78,11 +78,11 @@ impl Config {
Ok(Config {
api_url: api_url.pop().unwrap(),
nymd_url: details.endpoints[0]
.nymd_url
nyxd_url: details.endpoints[0]
.nyxd_url
.parse()
.map_err(ValidatorClientError::MalformedUrlProvided)?,
nymd_config: nymd::Config::try_from_nym_network_details(details)?,
nyxd_config: nyxd::Config::try_from_nym_network_details(details)?,
mixnode_page_limit: None,
gateway_page_limit: None,
mixnode_delegations_page_limit: None,
@@ -95,14 +95,14 @@ impl Config {
// TODO: this method shouldn't really exist as all information should be included immediately
// via `from_nym_network_details`, but it's here for, you guessed it, legacy compatibility
pub fn with_urls(mut self, nymd_url: Url, api_url: Url) -> Self {
self.nymd_url = nymd_url;
pub fn with_urls(mut self, nyxd_url: Url, api_url: Url) -> Self {
self.nyxd_url = nyxd_url;
self.api_url = api_url;
self
}
pub fn with_nymd_url(mut self, nymd_url: Url) -> Self {
self.nymd_url = nymd_url;
pub fn with_nyxd_url(mut self, nyxd_url: Url) -> Self {
self.nyxd_url = nyxd_url;
self
}
@@ -127,7 +127,7 @@ impl Config {
}
}
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
pub struct Client<C> {
// TODO: we really shouldn't be storing a mnemonic here, but removing it would be
// non-trivial amount of work and it's out of scope of the current branch
@@ -143,19 +143,19 @@ pub struct Client<C> {
// ideally they would have been read-only, but unfortunately rust doesn't have such features
pub nym_api: nym_api::Client,
pub nymd: NymdClient<C>,
pub nyxd: NyxdClient<C>,
}
#[cfg(feature = "nymd-client")]
impl Client<SigningNymdClient> {
#[cfg(feature = "nyxd-client")]
impl Client<SigningNyxdClient> {
pub fn new_signing(
config: Config,
mnemonic: bip39::Mnemonic,
) -> Result<Client<SigningNymdClient>, ValidatorClientError> {
) -> Result<Client<SigningNyxdClient>, ValidatorClientError> {
let nym_api_client = nym_api::Client::new(config.api_url.clone());
let nymd_client = NymdClient::connect_with_mnemonic(
config.nymd_config.clone(),
config.nymd_url.as_str(),
let nyxd_client = NyxdClient::connect_with_mnemonic(
config.nyxd_config.clone(),
config.nyxd_url.as_str(),
mnemonic.clone(),
None,
)?;
@@ -170,13 +170,13 @@ impl Client<SigningNymdClient> {
verification_key_page_limit: config.verification_key_page_limit,
proposals_page_limit: config.proposals_page_limit,
nym_api: nym_api_client,
nymd: nymd_client,
nyxd: nyxd_client,
})
}
pub fn change_nymd(&mut self, new_endpoint: Url) -> Result<(), ValidatorClientError> {
self.nymd = NymdClient::connect_with_mnemonic(
self.nymd.current_config().clone(),
pub fn change_nyxd(&mut self, new_endpoint: Url) -> Result<(), ValidatorClientError> {
self.nyxd = NyxdClient::connect_with_mnemonic(
self.nyxd.current_config().clone(),
new_endpoint.as_ref(),
self.mnemonic.clone().unwrap(),
None,
@@ -184,17 +184,17 @@ impl Client<SigningNymdClient> {
Ok(())
}
pub fn set_nymd_simulated_gas_multiplier(&mut self, multiplier: f32) {
self.nymd.set_simulated_gas_multiplier(multiplier)
pub fn set_nyxd_simulated_gas_multiplier(&mut self, multiplier: f32) {
self.nyxd.set_simulated_gas_multiplier(multiplier)
}
}
#[cfg(feature = "nymd-client")]
impl Client<QueryNymdClient> {
pub fn new_query(config: Config) -> Result<Client<QueryNymdClient>, ValidatorClientError> {
#[cfg(feature = "nyxd-client")]
impl Client<QueryNyxdClient> {
pub fn new_query(config: Config) -> Result<Client<QueryNyxdClient>, ValidatorClientError> {
let nym_api_client = nym_api::Client::new(config.api_url.clone());
let nymd_client =
NymdClient::connect(config.nymd_config.clone(), config.nymd_url.as_str())?;
let nyxd_client =
NyxdClient::connect(config.nyxd_config.clone(), config.nyxd_url.as_str())?;
Ok(Client {
mnemonic: None,
@@ -206,29 +206,29 @@ impl Client<QueryNymdClient> {
verification_key_page_limit: config.verification_key_page_limit,
proposals_page_limit: config.proposals_page_limit,
nym_api: nym_api_client,
nymd: nymd_client,
nyxd: nyxd_client,
})
}
pub fn change_nymd(&mut self, new_endpoint: Url) -> Result<(), ValidatorClientError> {
self.nymd = NymdClient::connect(self.nymd.current_config().clone(), new_endpoint.as_ref())?;
pub fn change_nyxd(&mut self, new_endpoint: Url) -> Result<(), ValidatorClientError> {
self.nyxd = NyxdClient::connect(self.nyxd.current_config().clone(), new_endpoint.as_ref())?;
Ok(())
}
}
// nymd wrappers
#[cfg(feature = "nymd-client")]
// nyxd wrappers
#[cfg(feature = "nyxd-client")]
impl<C> Client<C> {
// use case: somebody initialised client without a contract in order to upload and initialise one
// and now they want to actually use it without making new client
pub fn set_mixnet_contract_address(&mut self, mixnet_contract_address: cosmrs::AccountId) {
self.nymd
self.nyxd
.set_mixnet_contract_address(mixnet_contract_address)
}
pub fn get_mixnet_contract_address(&self) -> cosmrs::AccountId {
self.nymd.mixnet_contract_address().clone()
self.nyxd.mixnet_contract_address().clone()
}
pub async fn get_all_node_families(&self) -> Result<Vec<Family>, ValidatorClientError>
@@ -240,7 +240,7 @@ impl<C> Client<C> {
loop {
let paged_response = self
.nymd
.nyxd
.get_all_node_families_paged(start_after.take(), None)
.await?;
families.extend(paged_response.families);
@@ -266,7 +266,7 @@ impl<C> Client<C> {
loop {
let paged_response = self
.nymd
.nyxd
.get_all_family_members_paged(start_after.take(), None)
.await?;
members.extend(paged_response.members);
@@ -282,7 +282,7 @@ impl<C> Client<C> {
}
// basically handles paging for us
pub async fn get_all_nymd_rewarded_set_mixnodes(
pub async fn get_all_nyxd_rewarded_set_mixnodes(
&self,
) -> Result<Vec<(MixId, RewardedSetNodeStatus)>, ValidatorClientError>
where
@@ -293,7 +293,7 @@ impl<C> Client<C> {
loop {
let mut paged_response = self
.nymd
.nyxd
.get_rewarded_set_paged(start_after.take(), self.rewarded_set_page_limit)
.await?;
identities.append(&mut paged_response.nodes);
@@ -308,7 +308,7 @@ impl<C> Client<C> {
Ok(identities)
}
pub async fn get_all_nymd_mixnode_bonds(&self) -> Result<Vec<MixNodeBond>, ValidatorClientError>
pub async fn get_all_nyxd_mixnode_bonds(&self) -> Result<Vec<MixNodeBond>, ValidatorClientError>
where
C: CosmWasmClient + Sync + Send,
{
@@ -316,7 +316,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_mixnode_bonds_paged(self.mixnode_page_limit, start_after.take())
.await?;
mixnodes.append(&mut paged_response.nodes);
@@ -331,7 +331,7 @@ impl<C> Client<C> {
Ok(mixnodes)
}
pub async fn get_all_nymd_mixnodes_detailed(
pub async fn get_all_nyxd_mixnodes_detailed(
&self,
) -> Result<Vec<MixNodeDetails>, ValidatorClientError>
where
@@ -341,7 +341,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_mixnodes_detailed_paged(self.mixnode_page_limit, start_after.take())
.await?;
mixnodes.append(&mut paged_response.nodes);
@@ -356,7 +356,7 @@ impl<C> Client<C> {
Ok(mixnodes)
}
pub async fn get_all_nymd_unbonded_mixnodes(
pub async fn get_all_nyxd_unbonded_mixnodes(
&self,
) -> Result<Vec<(MixId, UnbondedMixnode)>, ValidatorClientError>
where
@@ -366,7 +366,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_unbonded_paged(self.mixnode_page_limit, start_after.take())
.await?;
mixnodes.append(&mut paged_response.nodes);
@@ -381,7 +381,7 @@ impl<C> Client<C> {
Ok(mixnodes)
}
pub async fn get_all_nymd_unbonded_mixnodes_by_owner(
pub async fn get_all_nyxd_unbonded_mixnodes_by_owner(
&self,
owner: &cosmrs::AccountId,
) -> Result<Vec<(MixId, UnbondedMixnode)>, ValidatorClientError>
@@ -392,7 +392,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_unbonded_by_owner_paged(owner, self.mixnode_page_limit, start_after.take())
.await?;
mixnodes.append(&mut paged_response.nodes);
@@ -407,7 +407,7 @@ impl<C> Client<C> {
Ok(mixnodes)
}
pub async fn get_all_nymd_unbonded_mixnodes_by_identity(
pub async fn get_all_nyxd_unbonded_mixnodes_by_identity(
&self,
identity_key: String,
) -> Result<Vec<(MixId, UnbondedMixnode)>, ValidatorClientError>
@@ -418,7 +418,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_unbonded_by_identity_paged(
identity_key.clone(),
self.mixnode_page_limit,
@@ -437,7 +437,7 @@ impl<C> Client<C> {
Ok(mixnodes)
}
pub async fn get_all_nymd_gateways(&self) -> Result<Vec<GatewayBond>, ValidatorClientError>
pub async fn get_all_nyxd_gateways(&self) -> Result<Vec<GatewayBond>, ValidatorClientError>
where
C: CosmWasmClient + Sync + Send,
{
@@ -445,7 +445,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_gateways_paged(start_after.take(), self.gateway_page_limit)
.await?;
gateways.append(&mut paged_response.nodes);
@@ -460,7 +460,7 @@ impl<C> Client<C> {
Ok(gateways)
}
pub async fn get_all_nymd_single_mixnode_delegations(
pub async fn get_all_nyxd_single_mixnode_delegations(
&self,
mix_id: MixId,
) -> Result<Vec<Delegation>, ValidatorClientError>
@@ -471,7 +471,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_mixnode_delegations_paged(
mix_id,
start_after.take(),
@@ -501,7 +501,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_delegator_delegations_paged(
delegation_owner.to_string(),
start_after.take(),
@@ -528,7 +528,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_all_network_delegations_paged(
start_after.take(),
self.mixnode_delegations_page_limit,
@@ -546,7 +546,7 @@ impl<C> Client<C> {
Ok(delegations)
}
pub async fn get_all_nymd_pending_epoch_events(
pub async fn get_all_nyxd_pending_epoch_events(
&self,
) -> Result<Vec<PendingEpochEvent>, ValidatorClientError>
where
@@ -557,7 +557,7 @@ impl<C> Client<C> {
loop {
let mut paged_response = self
.nymd
.nyxd
.get_pending_epoch_events_paged(start_after.take(), self.rewarded_set_page_limit)
.await?;
events.append(&mut paged_response.events);
@@ -572,7 +572,7 @@ impl<C> Client<C> {
Ok(events)
}
pub async fn get_all_nymd_pending_interval_events(
pub async fn get_all_nyxd_pending_interval_events(
&self,
) -> Result<Vec<PendingIntervalEvent>, ValidatorClientError>
where
@@ -583,7 +583,7 @@ impl<C> Client<C> {
loop {
let mut paged_response = self
.nymd
.nyxd
.get_pending_interval_events_paged(start_after.take(), self.rewarded_set_page_limit)
.await?;
events.append(&mut paged_response.events);
@@ -598,7 +598,7 @@ impl<C> Client<C> {
Ok(events)
}
pub async fn get_all_nymd_current_dealers(
pub async fn get_all_nyxd_current_dealers(
&self,
) -> Result<Vec<DealerDetails>, ValidatorClientError>
where
@@ -608,7 +608,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_current_dealers_paged(start_after.take(), self.dealers_page_limit)
.await?;
dealers.append(&mut paged_response.dealers);
@@ -623,7 +623,7 @@ impl<C> Client<C> {
Ok(dealers)
}
pub async fn get_all_nymd_past_dealers(
pub async fn get_all_nyxd_past_dealers(
&self,
) -> Result<Vec<DealerDetails>, ValidatorClientError>
where
@@ -633,7 +633,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_past_dealers_paged(start_after.take(), self.dealers_page_limit)
.await?;
dealers.append(&mut paged_response.dealers);
@@ -648,7 +648,7 @@ impl<C> Client<C> {
Ok(dealers)
}
pub async fn get_all_nymd_epoch_dealings(
pub async fn get_all_nyxd_epoch_dealings(
&self,
idx: usize,
) -> Result<Vec<ContractDealing>, ValidatorClientError>
@@ -659,7 +659,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_dealings_paged(idx, start_after.take(), self.dealers_page_limit)
.await?;
dealings.append(&mut paged_response.dealings);
@@ -674,7 +674,7 @@ impl<C> Client<C> {
Ok(dealings)
}
pub async fn get_all_nymd_verification_key_shares(
pub async fn get_all_nyxd_verification_key_shares(
&self,
) -> Result<Vec<ContractVKShare>, ValidatorClientError>
where
@@ -684,7 +684,7 @@ impl<C> Client<C> {
let mut start_after = None;
loop {
let mut paged_response = self
.nymd
.nyxd
.get_vk_shares_paged(start_after.take(), self.verification_key_page_limit)
.await?;
shares.append(&mut paged_response.shares);
@@ -699,7 +699,7 @@ impl<C> Client<C> {
Ok(shares)
}
pub async fn get_all_nymd_proposals(
pub async fn get_all_nyxd_proposals(
&self,
) -> Result<Vec<ProposalResponse>, ValidatorClientError>
where
@@ -710,7 +710,7 @@ impl<C> Client<C> {
loop {
let mut paged_response = self
.nymd
.nyxd
.list_proposals(start_after.take(), self.proposals_page_limit)
.await?;
@@ -729,7 +729,7 @@ impl<C> Client<C> {
}
// validator-api wrappers
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
impl<C> Client<C> {
pub fn change_nym_api(&mut self, new_endpoint: Url) {
self.nym_api.change_url(new_endpoint)
@@ -783,23 +783,23 @@ impl<C> Client<C> {
#[derive(Clone)]
pub struct CoconutApiClient {
pub api_client: ApiClient,
pub api_client: NymApiClient,
pub verification_key: VerificationKey,
pub node_id: NodeIndex,
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
pub cosmos_address: cosmrs::AccountId,
}
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
impl CoconutApiClient {
pub async fn all_coconut_api_clients<C>(
nymd_client: &Client<C>,
nyxd_client: &Client<C>,
) -> Result<Vec<Self>, ValidatorClientError>
where
C: CosmWasmClient + Sync + Send,
{
Ok(nymd_client
.get_all_nymd_verification_key_shares()
Ok(nyxd_client
.get_all_nyxd_verification_key_shares()
.await?
.into_iter()
.filter_map(Self::try_from)
@@ -812,7 +812,7 @@ impl CoconutApiClient {
if let Ok(verification_key) = VerificationKey::try_from_bs58(&share.share) {
if let Ok(cosmos_address) = cosmrs::AccountId::from_str(share.owner.as_str()) {
return Some(CoconutApiClient {
api_client: ApiClient::new(url_address),
api_client: NymApiClient::new(url_address),
verification_key,
node_id: share.node_index,
cosmos_address,
@@ -826,17 +826,17 @@ impl CoconutApiClient {
}
#[derive(Clone)]
pub struct ApiClient {
pub struct NymApiClient {
pub nym_api_client: nym_api::Client,
// TODO: perhaps if we really need it at some (currently I don't see any reasons for it)
// we could re-implement the communication with the REST API on port 1317
}
impl ApiClient {
impl NymApiClient {
pub fn new(api_url: Url) -> Self {
let nym_api_client = nym_api::Client::new(api_url);
ApiClient { nym_api_client }
NymApiClient { nym_api_client }
}
pub fn change_nym_api(&mut self, new_endpoint: Url) {
@@ -1,8 +1,8 @@
use crate::nymd::error::NymdError;
use crate::nymd::{Config as ClientConfig, NymdClient, QueryNymdClient};
use crate::ApiClient;
use crate::nyxd::error::NyxdError;
use crate::nyxd::{Config as ClientConfig, NyxdClient, QueryNyxdClient};
use crate::NymApiClient;
use crate::nymd::traits::MixnetQueryClient;
use crate::nyxd::traits::MixnetQueryClient;
use colored::Colorize;
use core::fmt;
use itertools::Itertools;
@@ -16,9 +16,9 @@ use url::Url;
const MAX_URLS_TESTED: usize = 200;
const CONNECTION_TEST_TIMEOUT_SEC: u64 = 2;
// Run connection tests for all specified nymd and api urls. These are all run concurrently.
/// Run connection tests for all specified nyxd and api urls. These are all run concurrently.
pub async fn run_validator_connection_test<H: BuildHasher + 'static>(
nymd_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
nyxd_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
api_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
mixnet_contract_address: HashMap<NymNetworkDetails, cosmrs::AccountId, H>,
) -> (
@@ -27,7 +27,7 @@ pub async fn run_validator_connection_test<H: BuildHasher + 'static>(
) {
// Setup all the clients for the connection tests
let connection_test_clients =
setup_connection_tests(nymd_urls, api_urls, mixnet_contract_address);
setup_connection_tests(nyxd_urls, api_urls, mixnet_contract_address);
// Run all tests concurrently
let connection_results = futures::future::join_all(
@@ -40,28 +40,28 @@ pub async fn run_validator_connection_test<H: BuildHasher + 'static>(
// Seperate and collect results into HashMaps
(
extract_and_collect_results_into_map(&connection_results, &UrlType::Nymd),
extract_and_collect_results_into_map(&connection_results, &UrlType::Api),
extract_and_collect_results_into_map(&connection_results, &UrlType::Nyxd),
extract_and_collect_results_into_map(&connection_results, &UrlType::NymApi),
)
}
fn setup_connection_tests<H: BuildHasher + 'static>(
nymd_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
nyxd_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
api_urls: impl Iterator<Item = (NymNetworkDetails, Url)>,
mixnet_contract_address: HashMap<NymNetworkDetails, cosmrs::AccountId, H>,
) -> impl Iterator<Item = ClientForConnectionTest> {
let nymd_connection_test_clients = nymd_urls.filter_map(move |(network, url)| {
let nyxd_connection_test_clients = nyxd_urls.filter_map(move |(network, url)| {
let address = mixnet_contract_address
.get(&network)
.expect("No configured contract address")
.clone();
let config = ClientConfig::try_from_nym_network_details(&network)
.expect("failed to create valid nymd client config");
.expect("failed to create valid nyxd client config");
if let Ok(mut client) = NymdClient::<QueryNymdClient>::connect(config, url.as_str()) {
if let Ok(mut client) = NyxdClient::<QueryNyxdClient>::connect(config, url.as_str()) {
// possibly redundant, but lets just leave it here
client.set_mixnet_contract_address(address);
Some(ClientForConnectionTest::Nymd(
Some(ClientForConnectionTest::Nyxd(
network,
url,
Box::new(client),
@@ -72,10 +72,10 @@ fn setup_connection_tests<H: BuildHasher + 'static>(
});
let api_connection_test_clients = api_urls.map(|(network, url)| {
ClientForConnectionTest::Api(network, url.clone(), ApiClient::new(url))
ClientForConnectionTest::Api(network, url.clone(), NymApiClient::new(url))
});
nymd_connection_test_clients.chain(api_connection_test_clients)
nyxd_connection_test_clients.chain(api_connection_test_clients)
}
fn extract_and_collect_results_into_map(
@@ -92,10 +92,10 @@ fn extract_and_collect_results_into_map(
.into_group_map()
}
async fn test_nymd_connection(
async fn test_nyxd_connection(
network: NymNetworkDetails,
url: &Url,
client: &NymdClient<QueryNymdClient>,
client: &NyxdClient<QueryNyxdClient>,
) -> ConnectionResult {
let result = match timeout(
Duration::from_secs(CONNECTION_TEST_TIMEOUT_SEC),
@@ -103,48 +103,48 @@ async fn test_nymd_connection(
)
.await
{
Ok(Err(NymdError::TendermintError(e))) => {
Ok(Err(NyxdError::TendermintError(e))) => {
// If we get a tendermint-rpc error, we classify the node as not contactable
log::debug!("Checking: nymd_url: {url}: {}: {}", "failed".red(), e);
log::debug!("Checking: nyxd url: {url}: {}: {}", "failed".red(), e);
false
}
Ok(Err(NymdError::AbciError { code, log, .. })) => {
Ok(Err(NyxdError::AbciError { code, log, .. })) => {
// We accept the mixnet contract not found as ok from a connection standpoint. This happens
// for example on a pre-launch network.
log::debug!(
"Checking: nymd_url: {url}: {}, but with abci error: {code}: {log}",
"Checking: nyxd url: {url}: {}, but with abci error: {code}: {log}",
"success".green()
);
code == 18
}
Ok(Err(error @ NymdError::NoContractAddressAvailable)) => {
log::debug!("Checking: nymd_url: {url}: {}: {error}", "failed".red());
Ok(Err(error @ NyxdError::NoContractAddressAvailable)) => {
log::debug!("Checking: nyxd url: {url}: {}: {error}", "failed".red());
false
}
Ok(Err(e)) => {
// For any other error, we're optimistic and just try anyway.
log::debug!(
"Checking: nymd_url: {url}: {}, but with error: {e}",
"Checking: nyxd_url: {url}: {}, but with error: {e}",
"success".green()
);
true
}
Ok(Ok(_)) => {
log::debug!("Checking: nymd_url: {url}: {}", "success".green());
log::debug!("Checking: nyxd_url: {url}: {}", "success".green());
true
}
Err(e) => {
log::debug!("Checking: nymd_url: {url}: {}: {e}", "failed".red());
log::debug!("Checking: nyxd_url: {url}: {}: {e}", "failed".red());
false
}
};
ConnectionResult::Nymd(network, url.clone(), result)
ConnectionResult::Nyxd(network, url.clone(), result)
}
async fn test_api_connection(
async fn test_nym_api_connection(
network: NymNetworkDetails,
url: &Url,
client: &ApiClient,
client: &NymApiClient,
) -> ConnectionResult {
let result = match timeout(
Duration::from_secs(CONNECTION_TEST_TIMEOUT_SEC),
@@ -169,18 +169,18 @@ async fn test_api_connection(
}
enum ClientForConnectionTest {
Nymd(NymNetworkDetails, Url, Box<NymdClient<QueryNymdClient>>),
Api(NymNetworkDetails, Url, ApiClient),
Nyxd(NymNetworkDetails, Url, Box<NyxdClient<QueryNyxdClient>>),
Api(NymNetworkDetails, Url, NymApiClient),
}
impl ClientForConnectionTest {
async fn run_connection_check(self) -> ConnectionResult {
match self {
ClientForConnectionTest::Nymd(network, ref url, ref client) => {
test_nymd_connection(network, url, client).await
ClientForConnectionTest::Nyxd(network, ref url, ref client) => {
test_nyxd_connection(network, url, client).await
}
ClientForConnectionTest::Api(network, ref url, ref client) => {
test_api_connection(network, url, client).await
test_nym_api_connection(network, url, client).await
}
}
}
@@ -188,37 +188,37 @@ impl ClientForConnectionTest {
#[derive(Debug, PartialEq, Eq)]
enum UrlType {
Nymd,
Api,
Nyxd,
NymApi,
}
impl fmt::Display for UrlType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
UrlType::Nymd => write!(f, "nymd"),
UrlType::Api => write!(f, "api"),
UrlType::Nyxd => write!(f, "nyxd"),
UrlType::NymApi => write!(f, "api"),
}
}
}
#[derive(Debug)]
enum ConnectionResult {
Nymd(NymNetworkDetails, Url, bool),
Nyxd(NymNetworkDetails, Url, bool),
Api(NymNetworkDetails, Url, bool),
}
impl ConnectionResult {
fn result(&self) -> (&NymNetworkDetails, &Url, &bool) {
match self {
ConnectionResult::Nymd(network, url, result)
ConnectionResult::Nyxd(network, url, result)
| ConnectionResult::Api(network, url, result) => (network, url, result),
}
}
fn url_type(&self) -> UrlType {
match self {
ConnectionResult::Nymd(..) => UrlType::Nymd,
ConnectionResult::Api(..) => UrlType::Api,
ConnectionResult::Nyxd(..) => UrlType::Nyxd,
ConnectionResult::Api(..) => UrlType::NymApi,
}
}
}
@@ -15,9 +15,9 @@ pub enum ValidatorClientError {
#[error("One of the provided URLs was malformed - {0}")]
MalformedUrlProvided(#[from] url::ParseError),
#[cfg(feature = "nymd-client")]
#[error("There was an issue with the Nymd client - {0}")]
NymdError(#[from] crate::nymd::error::NymdError),
#[cfg(feature = "nyxd-client")]
#[error("There was an issue with the Nyxd client - {0}")]
NyxdError(#[from] crate::nyxd::error::NyxdError),
#[error("No validator API url has been provided")]
NoAPIUrlAvailable,
@@ -2,17 +2,17 @@
// SPDX-License-Identifier: Apache-2.0
pub mod client;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
pub mod connection_tester;
mod error;
pub mod nym_api;
#[cfg(feature = "nymd-client")]
pub mod nymd;
#[cfg(feature = "nyxd-client")]
pub mod nyxd;
#[cfg(feature = "nymd-client")]
pub use crate::client::{ApiClient, CoconutApiClient};
#[cfg(feature = "nyxd-client")]
pub use crate::client::{CoconutApiClient, NymApiClient};
pub use crate::error::ValidatorClientError;
pub use nym_api_requests::*;
#[cfg(feature = "nymd-client")]
#[cfg(feature = "nyxd-client")]
pub use client::{Client, Config};
@@ -1,313 +0,0 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::coin::Coin;
pub use crate::nymd::cosmwasm_client::client::CosmWasmClient;
use crate::nymd::error::NymdError;
use crate::nymd::NymdClient;
use async_trait::async_trait;
use contracts_common::ContractBuildInformation;
use cosmwasm_std::{Coin as CosmWasmCoin, Timestamp};
use mixnet_contract_common::MixId;
use serde::Deserialize;
use vesting_contract::vesting::Account;
use vesting_contract_common::{
messages::QueryMsg as VestingQueryMsg, AllDelegationsResponse, DelegationTimesResponse,
OriginalVestingResponse, Period, PledgeData, VestingDelegation,
};
#[async_trait]
pub trait VestingQueryClient {
async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NymdError>
where
for<'a> T: Deserialize<'a>;
async fn get_vesting_contract_version(&self) -> Result<ContractBuildInformation, NymdError> {
self.query_vesting_contract(VestingQueryMsg::GetContractVersion {})
.await
}
async fn locked_coins(
&self,
address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>;
async fn spendable_coins(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>;
async fn vested_coins(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>;
async fn vesting_coins(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>;
async fn vesting_start_time(
&self,
vesting_account_address: &str,
) -> Result<Timestamp, NymdError>;
async fn vesting_end_time(&self, vesting_account_address: &str)
-> Result<Timestamp, NymdError>;
async fn original_vesting(
&self,
vesting_account_address: &str,
) -> Result<OriginalVestingResponse, NymdError>;
async fn delegated_free(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>;
async fn delegated_vesting(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError>;
async fn get_account(&self, address: &str) -> Result<Account, NymdError>;
async fn get_mixnode_pledge(&self, address: &str) -> Result<Option<PledgeData>, NymdError>;
async fn get_gateway_pledge(&self, address: &str) -> Result<Option<PledgeData>, NymdError>;
async fn get_current_vesting_period(
&self,
vesting_account_address: &str,
) -> Result<Period, NymdError>;
async fn get_delegation_timestamps(
&self,
address: &str,
mix_id: MixId,
) -> Result<DelegationTimesResponse, NymdError>;
async fn get_all_vesting_delegations_paged(
&self,
start_after: Option<(u32, MixId, u64)>,
limit: Option<u32>,
) -> Result<AllDelegationsResponse, NymdError>;
async fn get_all_vesting_delegations(&self) -> Result<Vec<VestingDelegation>, NymdError> {
let mut delegations = Vec::new();
let mut start_after = None;
loop {
let mut paged_response = self
.get_all_vesting_delegations_paged(start_after.take(), None)
.await?;
delegations.append(&mut paged_response.delegations);
if let Some(start_after_res) = paged_response.start_next_after {
start_after = Some(start_after_res)
} else {
break;
}
}
Ok(delegations)
}
}
#[async_trait]
impl<C: CosmWasmClient + Sync + Send> VestingQueryClient for NymdClient<C> {
async fn query_vesting_contract<T>(&self, query: VestingQueryMsg) -> Result<T, NymdError>
where
for<'a> T: Deserialize<'a>,
{
self.client
.query_contract_smart(self.vesting_contract_address(), &query)
.await
}
async fn locked_coins(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> {
let request = VestingQueryMsg::LockedCoins {
vesting_account_address: vesting_account_address.to_string(),
block_time,
};
self.client
.query_contract_smart::<_, CosmWasmCoin>(self.vesting_contract_address(), &request)
.await
.map(Into::into)
}
async fn spendable_coins(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> {
let request = VestingQueryMsg::SpendableCoins {
vesting_account_address: vesting_account_address.to_string(),
block_time,
};
self.client
.query_contract_smart::<_, CosmWasmCoin>(self.vesting_contract_address(), &request)
.await
.map(Into::into)
}
async fn vested_coins(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> {
let request = VestingQueryMsg::GetVestedCoins {
vesting_account_address: vesting_account_address.to_string(),
block_time,
};
self.client
.query_contract_smart::<_, CosmWasmCoin>(self.vesting_contract_address(), &request)
.await
.map(Into::into)
}
async fn vesting_coins(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> {
let request = VestingQueryMsg::GetVestingCoins {
vesting_account_address: vesting_account_address.to_string(),
block_time,
};
self.client
.query_contract_smart::<_, CosmWasmCoin>(self.vesting_contract_address(), &request)
.await
.map(Into::into)
}
async fn vesting_start_time(
&self,
vesting_account_address: &str,
) -> Result<Timestamp, NymdError> {
let request = VestingQueryMsg::GetStartTime {
vesting_account_address: vesting_account_address.to_string(),
};
self.client
.query_contract_smart(self.vesting_contract_address(), &request)
.await
}
async fn vesting_end_time(
&self,
vesting_account_address: &str,
) -> Result<Timestamp, NymdError> {
let request = VestingQueryMsg::GetEndTime {
vesting_account_address: vesting_account_address.to_string(),
};
self.client
.query_contract_smart(self.vesting_contract_address(), &request)
.await
}
async fn original_vesting(
&self,
vesting_account_address: &str,
) -> Result<OriginalVestingResponse, NymdError> {
let request = VestingQueryMsg::GetOriginalVesting {
vesting_account_address: vesting_account_address.to_string(),
};
self.client
.query_contract_smart(self.vesting_contract_address(), &request)
.await
}
async fn delegated_free(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> {
let request = VestingQueryMsg::GetDelegatedFree {
vesting_account_address: vesting_account_address.to_string(),
block_time,
};
self.client
.query_contract_smart::<_, CosmWasmCoin>(self.vesting_contract_address(), &request)
.await
.map(Into::into)
}
/// Returns the total amount of delegated tokens that have vested
async fn delegated_vesting(
&self,
vesting_account_address: &str,
block_time: Option<Timestamp>,
) -> Result<Coin, NymdError> {
let request = VestingQueryMsg::GetDelegatedVesting {
vesting_account_address: vesting_account_address.to_string(),
block_time,
};
self.client
.query_contract_smart::<_, CosmWasmCoin>(self.vesting_contract_address(), &request)
.await
.map(Into::into)
}
async fn get_account(&self, address: &str) -> Result<Account, NymdError> {
let request = VestingQueryMsg::GetAccount {
address: address.to_string(),
};
self.client
.query_contract_smart(self.vesting_contract_address(), &request)
.await
}
async fn get_mixnode_pledge(&self, address: &str) -> Result<Option<PledgeData>, NymdError> {
let request = VestingQueryMsg::GetMixnode {
address: address.to_string(),
};
self.client
.query_contract_smart(self.vesting_contract_address(), &request)
.await
}
async fn get_gateway_pledge(&self, address: &str) -> Result<Option<PledgeData>, NymdError> {
let request = VestingQueryMsg::GetGateway {
address: address.to_string(),
};
self.client
.query_contract_smart(self.vesting_contract_address(), &request)
.await
}
async fn get_current_vesting_period(&self, address: &str) -> Result<Period, NymdError> {
let request = VestingQueryMsg::GetCurrentVestingPeriod {
address: address.to_string(),
};
self.client
.query_contract_smart(self.vesting_contract_address(), &request)
.await
}
async fn get_delegation_timestamps(
&self,
address: &str,
mix_id: MixId,
) -> Result<DelegationTimesResponse, NymdError> {
let request = VestingQueryMsg::GetDelegationTimes {
address: address.to_string(),
mix_id,
};
self.client
.query_contract_smart(self.vesting_contract_address(), &request)
.await
}
async fn get_all_vesting_delegations_paged(
&self,
start_after: Option<(u32, MixId, u64)>,
limit: Option<u32>,
) -> Result<AllDelegationsResponse, NymdError> {
let request = VestingQueryMsg::GetAllDelegations { start_after, limit };
self.client
.query_contract_smart(self.vesting_contract_address(), &request)
.await
}
}
@@ -1,14 +1,14 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd;
use crate::nymd::coin::Coin;
use crate::nymd::cosmwasm_client::helpers::{create_pagination, next_page_key};
use crate::nymd::cosmwasm_client::types::{
use crate::nyxd;
use crate::nyxd::coin::Coin;
use crate::nyxd::cosmwasm_client::helpers::{create_pagination, next_page_key};
use crate::nyxd::cosmwasm_client::types::{
Account, Code, CodeDetails, Contract, ContractCodeHistoryEntry, ContractCodeId,
SequenceResponse, SimulateResponse,
};
use crate::nymd::error::NymdError;
use crate::nyxd::error::NyxdError;
use async_trait::async_trait;
use cosmrs::proto::cosmos::auth::v1beta1::{QueryAccountRequest, QueryAccountResponse};
use cosmrs::proto::cosmos::bank::v1beta1::{
@@ -57,7 +57,7 @@ pub trait CosmWasmClient: rpc::Client {
&self,
path: Option<abci::Path>,
req: Req,
) -> Result<Res, NymdError>
) -> Result<Res, NyxdError>
where
Req: Message,
Res: Message + Default,
@@ -66,21 +66,21 @@ pub trait CosmWasmClient: rpc::Client {
req.encode(&mut buf)?;
let res = self.abci_query(path, buf, None, false).await?;
let res_success = nymd::error::parse_abci_query_result(res)?;
let res_success = nyxd::error::parse_abci_query_result(res)?;
Ok(Res::decode(res_success.value.as_ref())?)
}
async fn get_chain_id(&self) -> Result<chain::Id, NymdError> {
async fn get_chain_id(&self) -> Result<chain::Id, NyxdError> {
Ok(self.status().await?.node_info.network)
}
async fn get_height(&self) -> Result<block::Height, NymdError> {
async fn get_height(&self) -> Result<block::Height, NyxdError> {
Ok(self.status().await?.sync_info.latest_block_height)
}
// TODO: the return type should probably be changed to a non-proto, type-safe Account alternative
async fn get_account(&self, address: &AccountId) -> Result<Option<Account>, NymdError> {
async fn get_account(&self, address: &AccountId) -> Result<Option<Account>, NyxdError> {
let path = Some("/cosmos.auth.v1beta1.Query/Account".parse().unwrap());
let req = QueryAccountRequest {
@@ -94,11 +94,11 @@ pub trait CosmWasmClient: rpc::Client {
res.account.map(TryFrom::try_from).transpose()
}
async fn get_sequence(&self, address: &AccountId) -> Result<SequenceResponse, NymdError> {
async fn get_sequence(&self, address: &AccountId) -> Result<SequenceResponse, NyxdError> {
let account = self
.get_account(address)
.await?
.ok_or_else(|| NymdError::NonExistentAccountError(address.clone()))?;
.ok_or_else(|| NyxdError::NonExistentAccountError(address.clone()))?;
let base_account = account.try_get_base_account()?;
Ok(SequenceResponse {
@@ -107,7 +107,7 @@ pub trait CosmWasmClient: rpc::Client {
})
}
async fn get_block(&self, height: Option<u32>) -> Result<BlockResponse, NymdError> {
async fn get_block(&self, height: Option<u32>) -> Result<BlockResponse, NyxdError> {
match height {
Some(height) => self.block(height).await.map_err(|err| err.into()),
None => self.latest_block().await.map_err(|err| err.into()),
@@ -118,7 +118,7 @@ pub trait CosmWasmClient: rpc::Client {
&self,
address: &AccountId,
search_denom: String,
) -> Result<Option<Coin>, NymdError> {
) -> Result<Option<Coin>, NyxdError> {
let path = Some("/cosmos.bank.v1beta1.Query/Balance".parse().unwrap());
let req = QueryBalanceRequest {
@@ -133,10 +133,10 @@ pub trait CosmWasmClient: rpc::Client {
res.balance
.map(|proto| CosmosCoin::try_from(proto).map(Into::into))
.transpose()
.map_err(|_| NymdError::SerializationError("Coin".to_owned()))
.map_err(|_| NyxdError::SerializationError("Coin".to_owned()))
}
async fn get_all_balances(&self, address: &AccountId) -> Result<Vec<Coin>, NymdError> {
async fn get_all_balances(&self, address: &AccountId) -> Result<Vec<Coin>, NyxdError> {
let path = Some("/cosmos.bank.v1beta1.Query/AllBalances".parse().unwrap());
let mut raw_balances = Vec::new();
@@ -164,10 +164,10 @@ pub trait CosmWasmClient: rpc::Client {
.into_iter()
.map(|proto| CosmosCoin::try_from(proto).map(Into::into))
.collect::<Result<_, _>>()
.map_err(|_| NymdError::SerializationError("Coins".to_owned()))
.map_err(|_| NyxdError::SerializationError("Coins".to_owned()))
}
async fn get_total_supply(&self) -> Result<Vec<Coin>, NymdError> {
async fn get_total_supply(&self) -> Result<Vec<Coin>, NyxdError> {
let path = Some("/cosmos.bank.v1beta1.Query/TotalSupply".parse().unwrap());
let mut supply = Vec::new();
@@ -192,14 +192,14 @@ pub trait CosmWasmClient: rpc::Client {
.into_iter()
.map(|proto| CosmosCoin::try_from(proto).map(Into::into))
.collect::<Result<_, _>>()
.map_err(|_| NymdError::SerializationError("Coins".to_owned()))
.map_err(|_| NyxdError::SerializationError("Coins".to_owned()))
}
async fn get_tx(&self, id: tx::Hash) -> Result<TxResponse, NymdError> {
async fn get_tx(&self, id: tx::Hash) -> Result<TxResponse, NyxdError> {
Ok(self.tx(id, false).await?)
}
async fn search_tx(&self, query: Query) -> Result<Vec<TxResponse>, NymdError> {
async fn search_tx(&self, query: Query) -> Result<Vec<TxResponse>, NyxdError> {
// according to https://docs.tendermint.com/master/rpc/#/Info/tx_search
// the maximum entries per page is 100 and the default is 30
// so let's attempt to use the maximum
@@ -234,7 +234,7 @@ pub trait CosmWasmClient: rpc::Client {
async fn broadcast_tx_async(
&self,
tx: Transaction,
) -> Result<broadcast::tx_async::Response, NymdError> {
) -> Result<broadcast::tx_async::Response, NyxdError> {
Ok(rpc::Client::broadcast_tx_async(self, tx).await?)
}
@@ -242,7 +242,7 @@ pub trait CosmWasmClient: rpc::Client {
async fn broadcast_tx_sync(
&self,
tx: Transaction,
) -> Result<broadcast::tx_sync::Response, NymdError> {
) -> Result<broadcast::tx_sync::Response, NyxdError> {
Ok(rpc::Client::broadcast_tx_sync(self, tx).await?)
}
@@ -250,16 +250,16 @@ pub trait CosmWasmClient: rpc::Client {
async fn broadcast_tx_commit(
&self,
tx: Transaction,
) -> Result<broadcast::tx_commit::Response, NymdError> {
) -> Result<broadcast::tx_commit::Response, NyxdError> {
Ok(rpc::Client::broadcast_tx_commit(self, tx).await?)
}
async fn broadcast_tx(&self, tx: Transaction) -> Result<TxResponse, NymdError> {
async fn broadcast_tx(&self, tx: Transaction) -> Result<TxResponse, NyxdError> {
let broadcasted = CosmWasmClient::broadcast_tx_sync(self, tx).await?;
if broadcasted.code.is_err() {
let code_val = broadcasted.code.value();
return Err(NymdError::BroadcastTxErrorDeliverTx {
return Err(NyxdError::BroadcastTxErrorDeliverTx {
hash: broadcasted.hash,
height: None,
code: code_val,
@@ -276,7 +276,7 @@ pub trait CosmWasmClient: rpc::Client {
broadcasted.hash
);
if tokio::time::Instant::now().duration_since(start) >= self.broadcast_timeout() {
return Err(NymdError::BroadcastTimeout {
return Err(NyxdError::BroadcastTimeout {
hash: tx_hash,
timeout: self.broadcast_timeout(),
});
@@ -290,7 +290,7 @@ pub trait CosmWasmClient: rpc::Client {
}
}
async fn get_codes(&self) -> Result<Vec<Code>, NymdError> {
async fn get_codes(&self) -> Result<Vec<Code>, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/Codes".parse().unwrap());
let mut raw_codes = Vec::new();
@@ -317,7 +317,7 @@ pub trait CosmWasmClient: rpc::Client {
.collect::<Result<_, _>>()
}
async fn get_code_details(&self, code_id: ContractCodeId) -> Result<CodeDetails, NymdError> {
async fn get_code_details(&self, code_id: ContractCodeId) -> Result<CodeDetails, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/Code".parse().unwrap());
let req = QueryCodeRequest { code_id };
@@ -329,10 +329,10 @@ pub trait CosmWasmClient: rpc::Client {
if let Some(code_info) = res.code_info {
Ok(CodeDetails::new(code_info.try_into()?, res.data))
} else {
Err(NymdError::NoCodeInformation(code_id))
Err(NyxdError::NoCodeInformation(code_id))
}
}
async fn get_contracts(&self, code_id: ContractCodeId) -> Result<Vec<AccountId>, NymdError> {
async fn get_contracts(&self, code_id: ContractCodeId) -> Result<Vec<AccountId>, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/ContractsByCode".parse().unwrap());
let mut raw_contracts = Vec::new();
@@ -360,10 +360,10 @@ pub trait CosmWasmClient: rpc::Client {
.iter()
.map(|raw| raw.parse())
.collect::<Result<_, _>>()
.map_err(|_| NymdError::DeserializationError("Contract addresses".to_owned()))
.map_err(|_| NyxdError::DeserializationError("Contract addresses".to_owned()))
}
async fn get_contract(&self, address: &AccountId) -> Result<Contract, NymdError> {
async fn get_contract(&self, address: &AccountId) -> Result<Contract, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/ContractInfo".parse().unwrap());
let req = QueryContractInfoRequest {
@@ -378,17 +378,17 @@ pub trait CosmWasmClient: rpc::Client {
if let Some(contract_info) = res.contract_info {
let address = response_address
.parse()
.map_err(|_| NymdError::MalformedAccountAddress(response_address))?;
.map_err(|_| NyxdError::MalformedAccountAddress(response_address))?;
Ok(Contract::new(address, contract_info.try_into()?))
} else {
Err(NymdError::NoContractInformation(address.clone()))
Err(NyxdError::NoContractInformation(address.clone()))
}
}
async fn get_contract_code_history(
&self,
address: &AccountId,
) -> Result<Vec<ContractCodeHistoryEntry>, NymdError> {
) -> Result<Vec<ContractCodeHistoryEntry>, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/ContractHistory".parse().unwrap());
let mut raw_entries = Vec::new();
@@ -422,7 +422,7 @@ pub trait CosmWasmClient: rpc::Client {
&self,
address: &AccountId,
query_data: Vec<u8>,
) -> Result<Vec<u8>, NymdError> {
) -> Result<Vec<u8>, NyxdError> {
let path = Some("/cosmwasm.wasm.v1.Query/RawContractState".parse().unwrap());
let req = QueryRawContractStateRequest {
@@ -441,7 +441,7 @@ pub trait CosmWasmClient: rpc::Client {
&self,
address: &AccountId,
query_msg: &M,
) -> Result<T, NymdError>
) -> Result<T, NyxdError>
where
M: ?Sized + Serialize + Sync,
for<'a> T: Deserialize<'a>,
@@ -478,7 +478,7 @@ pub trait CosmWasmClient: rpc::Client {
&self,
tx: Option<Tx>,
tx_bytes: Vec<u8>,
) -> Result<SimulateResponse, NymdError> {
) -> Result<SimulateResponse, NyxdError> {
let path = Some("/cosmos.tx.v1beta1.Service/Simulate".parse().unwrap());
let req = SimulateRequest {
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nyxd::error::NyxdError;
use cosmrs::proto::cosmos::base::query::v1beta1::{PageRequest, PageResponse};
use cosmrs::proto::cosmos::base::v1beta1::Coin as ProtoCoin;
use cosmrs::rpc::endpoint::broadcast;
@@ -11,13 +11,13 @@ use flate2::Compression;
use std::io::Write;
pub(crate) trait CheckResponse: Sized {
fn check_response(self) -> Result<Self, NymdError>;
fn check_response(self) -> Result<Self, NyxdError>;
}
impl CheckResponse for broadcast::tx_commit::Response {
fn check_response(self) -> Result<Self, NymdError> {
fn check_response(self) -> Result<Self, NyxdError> {
if self.check_tx.code.is_err() {
return Err(NymdError::BroadcastTxErrorCheckTx {
return Err(NyxdError::BroadcastTxErrorCheckTx {
hash: self.hash,
height: Some(self.height),
code: self.check_tx.code.value(),
@@ -26,7 +26,7 @@ impl CheckResponse for broadcast::tx_commit::Response {
}
if self.deliver_tx.code.is_err() {
return Err(NymdError::BroadcastTxErrorDeliverTx {
return Err(NyxdError::BroadcastTxErrorDeliverTx {
hash: self.hash,
height: Some(self.height),
code: self.deliver_tx.code.value(),
@@ -38,10 +38,10 @@ impl CheckResponse for broadcast::tx_commit::Response {
}
}
impl CheckResponse for crate::nymd::TxResponse {
fn check_response(self) -> Result<Self, NymdError> {
impl CheckResponse for crate::nyxd::TxResponse {
fn check_response(self) -> Result<Self, NyxdError> {
if self.tx_result.code.is_err() {
return Err(NymdError::BroadcastTxErrorDeliverTx {
return Err(NyxdError::BroadcastTxErrorDeliverTx {
hash: self.hash,
height: Some(self.height),
code: self.tx_result.code.value(),
@@ -53,13 +53,13 @@ impl CheckResponse for crate::nymd::TxResponse {
}
}
pub(crate) fn compress_wasm_code(code: &[u8]) -> Result<Vec<u8>, NymdError> {
pub(crate) fn compress_wasm_code(code: &[u8]) -> Result<Vec<u8>, NyxdError> {
// using compression level 9, same as cosmjs, that optimises for size
let mut encoder = GzEncoder::new(Vec::new(), Compression::best());
encoder
.write_all(code)
.map_err(NymdError::WasmCompressionError)?;
encoder.finish().map_err(NymdError::WasmCompressionError)
.map_err(NyxdError::WasmCompressionError)?;
encoder.finish().map_err(NyxdError::WasmCompressionError)
}
pub(crate) fn create_pagination(key: Vec<u8>) -> PageRequest {
@@ -84,11 +84,11 @@ pub(crate) fn next_page_key(pagination_info: Option<PageResponse>) -> Option<Vec
None
}
pub(crate) fn parse_proto_coin_vec(value: Vec<ProtoCoin>) -> Result<Vec<Coin>, NymdError> {
pub(crate) fn parse_proto_coin_vec(value: Vec<ProtoCoin>) -> Result<Vec<Coin>, NyxdError> {
value
.into_iter()
.map(|proto_coin| {
Coin::try_from(&proto_coin).map_err(|_| NymdError::MalformedCoin {
Coin::try_from(&proto_coin).map_err(|_| NyxdError::MalformedCoin {
coin_representation: format!("{:?}", proto_coin),
})
})
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nyxd::error::NyxdError;
use cosmrs::tendermint::abci;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
@@ -39,17 +39,17 @@ pub fn find_attribute<'a>(
}
// those two functions were separated so that the internal logic could actually be tested
fn parse_raw_str_logs(raw: &str) -> Result<Vec<Log>, NymdError> {
let logs: Vec<Log> = serde_json::from_str(raw).map_err(|_| NymdError::MalformedLogString)?;
fn parse_raw_str_logs(raw: &str) -> Result<Vec<Log>, NyxdError> {
let logs: Vec<Log> = serde_json::from_str(raw).map_err(|_| NyxdError::MalformedLogString)?;
if logs.len() != logs.iter().unique_by(|log| log.msg_index).count() {
// this check is only here because I don't yet fully understand raw log string generation and
// the fact the first entry does not seem to have `msg_index` defined on it.
return Err(NymdError::MalformedLogString);
return Err(NyxdError::MalformedLogString);
}
Ok(logs)
}
pub fn parse_raw_logs(raw: abci::Log) -> Result<Vec<Log>, NymdError> {
pub fn parse_raw_logs(raw: abci::Log) -> Result<Vec<Log>, NyxdError> {
parse_raw_str_logs(raw.as_ref())
}
@@ -1,9 +1,9 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nymd::wallet::DirectSecp256k1HdWallet;
use crate::nymd::GasPrice;
use crate::nyxd::error::NyxdError;
use crate::nyxd::wallet::DirectSecp256k1HdWallet;
use crate::nyxd::GasPrice;
use cosmrs::rpc::{Error as TendermintRpcError, HttpClient, HttpClientUrl};
use std::convert::TryInto;
@@ -13,7 +13,7 @@ pub mod logs;
pub mod signing_client;
pub mod types;
pub fn connect<U>(endpoint: U) -> Result<HttpClient, NymdError>
pub fn connect<U>(endpoint: U) -> Result<HttpClient, NyxdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
@@ -25,7 +25,7 @@ pub fn connect_with_signer<U: Clone>(
endpoint: U,
signer: DirectSecp256k1HdWallet,
gas_price: GasPrice,
) -> Result<signing_client::Client, NymdError>
) -> Result<signing_client::Client, NyxdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
@@ -1,14 +1,14 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::cosmwasm_client::client::CosmWasmClient;
use crate::nymd::cosmwasm_client::helpers::{compress_wasm_code, CheckResponse};
use crate::nymd::cosmwasm_client::logs::{self, parse_raw_logs};
use crate::nymd::cosmwasm_client::types::*;
use crate::nymd::error::NymdError;
use crate::nymd::fee::{Fee, DEFAULT_SIMULATED_GAS_MULTIPLIER};
use crate::nymd::wallet::DirectSecp256k1HdWallet;
use crate::nymd::{Coin, GasAdjustable, GasPrice, TxResponse};
use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
use crate::nyxd::cosmwasm_client::helpers::{compress_wasm_code, CheckResponse};
use crate::nyxd::cosmwasm_client::logs::{self, parse_raw_logs};
use crate::nyxd::cosmwasm_client::types::*;
use crate::nyxd::error::NyxdError;
use crate::nyxd::fee::{Fee, DEFAULT_SIMULATED_GAS_MULTIPLIER};
use crate::nyxd::wallet::DirectSecp256k1HdWallet;
use crate::nyxd::{Coin, GasAdjustable, GasPrice, TxResponse};
use async_trait::async_trait;
use cosmrs::bank::MsgSend;
use cosmrs::distribution::MsgWithdrawDelegatorReward;
@@ -74,7 +74,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
signer_address: &AccountId,
messages: Vec<Any>,
memo: impl Into<String> + Send + 'static,
) -> Result<SimulateResponse, NymdError> {
) -> Result<SimulateResponse, NyxdError> {
let public_key = self.signer_public_key(signer_address);
let sequence_response = self.get_sequence(signer_address).await?;
@@ -102,7 +102,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
wasm_code: Vec<u8>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<UploadResult, NymdError> {
) -> Result<UploadResult, NyxdError> {
let compressed = compress_wasm_code(&wasm_code)?;
let compressed_size = compressed.len();
let compressed_checksum = Sha256::digest(&compressed).to_vec();
@@ -115,7 +115,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
instantiate_permission: Default::default(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgStoreCode".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgStoreCode".to_owned()))?;
let tx_res = self
.sign_and_broadcast(sender_address, vec![upload_msg], fee, memo)
@@ -161,7 +161,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
fee: Fee,
memo: impl Into<String> + Send + 'static,
mut options: Option<InstantiateOptions>,
) -> Result<InstantiateResult, NymdError>
) -> Result<InstantiateResult, NyxdError>
where
M: ?Sized + Serialize + Sync,
{
@@ -176,7 +176,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
funds: options.map(|options| options.funds).unwrap_or_default(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgInstantiateContract".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgInstantiateContract".to_owned()))?;
let tx_res = self
.sign_and_broadcast(sender_address, vec![init_msg], fee, memo)
@@ -211,14 +211,14 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
new_admin: &AccountId,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<ChangeAdminResult, NymdError> {
) -> Result<ChangeAdminResult, NyxdError> {
let change_admin_msg = cosmwasm::MsgUpdateAdmin {
sender: sender_address.clone(),
new_admin: new_admin.clone(),
contract: contract_address.clone(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgUpdateAdmin".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgUpdateAdmin".to_owned()))?;
let tx_res = self
.sign_and_broadcast(sender_address, vec![change_admin_msg], fee, memo)
@@ -240,13 +240,13 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
contract_address: &AccountId,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<ChangeAdminResult, NymdError> {
) -> Result<ChangeAdminResult, NyxdError> {
let change_admin_msg = cosmwasm::MsgClearAdmin {
sender: sender_address.clone(),
contract: contract_address.clone(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgClearAdmin".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgClearAdmin".to_owned()))?;
let tx_res = self
.sign_and_broadcast(sender_address, vec![change_admin_msg], fee, memo)
@@ -270,7 +270,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
fee: Fee,
msg: &M,
memo: impl Into<String> + Send + 'static,
) -> Result<MigrateResult, NymdError>
) -> Result<MigrateResult, NyxdError>
where
M: ?Sized + Serialize + Sync,
{
@@ -281,7 +281,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
msg: serde_json::to_vec(msg)?,
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgMigrateContract".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgMigrateContract".to_owned()))?;
let tx_res = self
.sign_and_broadcast(sender_address, vec![migrate_msg], fee, memo)
@@ -305,7 +305,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
fee: Fee,
memo: impl Into<String> + Send + 'static,
funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError>
) -> Result<ExecuteResult, NyxdError>
where
M: ?Sized + Serialize + Sync,
{
@@ -316,7 +316,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
funds: funds.into_iter().map(Into::into).collect(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgExecuteContract".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgExecuteContract".to_owned()))?;
let tx_res = self
.sign_and_broadcast(sender_address, vec![execute_msg], fee, memo)
@@ -340,7 +340,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
msgs: I,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<ExecuteResult, NymdError>
) -> Result<ExecuteResult, NyxdError>
where
I: IntoIterator<Item = (M, Vec<Coin>)> + Send,
M: Serialize,
@@ -355,7 +355,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
funds: funds.into_iter().map(Into::into).collect(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgExecuteContract".to_owned()))
.map_err(|_| NyxdError::SerializationError("MsgExecuteContract".to_owned()))
})
.collect::<Result<_, _>>()?;
@@ -381,14 +381,14 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
amount: Vec<Coin>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let send_msg = MsgSend {
from_address: sender_address.clone(),
to_address: recipient_address.clone(),
amount: amount.into_iter().map(Into::into).collect(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgSend".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgSend".to_owned()))?;
self.sign_and_broadcast(sender_address, vec![send_msg], fee, memo)
.await?
@@ -401,7 +401,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
msgs: I,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError>
) -> Result<TxResponse, NyxdError>
where
I: IntoIterator<Item = (AccountId, Vec<Coin>)> + Send,
{
@@ -414,7 +414,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
amount: amount.into_iter().map(Into::into).collect(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgExecuteContract".to_owned()))
.map_err(|_| NyxdError::SerializationError("MsgExecuteContract".to_owned()))
})
.collect::<Result<_, _>>()?;
@@ -433,20 +433,20 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
allowed_messages: Vec<String>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let basic_allowance = BasicAllowance {
spend_limit: spend_limit.into_iter().map(Into::into).collect(),
expiration,
}
.to_any()
.map_err(|_| NymdError::SerializationError("BasicAllowance".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("BasicAllowance".to_owned()))?;
let allowed_msg_allowance = AllowedMsgAllowance {
allowance: Some(basic_allowance),
allowed_messages,
}
.to_any()
.map_err(|_| NymdError::SerializationError("AllowedMsgAllowance".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("AllowedMsgAllowance".to_owned()))?;
let grant_allowance_msg = MsgGrantAllowance {
granter: granter.to_owned(),
@@ -454,7 +454,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
allowance: Some(allowed_msg_allowance),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgGrantAllowance".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgGrantAllowance".to_owned()))?;
self.sign_and_broadcast(granter, vec![grant_allowance_msg], fee, memo)
.await?
@@ -467,13 +467,13 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
grantee: &AccountId,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let revoke_allowance_msg = MsgRevokeAllowance {
granter: granter.to_owned(),
grantee: grantee.to_owned(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgRevokeAllowance".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgRevokeAllowance".to_owned()))?;
self.sign_and_broadcast(granter, vec![revoke_allowance_msg], fee, memo)
.await?
@@ -487,14 +487,14 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
amount: Coin,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let delegate_msg = MsgDelegate {
delegator_address: delegator_address.to_owned(),
validator_address: validator_address.to_owned(),
amount: amount.into(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgDelegate".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgDelegate".to_owned()))?;
self.sign_and_broadcast(delegator_address, vec![delegate_msg], fee, memo)
.await?
@@ -508,14 +508,14 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
amount: Coin,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let undelegate_msg = MsgUndelegate {
delegator_address: delegator_address.to_owned(),
validator_address: validator_address.to_owned(),
amount: amount.into(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgUndelegate".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgUndelegate".to_owned()))?;
self.sign_and_broadcast(delegator_address, vec![undelegate_msg], fee, memo)
.await?
@@ -528,13 +528,13 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
validator_address: &AccountId,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let withdraw_msg = MsgWithdrawDelegatorReward {
delegator_address: delegator_address.to_owned(),
validator_address: validator_address.to_owned(),
}
.to_any()
.map_err(|_| NymdError::SerializationError("MsgWithdrawDelegatorReward".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("MsgWithdrawDelegatorReward".to_owned()))?;
self.sign_and_broadcast(delegator_address, vec![withdraw_msg], fee, memo)
.await?
@@ -549,7 +549,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: &[Any],
fee: Fee,
memo: &String,
) -> Result<tx::Fee, NymdError> {
) -> Result<tx::Fee, NyxdError> {
let auto_fee = |multiplier: Option<f32>| async move {
debug!("Trying to simulate gas costs...");
// from what I've seen in manual testing, gas estimation does not exist if transaction
@@ -558,7 +558,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
.simulate(signer_address, messages.to_vec(), memo.clone())
.await?
.gas_info
.ok_or(NymdError::GasEstimationFailure)?
.ok_or(NyxdError::GasEstimationFailure)?
.gas_used;
let multiplier = multiplier.unwrap_or(DEFAULT_SIMULATED_GAS_MULTIPLIER);
@@ -569,7 +569,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
debug!("Final gas limit used: {}", gas);
let fee = self.gas_price() * gas;
Ok::<tx::Fee, NymdError>(tx::Fee::from_amount_and_gas(fee, gas))
Ok::<tx::Fee, NyxdError>(tx::Fee::from_amount_and_gas(fee, gas))
};
let fee = match fee {
Fee::Manual(fee) => fee,
@@ -592,7 +592,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<broadcast::tx_async::Response, NymdError> {
) -> Result<broadcast::tx_async::Response, NyxdError> {
let memo = memo.into();
let fee = self
.determine_transaction_fee(signer_address, &messages, fee, &memo)
@@ -600,7 +600,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
let tx_raw = self.sign(signer_address, messages, fee, memo).await?;
let tx_bytes = tx_raw
.to_bytes()
.map_err(|_| NymdError::SerializationError("Tx".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("Tx".to_owned()))?;
CosmWasmClient::broadcast_tx_async(self, tx_bytes.into()).await
}
@@ -612,7 +612,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<broadcast::tx_sync::Response, NymdError> {
) -> Result<broadcast::tx_sync::Response, NyxdError> {
let memo = memo.into();
let fee = self
.determine_transaction_fee(signer_address, &messages, fee, &memo)
@@ -620,7 +620,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
let tx_raw = self.sign(signer_address, messages, fee, memo).await?;
let tx_bytes = tx_raw
.to_bytes()
.map_err(|_| NymdError::SerializationError("Tx".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("Tx".to_owned()))?;
CosmWasmClient::broadcast_tx_sync(self, tx_bytes.into()).await
}
@@ -632,7 +632,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<broadcast::tx_commit::Response, NymdError> {
) -> Result<broadcast::tx_commit::Response, NyxdError> {
let memo = memo.into();
let fee = self
.determine_transaction_fee(signer_address, &messages, fee, &memo)
@@ -641,7 +641,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
let tx_raw = self.sign(signer_address, messages, fee, memo).await?;
let tx_bytes = tx_raw
.to_bytes()
.map_err(|_| NymdError::SerializationError("Tx".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("Tx".to_owned()))?;
CosmWasmClient::broadcast_tx_commit(self, tx_bytes.into()).await
}
@@ -653,7 +653,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>,
fee: Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<TxResponse, NymdError> {
) -> Result<TxResponse, NyxdError> {
let memo = memo.into();
let fee = self
.determine_transaction_fee(signer_address, &messages, fee, &memo)
@@ -662,7 +662,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
let tx_raw = self.sign(signer_address, messages, fee, memo).await?;
let tx_bytes = tx_raw
.to_bytes()
.map_err(|_| NymdError::SerializationError("Tx".to_owned()))?;
.map_err(|_| NyxdError::SerializationError("Tx".to_owned()))?;
self.broadcast_tx(tx_bytes.into()).await
}
@@ -674,12 +674,12 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
fee: tx::Fee,
memo: impl Into<String> + Send + 'static,
signer_data: SignerData,
) -> Result<tx::Raw, NymdError> {
) -> Result<tx::Raw, NyxdError> {
let signer_accounts = self.signer().try_derive_accounts()?;
let account_from_signer = signer_accounts
.iter()
.find(|account| &account.address == signer_address)
.ok_or_else(|| NymdError::SigningAccountNotFound(signer_address.clone()))?;
.ok_or_else(|| NyxdError::SigningAccountNotFound(signer_address.clone()))?;
// TODO: WTF HOW IS TIMEOUT_HEIGHT SUPPOSED TO GET DETERMINED?
// IT DOESNT EXIST IN COSMJS!!
@@ -691,7 +691,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
SignerInfo::single_direct(Some(account_from_signer.public_key), signer_data.sequence);
let auth_info = signer_info.auth_info(fee);
// ideally I'd prefer to have the entire error put into the NymdError::SigningFailure
// ideally I'd prefer to have the entire error put into the NyxdError::SigningFailure
// but I'm super hesitant to trying to downcast the eyre::Report to cosmrs::error::Error
let sign_doc = SignDoc::new(
&tx_body,
@@ -699,7 +699,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
&signer_data.chain_id,
signer_data.account_number,
)
.map_err(|_| NymdError::SigningFailure)?;
.map_err(|_| NyxdError::SigningFailure)?;
self.signer()
.sign_direct_with_account(account_from_signer, sign_doc)
@@ -711,7 +711,7 @@ pub trait SigningCosmWasmClient: CosmWasmClient {
messages: Vec<Any>,
fee: tx::Fee,
memo: impl Into<String> + Send + 'static,
) -> Result<tx::Raw, NymdError> {
) -> Result<tx::Raw, NyxdError> {
// TODO: Future optimisation: rather than grabbing current account_number and sequence
// on every sign request -> just keep them cached on the struct and increment as required
let sequence_response = self.get_sequence(signer_address).await?;
@@ -742,7 +742,7 @@ impl Client {
endpoint: U,
signer: DirectSecp256k1HdWallet,
gas_price: GasPrice,
) -> Result<Self, NymdError>
) -> Result<Self, NyxdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
@@ -3,9 +3,9 @@
// TODO: There's a significant argument to pull those out of the package and make a PR on https://github.com/cosmos/cosmos-rust/
use crate::nymd::cosmwasm_client::helpers::parse_proto_coin_vec;
use crate::nymd::cosmwasm_client::logs::Log;
use crate::nymd::error::NymdError;
use crate::nyxd::cosmwasm_client::helpers::parse_proto_coin_vec;
use crate::nyxd::cosmwasm_client::logs::Log;
use crate::nyxd::error::NyxdError;
use cosmrs::crypto::PublicKey;
use cosmrs::proto::cosmos::auth::v1beta1::{
BaseAccount as ProtoBaseAccount, ModuleAccount as ProtoModuleAccount,
@@ -57,19 +57,19 @@ pub struct BaseAccount {
}
impl TryFrom<ProtoBaseAccount> for BaseAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoBaseAccount) -> Result<Self, Self::Error> {
let address: AccountId = value
.address
.parse()
.map_err(|_| NymdError::MalformedAccountAddress(value.address.clone()))?;
.map_err(|_| NyxdError::MalformedAccountAddress(value.address.clone()))?;
let pubkey = value
.pub_key
.map(PublicKey::try_from)
.transpose()
.map_err(|_| NymdError::InvalidPublicKey(address.clone()))?;
.map_err(|_| NyxdError::InvalidPublicKey(address.clone()))?;
Ok(BaseAccount {
address,
@@ -89,7 +89,7 @@ pub struct ModuleAccount {
}
impl TryFrom<ProtoModuleAccount> for ModuleAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoModuleAccount) -> Result<Self, Self::Error> {
let base_account = value.base_account.map(TryFrom::try_from).transpose()?;
@@ -114,7 +114,7 @@ pub struct BaseVestingAccount {
}
impl TryFrom<ProtoBaseVestingAccount> for BaseVestingAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoBaseVestingAccount) -> Result<Self, Self::Error> {
let base_account = value.base_account.map(TryFrom::try_from).transpose()?;
@@ -142,7 +142,7 @@ pub struct ContinuousVestingAccount {
}
impl TryFrom<ProtoContinuousVestingAccount> for ContinuousVestingAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoContinuousVestingAccount) -> Result<Self, Self::Error> {
let base_vesting_account = value
@@ -166,7 +166,7 @@ pub struct DelayedVestingAccount {
}
impl TryFrom<ProtoDelayedVestingAccount> for DelayedVestingAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoDelayedVestingAccount) -> Result<Self, Self::Error> {
let base_vesting_account = value
@@ -188,7 +188,7 @@ pub struct Period {
}
impl TryFrom<ProtoPeriod> for Period {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoPeriod) -> Result<Self, Self::Error> {
Ok(Period {
@@ -208,7 +208,7 @@ pub struct PeriodicVestingAccount {
}
impl TryFrom<ProtoPeriodicVestingAccount> for PeriodicVestingAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoPeriodicVestingAccount) -> Result<Self, Self::Error> {
let base_vesting_account = value
@@ -239,7 +239,7 @@ pub struct PermanentLockedAccount {
}
impl TryFrom<ProtoPermanentLockedAccount> for PermanentLockedAccount {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoPermanentLockedAccount) -> Result<Self, Self::Error> {
let base_vesting_account = value
@@ -265,43 +265,43 @@ pub enum Account {
}
impl Account {
pub fn try_get_base_account(&self) -> Result<&BaseAccount, NymdError> {
pub fn try_get_base_account(&self) -> Result<&BaseAccount, NyxdError> {
match self {
Account::Base(acc) => Ok(acc),
Account::Module(acc) => acc
.base_account
.as_ref()
.ok_or(NymdError::NoBaseAccountInformationAvailable),
.ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::BaseVesting(acc) => acc
.base_account
.as_ref()
.ok_or(NymdError::NoBaseAccountInformationAvailable),
.ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::ContinuousVesting(acc) => acc
.base_vesting_account
.as_ref()
.and_then(|vesting_acc| vesting_acc.base_account.as_ref())
.ok_or(NymdError::NoBaseAccountInformationAvailable),
.ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::DelayedVesting(acc) => acc
.base_vesting_account
.as_ref()
.and_then(|vesting_acc| vesting_acc.base_account.as_ref())
.ok_or(NymdError::NoBaseAccountInformationAvailable),
.ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::PeriodicVesting(acc) => acc
.base_vesting_account
.as_ref()
.and_then(|vesting_acc| vesting_acc.base_account.as_ref())
.ok_or(NymdError::NoBaseAccountInformationAvailable),
.ok_or(NyxdError::NoBaseAccountInformationAvailable),
Account::PermanentLockedVesting(acc) => acc
.base_vesting_account
.as_ref()
.and_then(|vesting_acc| vesting_acc.base_account.as_ref())
.ok_or(NymdError::NoBaseAccountInformationAvailable),
.ok_or(NyxdError::NoBaseAccountInformationAvailable),
}
}
}
impl TryFrom<Any> for Account {
type Error = NymdError;
type Error = NyxdError;
fn try_from(raw_account: Any) -> Result<Self, Self::Error> {
match raw_account.type_url.as_ref() {
@@ -328,7 +328,7 @@ impl TryFrom<Any> for Account {
ProtoPermanentLockedAccount::decode(raw_account.value.as_ref())?.try_into()?,
))
}
_ => Err(NymdError::UnsupportedAccountType {
_ => Err(NyxdError::UnsupportedAccountType {
type_url: raw_account.type_url,
}),
}
@@ -347,7 +347,7 @@ pub struct Code {
}
impl TryFrom<CodeInfoResponse> for Code {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: CodeInfoResponse) -> Result<Self, Self::Error> {
let CodeInfoResponse {
@@ -358,7 +358,7 @@ impl TryFrom<CodeInfoResponse> for Code {
let creator = creator
.parse()
.map_err(|_| NymdError::MalformedAccountAddress(creator))?;
.map_err(|_| NyxdError::MalformedAccountAddress(creator))?;
Ok(Code {
code_id,
@@ -391,7 +391,7 @@ pub(crate) struct ContractInfo {
}
impl TryFrom<ProtoContractInfo> for ContractInfo {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoContractInfo) -> Result<Self, Self::Error> {
let ProtoContractInfo {
@@ -408,7 +408,7 @@ impl TryFrom<ProtoContractInfo> for ContractInfo {
Some(
admin
.parse()
.map_err(|_| NymdError::MalformedAccountAddress(admin))?,
.map_err(|_| NyxdError::MalformedAccountAddress(admin))?,
)
};
@@ -416,7 +416,7 @@ impl TryFrom<ProtoContractInfo> for ContractInfo {
code_id,
creator: creator
.parse()
.map_err(|_| NymdError::MalformedAccountAddress(creator))?,
.map_err(|_| NyxdError::MalformedAccountAddress(creator))?,
admin,
label,
})
@@ -466,14 +466,14 @@ pub struct ContractCodeHistoryEntry {
}
impl TryFrom<ProtoContractCodeHistoryEntry> for ContractCodeHistoryEntry {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoContractCodeHistoryEntry) -> Result<Self, Self::Error> {
let operation = match ContractCodeHistoryOperationType::from_i32(value.operation)
.ok_or(NymdError::InvalidContractHistoryOperation)?
.ok_or(NyxdError::InvalidContractHistoryOperation)?
{
ContractCodeHistoryOperationType::Unspecified => {
return Err(NymdError::InvalidContractHistoryOperation)
return Err(NyxdError::InvalidContractHistoryOperation)
}
ContractCodeHistoryOperationType::Init => ContractCodeHistoryEntryOperation::Init,
ContractCodeHistoryOperationType::Genesis => ContractCodeHistoryEntryOperation::Genesis,
@@ -484,7 +484,7 @@ impl TryFrom<ProtoContractCodeHistoryEntry> for ContractCodeHistoryEntry {
operation,
code_id: value.code_id,
msg_json: String::from_utf8(value.msg)
.map_err(|_| NymdError::DeserializationError("Contract history msg".to_owned()))?,
.map_err(|_| NyxdError::DeserializationError("Contract history msg".to_owned()))?,
})
}
}
@@ -532,7 +532,7 @@ pub struct AbciResult {
}
impl TryFrom<ProtoAbciResult> for AbciResult {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoAbciResult) -> Result<Self, Self::Error> {
let mut events = Vec::with_capacity(value.events.len());
@@ -543,9 +543,9 @@ impl TryFrom<ProtoAbciResult> for AbciResult {
let mut attributes = Vec::with_capacity(proto_event.attributes.len());
for proto_attribute in proto_event.attributes.into_iter() {
let stringified_ked = String::from_utf8(proto_attribute.key)
.map_err(|_| NymdError::DeserializationError("EventAttributeKey".to_owned()))?;
.map_err(|_| NyxdError::DeserializationError("EventAttributeKey".to_owned()))?;
let stringified_value = String::from_utf8(proto_attribute.value)
.map_err(|_| NymdError::DeserializationError("EventAttributeKey".to_owned()))?;
.map_err(|_| NyxdError::DeserializationError("EventAttributeKey".to_owned()))?;
attributes.push(abci::tag::Tag {
key: stringified_ked.parse().unwrap(),
@@ -574,7 +574,7 @@ pub struct SimulateResponse {
}
impl TryFrom<ProtoSimulateResponse> for SimulateResponse {
type Error = NymdError;
type Error = NyxdError;
fn try_from(value: ProtoSimulateResponse) -> Result<Self, Self::Error> {
Ok(SimulateResponse {
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::cosmwasm_client::types::ContractCodeId;
use crate::nyxd::cosmwasm_client::types::ContractCodeId;
use cosmrs::{
bip32,
rpc::endpoint::abci_query::AbciQuery,
@@ -21,7 +21,7 @@ pub use cosmrs::rpc::{
};
#[derive(Debug, Error)]
pub enum NymdError {
pub enum NyxdError {
#[error("No contract address is available to perform the call")]
NoContractAddressAvailable,
@@ -148,10 +148,10 @@ pub enum NymdError {
// The purpose of parsing the abci query result is that we want to generate the `pretty_log` if
// possible.
pub fn parse_abci_query_result(query_result: AbciQuery) -> Result<AbciQuery, NymdError> {
pub fn parse_abci_query_result(query_result: AbciQuery) -> Result<AbciQuery, NyxdError> {
match query_result.code {
AbciCode::Ok => Ok(query_result),
AbciCode::Err(code) => Err(NymdError::AbciError {
AbciCode::Err(code) => Err(NyxdError::AbciError {
code,
log: query_result.log.clone(),
pretty_log: try_parse_abci_log(&query_result.log),
@@ -172,10 +172,10 @@ fn try_parse_abci_log(log: &abci::Log) -> Option<String> {
}
}
impl NymdError {
impl NyxdError {
pub fn is_tendermint_response_timeout(&self) -> bool {
match &self {
NymdError::TendermintError(TendermintRpcError(
NyxdError::TendermintError(TendermintRpcError(
TendermintRpcErrorDetail::Response(err),
_,
)) => {
@@ -202,7 +202,7 @@ impl NymdError {
pub fn is_tendermint_response_duplicate(&self) -> bool {
match &self {
NymdError::TendermintError(TendermintRpcError(
NyxdError::TendermintError(TendermintRpcError(
TendermintRpcErrorDetail::Response(err),
_,
)) => {
@@ -1,7 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nyxd::error::NyxdError;
use config::defaults;
use cosmrs::tx::Gas;
use cosmrs::Coin;
@@ -55,7 +55,7 @@ impl<'a> Mul<Gas> for &'a GasPrice {
}
impl FromStr for GasPrice {
type Err = NymdError;
type Err = NyxdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let possible_amount = s
@@ -65,7 +65,7 @@ impl FromStr for GasPrice {
let amount_len = possible_amount.len();
let amount = possible_amount
.parse()
.map_err(|_| NymdError::MalformedGasPrice)?;
.map_err(|_| NyxdError::MalformedGasPrice)?;
let possible_denom = s.chars().skip(amount_len).collect::<String>();
let denom = possible_denom.trim().to_string();
@@ -74,7 +74,7 @@ impl FromStr for GasPrice {
}
impl GasPrice {
pub fn new_with_default_price(denom: &str) -> Result<Self, NymdError> {
pub fn new_with_default_price(denom: &str) -> Result<Self, NyxdError> {
format!("{}{}", defaults::GAS_PRICE_AMOUNT, denom).parse()
}
}
@@ -1,8 +1,8 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::Coin;
use crate::nymd::Gas;
use crate::nyxd::Coin;
use crate::nyxd::Gas;
use cosmrs::{tx, AccountId};
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
@@ -1,14 +1,14 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::cosmwasm_client::signing_client;
use crate::nymd::cosmwasm_client::types::{
use crate::nyxd::cosmwasm_client::signing_client;
use crate::nyxd::cosmwasm_client::types::{
Account, ChangeAdminResult, ContractCodeId, ExecuteResult, InstantiateOptions,
InstantiateResult, MigrateResult, SequenceResponse, SimulateResponse, UploadResult,
};
use crate::nymd::error::NymdError;
use crate::nymd::fee::DEFAULT_SIMULATED_GAS_MULTIPLIER;
use crate::nymd::wallet::DirectSecp256k1HdWallet;
use crate::nyxd::error::NyxdError;
use crate::nyxd::fee::DEFAULT_SIMULATED_GAS_MULTIPLIER;
use crate::nyxd::wallet::DirectSecp256k1HdWallet;
use cosmrs::cosmwasm;
use cosmrs::rpc::endpoint::block::Response as BlockResponse;
use cosmrs::rpc::query::Query;
@@ -16,20 +16,21 @@ use cosmrs::rpc::Error as TendermintRpcError;
use cosmrs::rpc::HttpClientUrl;
use cosmrs::tx::Msg;
use execute::execute;
use log::debug;
use network_defaults::{ChainDetails, NymNetworkDetails};
use serde::{Deserialize, Serialize};
use std::convert::TryInto;
use std::time::SystemTime;
use vesting_contract_common::ExecuteMsg as VestingExecuteMsg;
pub use crate::nymd::cosmwasm_client::client::CosmWasmClient;
pub use crate::nymd::cosmwasm_client::signing_client::SigningCosmWasmClient;
pub use crate::nymd::fee::Fee;
pub use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
pub use crate::nyxd::fee::Fee;
pub use coin::Coin;
pub use cosmrs::bank::MsgSend;
pub use cosmrs::rpc::endpoint::tx::Response as TxResponse;
pub use cosmrs::rpc::endpoint::validators::Response as ValidatorResponse;
pub use cosmrs::rpc::HttpClient as QueryNymdClient;
pub use cosmrs::rpc::HttpClient as QueryNyxdClient;
pub use cosmrs::rpc::Paging;
pub use cosmrs::tendermint::abci::responses::{DeliverTx, Event};
pub use cosmrs::tendermint::abci::tag::Tag;
@@ -43,7 +44,7 @@ pub use cosmrs::{bip32, AccountId, Decimal, Denom};
pub use cosmwasm_std::Coin as CosmWasmCoin;
pub use fee::{gas_price::GasPrice, GasAdjustable, GasAdjustment};
use mixnet_contract_common::MixId;
pub use signing_client::Client as SigningNymdClient;
pub use signing_client::Client as SigningNyxdClient;
pub use traits::{VestingQueryClient, VestingSigningClient};
use vesting_contract_common::PledgeCap;
@@ -74,13 +75,16 @@ impl Config {
fn parse_optional_account(
raw: Option<&String>,
expected_prefix: &str,
) -> Result<Option<AccountId>, NymdError> {
) -> Result<Option<AccountId>, NyxdError> {
if let Some(address) = raw {
debug!("Raw address:{:?}", raw);
debug!("Expected prefix:{:?}", expected_prefix);
let parsed: AccountId = address
.parse()
.map_err(|_| NymdError::MalformedAccountAddress(address.clone()))?;
.map_err(|_| NyxdError::MalformedAccountAddress(address.clone()))?;
debug!("Parsed prefix:{:?}", parsed);
if parsed.prefix() != expected_prefix {
Err(NymdError::UnexpectedBech32Prefix {
Err(NyxdError::UnexpectedBech32Prefix {
got: parsed.prefix().into(),
expected: expected_prefix.into(),
})
@@ -92,7 +96,7 @@ impl Config {
}
}
pub fn try_from_nym_network_details(details: &NymNetworkDetails) -> Result<Self, NymdError> {
pub fn try_from_nym_network_details(details: &NymNetworkDetails) -> Result<Self, NyxdError> {
let prefix = &details.chain_details.bech32_account_prefix;
Ok(Config {
chain_details: details.chain_details.clone(),
@@ -128,20 +132,20 @@ impl Config {
}
#[derive(Debug)]
pub struct NymdClient<C> {
pub struct NyxdClient<C> {
client: C,
config: Config,
client_address: Option<Vec<AccountId>>,
simulated_gas_multiplier: f32,
}
impl NymdClient<QueryNymdClient> {
pub fn connect<U>(config: Config, endpoint: U) -> Result<NymdClient<QueryNymdClient>, NymdError>
impl NyxdClient<QueryNyxdClient> {
pub fn connect<U>(config: Config, endpoint: U) -> Result<NyxdClient<QueryNyxdClient>, NyxdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
Ok(NymdClient {
client: QueryNymdClient::new(endpoint)?,
Ok(NyxdClient {
client: QueryNyxdClient::new(endpoint)?,
config,
client_address: None,
simulated_gas_multiplier: DEFAULT_SIMULATED_GAS_MULTIPLIER,
@@ -149,7 +153,7 @@ impl NymdClient<QueryNymdClient> {
}
}
impl NymdClient<SigningNymdClient> {
impl NyxdClient<SigningNyxdClient> {
// maybe the wallet could be made into a generic, but for now, let's just have this one implementation
pub fn connect_with_signer<U: Clone>(
config: Config,
@@ -157,7 +161,7 @@ impl NymdClient<SigningNymdClient> {
endpoint: U,
signer: DirectSecp256k1HdWallet,
gas_price: Option<GasPrice>,
) -> Result<NymdClient<SigningNymdClient>, NymdError>
) -> Result<NyxdClient<SigningNyxdClient>, NyxdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
@@ -169,8 +173,8 @@ impl NymdClient<SigningNymdClient> {
.collect();
let gas_price = gas_price.unwrap_or(GasPrice::new_with_default_price(&denom)?);
Ok(NymdClient {
client: SigningNymdClient::connect_with_signer(endpoint, signer, gas_price)?,
Ok(NyxdClient {
client: SigningNyxdClient::connect_with_signer(endpoint, signer, gas_price)?,
config,
client_address: Some(client_address),
simulated_gas_multiplier: DEFAULT_SIMULATED_GAS_MULTIPLIER,
@@ -182,7 +186,7 @@ impl NymdClient<SigningNymdClient> {
endpoint: U,
mnemonic: bip39::Mnemonic,
gas_price: Option<GasPrice>,
) -> Result<NymdClient<SigningNymdClient>, NymdError>
) -> Result<NyxdClient<SigningNyxdClient>, NyxdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
@@ -196,8 +200,8 @@ impl NymdClient<SigningNymdClient> {
.collect();
let gas_price = gas_price.unwrap_or(GasPrice::new_with_default_price(denom)?);
Ok(NymdClient {
client: SigningNymdClient::connect_with_signer(endpoint, wallet, gas_price)?,
Ok(NyxdClient {
client: SigningNyxdClient::connect_with_signer(endpoint, wallet, gas_price)?,
config,
client_address: Some(client_address),
simulated_gas_multiplier: DEFAULT_SIMULATED_GAS_MULTIPLIER,
@@ -205,7 +209,7 @@ impl NymdClient<SigningNymdClient> {
}
}
impl<C> NymdClient<C> {
impl<C> NyxdClient<C> {
pub fn current_config(&self) -> &Config {
&self.config
}
@@ -234,7 +238,7 @@ impl<C> NymdClient<C> {
self.config.multisig_contract_address = Some(address);
}
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it)
@@ -242,7 +246,7 @@ impl<C> NymdClient<C> {
self.config.mixnet_contract_address.as_ref().unwrap()
}
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it)
@@ -250,7 +254,7 @@ impl<C> NymdClient<C> {
self.config.vesting_contract_address.as_ref().unwrap()
}
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it)
@@ -261,7 +265,7 @@ impl<C> NymdClient<C> {
.unwrap()
}
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it)
@@ -272,7 +276,7 @@ impl<C> NymdClient<C> {
.unwrap()
}
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it)
@@ -280,7 +284,7 @@ impl<C> NymdClient<C> {
self.config.multisig_contract_address.as_ref().unwrap()
}
// TODO: this should get changed into Result<&AccountId, NymdError> (or Option<&AccountId> in future commits
// TODO: this should get changed into Result<&AccountId, NyxdError> (or Option<&AccountId> in future commits
// note: what unwrap is doing here is just moving a failure that would have normally
// occurred in `connect` when attempting to parse an empty address,
// so it's not introducing new source of failure (just moves it)
@@ -296,7 +300,7 @@ impl<C> NymdClient<C> {
&self,
contract: &AccountId,
query_msg: &M,
) -> Result<T, NymdError>
) -> Result<T, NyxdError>
where
C: CosmWasmClient + Sync,
M: ?Sized + Serialize + Sync,
@@ -309,7 +313,7 @@ impl<C> NymdClient<C> {
&self,
contract: &AccountId,
query_data: Vec<u8>,
) -> Result<Vec<u8>, NymdError>
) -> Result<Vec<u8>, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -321,7 +325,7 @@ impl<C> NymdClient<C> {
contract_address: &AccountId,
msg: &M,
funds: Vec<Coin>,
) -> Result<cosmwasm::MsgExecuteContract, NymdError>
) -> Result<cosmwasm::MsgExecuteContract, NyxdError>
where
C: SigningCosmWasmClient,
M: ?Sized + Serialize,
@@ -366,7 +370,7 @@ impl<C> NymdClient<C> {
// CHAIN QUERIES
pub async fn account_sequence(&self) -> Result<SequenceResponse, NymdError>
pub async fn account_sequence(&self) -> Result<SequenceResponse, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -376,7 +380,7 @@ impl<C> NymdClient<C> {
pub async fn get_account_details(
&self,
address: &AccountId,
) -> Result<Option<Account>, NymdError>
) -> Result<Option<Account>, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -386,7 +390,7 @@ impl<C> NymdClient<C> {
pub async fn get_account_public_key(
&self,
address: &AccountId,
) -> Result<Option<cosmrs::crypto::PublicKey>, NymdError>
) -> Result<Option<cosmrs::crypto::PublicKey>, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -398,7 +402,7 @@ impl<C> NymdClient<C> {
Ok(None)
}
pub async fn get_current_block_timestamp(&self) -> Result<TendermintTime, NymdError>
pub async fn get_current_block_timestamp(&self) -> Result<TendermintTime, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -408,21 +412,21 @@ impl<C> NymdClient<C> {
pub async fn get_block_timestamp(
&self,
height: Option<u32>,
) -> Result<TendermintTime, NymdError>
) -> Result<TendermintTime, NyxdError>
where
C: CosmWasmClient + Sync,
{
Ok(self.client.get_block(height).await?.block.header.time)
}
pub async fn get_block(&self, height: Option<u32>) -> Result<BlockResponse, NymdError>
pub async fn get_block(&self, height: Option<u32>) -> Result<BlockResponse, NyxdError>
where
C: CosmWasmClient + Sync,
{
self.client.get_block(height).await
}
pub async fn get_current_block_height(&self) -> Result<Height, NymdError>
pub async fn get_current_block_height(&self) -> Result<Height, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -434,7 +438,7 @@ impl<C> NymdClient<C> {
/// # Arguments
///
/// * `height`: height of the block for which we want to obtain the hash.
pub async fn get_block_hash(&self, height: u32) -> Result<hash::Hash, NymdError>
pub async fn get_block_hash(&self, height: u32) -> Result<hash::Hash, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -448,7 +452,7 @@ impl<C> NymdClient<C> {
&self,
height: u64,
paging: Paging,
) -> Result<ValidatorResponse, NymdError>
) -> Result<ValidatorResponse, NyxdError>
where
C: CosmWasmClient + Sync,
{
@@ -459,42 +463,42 @@ impl<C> NymdClient<C> {
&self,
address: &AccountId,
denom: String,
) -> Result<Option<Coin>, NymdError>
) -> Result<Option<Coin>, NyxdError>
where
C: CosmWasmClient + Sync,
{
self.client.get_balance(address, denom).await
}
pub async fn get_all_balances(&self, address: &AccountId) -> Result<Vec<Coin>, NymdError>
pub async fn get_all_balances(&self, address: &AccountId) -> Result<Vec<Coin>, NyxdError>
where
C: CosmWasmClient + Sync,
{
self.client.get_all_balances(address).await
}
pub async fn get_tx(&self, id: tx::Hash) -> Result<TxResponse, NymdError>
pub async fn get_tx(&self, id: tx::Hash) -> Result<TxResponse, NyxdError>
where
C: CosmWasmClient + Sync,
{
self.client.get_tx(id).await
}
pub async fn search_tx(&self, query: Query) -> Result<Vec<TxResponse>, NymdError>
pub async fn search_tx(&self, query: Query) -> Result<Vec<TxResponse>, NyxdError>
where
C: CosmWasmClient + Sync,
{
self.client.search_tx(query).await
}
pub async fn get_total_supply(&self) -> Result<Vec<Coin>, NymdError>
pub async fn get_total_supply(&self) -> Result<Vec<Coin>, NyxdError>
where
C: CosmWasmClient + Sync,
{
self.client.get_total_supply().await
}
pub async fn simulate<I, M>(&self, messages: I) -> Result<SimulateResponse, NymdError>
pub async fn simulate<I, M>(&self, messages: I) -> Result<SimulateResponse, NyxdError>
where
C: SigningCosmWasmClient + Sync,
I: IntoIterator<Item = M> + Send,
@@ -508,7 +512,7 @@ impl<C> NymdClient<C> {
.map(|msg| msg.into_any())
.collect::<Result<Vec<_>, _>>()
.map_err(|_| {
NymdError::SerializationError("custom simulate messages".to_owned())
NyxdError::SerializationError("custom simulate messages".to_owned())
})?,
"simulating execution of transactions",
)
@@ -522,7 +526,7 @@ impl<C> NymdClient<C> {
amount: Vec<Coin>,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<TxResponse, NymdError>
) -> Result<TxResponse, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -538,7 +542,7 @@ impl<C> NymdClient<C> {
msgs: Vec<(AccountId, Vec<Coin>)>,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<TxResponse, NymdError>
) -> Result<TxResponse, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -557,7 +561,7 @@ impl<C> NymdClient<C> {
allowed_messages: Vec<String>,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<TxResponse, NymdError>
) -> Result<TxResponse, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -581,7 +585,7 @@ impl<C> NymdClient<C> {
grantee: &AccountId,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<TxResponse, NymdError>
) -> Result<TxResponse, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -598,7 +602,7 @@ impl<C> NymdClient<C> {
fee: Option<Fee>,
memo: impl Into<String> + Send + 'static,
funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError>
) -> Result<ExecuteResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
M: ?Sized + Serialize + Sync,
@@ -615,7 +619,7 @@ impl<C> NymdClient<C> {
msgs: I,
fee: Option<Fee>,
memo: impl Into<String> + Send + 'static,
) -> Result<ExecuteResult, NymdError>
) -> Result<ExecuteResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
I: IntoIterator<Item = (M, Vec<Coin>)> + Send,
@@ -632,7 +636,7 @@ impl<C> NymdClient<C> {
wasm_code: Vec<u8>,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<UploadResult, NymdError>
) -> Result<UploadResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -650,7 +654,7 @@ impl<C> NymdClient<C> {
memo: impl Into<String> + Send + 'static,
options: Option<InstantiateOptions>,
fee: Option<Fee>,
) -> Result<InstantiateResult, NymdError>
) -> Result<InstantiateResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
M: ?Sized + Serialize + Sync,
@@ -667,7 +671,7 @@ impl<C> NymdClient<C> {
new_admin: &AccountId,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<ChangeAdminResult, NymdError>
) -> Result<ChangeAdminResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -682,7 +686,7 @@ impl<C> NymdClient<C> {
contract_address: &AccountId,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<ChangeAdminResult, NymdError>
) -> Result<ChangeAdminResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
{
@@ -699,7 +703,7 @@ impl<C> NymdClient<C> {
msg: &M,
memo: impl Into<String> + Send + 'static,
fee: Option<Fee>,
) -> Result<MigrateResult, NymdError>
) -> Result<MigrateResult, NyxdError>
where
C: SigningCosmWasmClient + Sync,
M: ?Sized + Serialize + Sync,
@@ -1,8 +1,8 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nymd::{CosmWasmClient, NymdClient};
use crate::nyxd::error::NyxdError;
use crate::nyxd::{CosmWasmClient, NyxdClient};
use coconut_bandwidth_contract_common::msg::QueryMsg;
use coconut_bandwidth_contract_common::spend_credential::SpendCredentialResponse;
@@ -14,15 +14,15 @@ pub trait CoconutBandwidthQueryClient {
async fn get_spent_credential(
&self,
blinded_serial_number: String,
) -> Result<SpendCredentialResponse, NymdError>;
) -> Result<SpendCredentialResponse, NyxdError>;
}
#[async_trait]
impl<C: CosmWasmClient + Sync + Send> CoconutBandwidthQueryClient for NymdClient<C> {
impl<C: CosmWasmClient + Sync + Send> CoconutBandwidthQueryClient for NyxdClient<C> {
async fn get_spent_credential(
&self,
blinded_serial_number: String,
) -> Result<SpendCredentialResponse, NymdError> {
) -> Result<SpendCredentialResponse, NyxdError> {
let request = QueryMsg::GetSpentCredential {
blinded_serial_number,
};
@@ -1,10 +1,10 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub use crate::nymd::cosmwasm_client::signing_client::SigningCosmWasmClient;
use crate::nymd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError;
use crate::nymd::{Coin, Fee, NymdClient};
pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nyxd::error::NyxdError;
use crate::nyxd::{Coin, Fee, NyxdClient};
use coconut_bandwidth_contract_common::spend_credential::SpendCredentialData;
use coconut_bandwidth_contract_common::{deposit::DepositData, msg::ExecuteMsg};
@@ -19,18 +19,18 @@ pub trait CoconutBandwidthSigningClient {
verification_key: String,
encryption_key: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn spend_credential(
&self,
funds: Coin,
blinded_serial_number: String,
gateway_cosmos_address: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
}
#[async_trait]
impl<C: SigningCosmWasmClient + Sync + Send> CoconutBandwidthSigningClient for NymdClient<C> {
impl<C: SigningCosmWasmClient + Sync + Send> CoconutBandwidthSigningClient for NyxdClient<C> {
async fn deposit(
&self,
amount: Coin,
@@ -38,7 +38,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> CoconutBandwidthSigningClient for N
verification_key: String,
encryption_key: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = ExecuteMsg::DepositFunds {
data: DepositData::new(info.to_string(), verification_key, encryption_key),
@@ -60,7 +60,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> CoconutBandwidthSigningClient for N
blinded_serial_number: String,
gateway_cosmos_address: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = ExecuteMsg::SpendCredential {
data: SpendCredentialData::new(
@@ -1,8 +1,8 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nymd::{CosmWasmClient, NymdClient};
use crate::nyxd::error::NyxdError;
use crate::nyxd::{CosmWasmClient, NyxdClient};
use async_trait::async_trait;
use coconut_dkg_common::dealer::{
DealerDetailsResponse, PagedDealerResponse, PagedDealingsResponse,
@@ -14,48 +14,48 @@ use cosmrs::AccountId;
#[async_trait]
pub trait DkgQueryClient {
async fn get_current_epoch(&self) -> Result<Epoch, NymdError>;
async fn get_current_epoch_threshold(&self) -> Result<Option<u64>, NymdError>;
async fn get_current_epoch(&self) -> Result<Epoch, NyxdError>;
async fn get_current_epoch_threshold(&self) -> Result<Option<u64>, NyxdError>;
async fn get_dealer_details(
&self,
address: &AccountId,
) -> Result<DealerDetailsResponse, NymdError>;
) -> Result<DealerDetailsResponse, NyxdError>;
async fn get_current_dealers_paged(
&self,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedDealerResponse, NymdError>;
) -> Result<PagedDealerResponse, NyxdError>;
async fn get_past_dealers_paged(
&self,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedDealerResponse, NymdError>;
) -> Result<PagedDealerResponse, NyxdError>;
async fn get_dealings_paged(
&self,
idx: usize,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedDealingsResponse, NymdError>;
) -> Result<PagedDealingsResponse, NyxdError>;
async fn get_vk_shares_paged(
&self,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedVKSharesResponse, NymdError>;
) -> Result<PagedVKSharesResponse, NyxdError>;
}
#[async_trait]
impl<C> DkgQueryClient for NymdClient<C>
impl<C> DkgQueryClient for NyxdClient<C>
where
C: CosmWasmClient + Send + Sync,
{
async fn get_current_epoch(&self) -> Result<Epoch, NymdError> {
async fn get_current_epoch(&self) -> Result<Epoch, NyxdError> {
let request = DkgQueryMsg::GetCurrentEpochState {};
self.client
.query_contract_smart(self.coconut_dkg_contract_address(), &request)
.await
}
async fn get_current_epoch_threshold(&self) -> Result<Option<u64>, NymdError> {
async fn get_current_epoch_threshold(&self) -> Result<Option<u64>, NyxdError> {
let request = DkgQueryMsg::GetCurrentEpochThreshold {};
self.client
.query_contract_smart(self.coconut_dkg_contract_address(), &request)
@@ -64,7 +64,7 @@ where
async fn get_dealer_details(
&self,
address: &AccountId,
) -> Result<DealerDetailsResponse, NymdError> {
) -> Result<DealerDetailsResponse, NyxdError> {
let request = DkgQueryMsg::GetDealerDetails {
dealer_address: address.to_string(),
};
@@ -77,7 +77,7 @@ where
&self,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedDealerResponse, NymdError> {
) -> Result<PagedDealerResponse, NyxdError> {
let request = DkgQueryMsg::GetCurrentDealers {
start_after,
limit: page_limit,
@@ -91,7 +91,7 @@ where
&self,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedDealerResponse, NymdError> {
) -> Result<PagedDealerResponse, NyxdError> {
let request = DkgQueryMsg::GetPastDealers {
start_after,
limit: page_limit,
@@ -106,7 +106,7 @@ where
idx: usize,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedDealingsResponse, NymdError> {
) -> Result<PagedDealingsResponse, NyxdError> {
let request = DkgQueryMsg::GetDealing {
idx: idx as u64,
limit: page_limit,
@@ -121,7 +121,7 @@ where
&self,
start_after: Option<String>,
page_limit: Option<u32>,
) -> Result<PagedVKSharesResponse, NymdError> {
) -> Result<PagedVKSharesResponse, NyxdError> {
let request = DkgQueryMsg::GetVerificationKeys {
limit: page_limit,
start_after,
@@ -1,9 +1,9 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError;
use crate::nymd::{Fee, NymdClient, SigningCosmWasmClient};
use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nyxd::error::NyxdError;
use crate::nyxd::{Fee, NyxdClient, SigningCosmWasmClient};
use async_trait::async_trait;
use coconut_dkg_common::msg::ExecuteMsg as DkgExecuteMsg;
use coconut_dkg_common::types::EncodedBTEPublicKeyWithProof;
@@ -12,33 +12,33 @@ use contracts_common::dealings::ContractSafeBytes;
#[async_trait]
pub trait DkgSigningClient {
async fn advance_dkg_epoch_state(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError>;
async fn advance_dkg_epoch_state(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError>;
async fn register_dealer(
&self,
bte_key: EncodedBTEPublicKeyWithProof,
announce_address: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn submit_dealing_bytes(
&self,
commitment: ContractSafeBytes,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn submit_verification_key_share(
&self,
share: VerificationKeyShare,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
}
#[async_trait]
impl<C> DkgSigningClient for NymdClient<C>
impl<C> DkgSigningClient for NyxdClient<C>
where
C: SigningCosmWasmClient + Send + Sync,
{
async fn advance_dkg_epoch_state(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> {
async fn advance_dkg_epoch_state(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
let req = DkgExecuteMsg::AdvanceEpochState {};
self.client
@@ -58,7 +58,7 @@ where
bte_key: EncodedBTEPublicKeyWithProof,
announce_address: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let req = DkgExecuteMsg::RegisterDealer {
bte_key_with_proof: bte_key,
announce_address,
@@ -80,7 +80,7 @@ where
&self,
dealing_bytes: ContractSafeBytes,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let req = DkgExecuteMsg::CommitDealing { dealing_bytes };
self.client
@@ -99,7 +99,7 @@ where
&self,
share: VerificationKeyShare,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let req = DkgExecuteMsg::CommitVerificationKeyShare { share };
self.client
@@ -1,9 +1,9 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub use crate::nymd::cosmwasm_client::client::CosmWasmClient;
use crate::nymd::error::NymdError;
use crate::nymd::NymdClient;
pub use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
use crate::nyxd::error::NyxdError;
use crate::nyxd::NyxdClient;
use async_trait::async_trait;
use cosmrs::AccountId;
use mixnet_contract_common::delegation::{MixNodeDelegationResponse, OwnerProxySubKey};
@@ -29,38 +29,38 @@ use serde::Deserialize;
#[async_trait]
pub trait MixnetQueryClient {
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NymdError>
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NyxdError>
where
for<'a> T: Deserialize<'a>;
// state/sys-params-related
async fn get_mixnet_contract_version(&self) -> Result<ContractBuildInformation, NymdError> {
async fn get_mixnet_contract_version(&self) -> Result<ContractBuildInformation, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetContractVersion {})
.await
}
async fn get_rewarding_validator_address(&self) -> Result<AccountId, NymdError> {
async fn get_rewarding_validator_address(&self) -> Result<AccountId, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetRewardingValidatorAddress {})
.await
}
async fn get_mixnet_contract_settings(&self) -> Result<ContractStateParams, NymdError> {
async fn get_mixnet_contract_settings(&self) -> Result<ContractStateParams, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetStateParams {})
.await
}
async fn get_mixnet_contract_state(&self) -> Result<ContractState, NymdError> {
async fn get_mixnet_contract_state(&self) -> Result<ContractState, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetState {})
.await
}
async fn get_rewarding_parameters(&self) -> Result<RewardingParams, NymdError> {
async fn get_rewarding_parameters(&self) -> Result<RewardingParams, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetRewardingParams {})
.await
}
async fn get_current_interval_details(&self) -> Result<CurrentIntervalResponse, NymdError> {
async fn get_current_interval_details(&self) -> Result<CurrentIntervalResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetCurrentIntervalDetails {})
.await
}
@@ -69,7 +69,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<MixId>,
limit: Option<u32>,
) -> Result<PagedRewardedSetResponse, NymdError> {
) -> Result<PagedRewardedSetResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetRewardedSet { limit, start_after })
.await
}
@@ -78,7 +78,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<String>,
limit: Option<u32>,
) -> Result<PagedFamiliesResponse, NymdError> {
) -> Result<PagedFamiliesResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetAllFamiliesPaged { limit, start_after })
.await
}
@@ -87,7 +87,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<String>,
limit: Option<u32>,
) -> Result<PagedMembersResponse, NymdError> {
) -> Result<PagedMembersResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetAllMembersPaged { limit, start_after })
.await
}
@@ -98,7 +98,7 @@ pub trait MixnetQueryClient {
&self,
limit: Option<u32>,
start_after: Option<MixId>,
) -> Result<PagedMixnodeBondsResponse, NymdError> {
) -> Result<PagedMixnodeBondsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixNodeBonds { limit, start_after })
.await
}
@@ -107,7 +107,7 @@ pub trait MixnetQueryClient {
&self,
limit: Option<u32>,
start_after: Option<MixId>,
) -> Result<PagedMixnodesDetailsResponse, NymdError> {
) -> Result<PagedMixnodesDetailsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixNodesDetailed { limit, start_after })
.await
}
@@ -116,7 +116,7 @@ pub trait MixnetQueryClient {
&self,
limit: Option<u32>,
start_after: Option<MixId>,
) -> Result<PagedUnbondedMixnodesResponse, NymdError> {
) -> Result<PagedUnbondedMixnodesResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodes { limit, start_after })
.await
}
@@ -126,7 +126,7 @@ pub trait MixnetQueryClient {
owner: &AccountId,
limit: Option<u32>,
start_after: Option<MixId>,
) -> Result<PagedUnbondedMixnodesResponse, NymdError> {
) -> Result<PagedUnbondedMixnodesResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodesByOwner {
owner: owner.to_string(),
limit,
@@ -140,7 +140,7 @@ pub trait MixnetQueryClient {
identity_key: String,
limit: Option<u32>,
start_after: Option<MixId>,
) -> Result<PagedUnbondedMixnodesResponse, NymdError> {
) -> Result<PagedUnbondedMixnodesResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodesByIdentityKey {
identity_key,
limit,
@@ -152,7 +152,7 @@ pub trait MixnetQueryClient {
async fn get_owned_mixnode(
&self,
address: &AccountId,
) -> Result<MixOwnershipResponse, NymdError> {
) -> Result<MixOwnershipResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetOwnedMixnode {
address: address.to_string(),
})
@@ -162,7 +162,7 @@ pub trait MixnetQueryClient {
async fn get_mixnode_details(
&self,
mix_id: MixId,
) -> Result<MixnodeDetailsResponse, NymdError> {
) -> Result<MixnodeDetailsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixnodeDetails { mix_id })
.await
}
@@ -170,7 +170,7 @@ pub trait MixnetQueryClient {
async fn get_mixnode_rewarding_details(
&self,
mix_id: MixId,
) -> Result<MixnodeRewardingDetailsResponse, NymdError> {
) -> Result<MixnodeRewardingDetailsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixnodeRewardingDetails { mix_id })
.await
}
@@ -178,7 +178,7 @@ pub trait MixnetQueryClient {
async fn get_mixnode_stake_saturation(
&self,
mix_id: MixId,
) -> Result<StakeSaturationResponse, NymdError> {
) -> Result<StakeSaturationResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetStakeSaturation { mix_id })
.await
}
@@ -186,12 +186,12 @@ pub trait MixnetQueryClient {
async fn get_unbonded_mixnode_information(
&self,
mix_id: MixId,
) -> Result<UnbondedMixnodeResponse, NymdError> {
) -> Result<UnbondedMixnodeResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetUnbondedMixNodeInformation { mix_id })
.await
}
async fn get_layer_distribution(&self) -> Result<LayerDistribution, NymdError> {
async fn get_layer_distribution(&self) -> Result<LayerDistribution, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetLayerDistribution {})
.await
}
@@ -202,7 +202,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<IdentityKey>,
limit: Option<u32>,
) -> Result<PagedGatewayResponse, NymdError> {
) -> Result<PagedGatewayResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetGateways { start_after, limit })
.await
}
@@ -211,7 +211,7 @@ pub trait MixnetQueryClient {
async fn get_gateway_bond(
&self,
identity: IdentityKey,
) -> Result<GatewayBondResponse, NymdError> {
) -> Result<GatewayBondResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetGatewayBond { identity })
.await
}
@@ -220,7 +220,7 @@ pub trait MixnetQueryClient {
async fn get_owned_gateway(
&self,
address: &AccountId,
) -> Result<GatewayOwnershipResponse, NymdError> {
) -> Result<GatewayOwnershipResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetOwnedGateway {
address: address.to_string(),
})
@@ -235,7 +235,7 @@ pub trait MixnetQueryClient {
mix_id: MixId,
start_after: Option<String>,
limit: Option<u32>,
) -> Result<PagedMixNodeDelegationsResponse, NymdError> {
) -> Result<PagedMixNodeDelegationsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetMixnodeDelegations {
mix_id,
start_after,
@@ -250,7 +250,7 @@ pub trait MixnetQueryClient {
delegator: String,
start_after: Option<(MixId, OwnerProxySubKey)>,
limit: Option<u32>,
) -> Result<PagedDelegatorDelegationsResponse, NymdError> {
) -> Result<PagedDelegatorDelegationsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetDelegatorDelegations {
delegator,
start_after,
@@ -265,7 +265,7 @@ pub trait MixnetQueryClient {
mix_id: MixId,
delegator: &AccountId,
proxy: Option<String>,
) -> Result<MixNodeDelegationResponse, NymdError> {
) -> Result<MixNodeDelegationResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetDelegationDetails {
mix_id,
delegator: delegator.to_string(),
@@ -279,7 +279,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<delegation::StorageKey>,
limit: Option<u32>,
) -> Result<PagedAllDelegationsResponse, NymdError> {
) -> Result<PagedAllDelegationsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetAllDelegations { start_after, limit })
.await
}
@@ -288,7 +288,7 @@ pub trait MixnetQueryClient {
async fn get_pending_operator_reward(
&self,
operator: &AccountId,
) -> Result<PendingRewardResponse, NymdError> {
) -> Result<PendingRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingOperatorReward {
address: operator.to_string(),
})
@@ -298,7 +298,7 @@ pub trait MixnetQueryClient {
async fn get_pending_mixnode_operator_reward(
&self,
mix_id: MixId,
) -> Result<PendingRewardResponse, NymdError> {
) -> Result<PendingRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingMixNodeOperatorReward { mix_id })
.await
}
@@ -308,7 +308,7 @@ pub trait MixnetQueryClient {
delegator: &AccountId,
mix_id: MixId,
proxy: Option<String>,
) -> Result<PendingRewardResponse, NymdError> {
) -> Result<PendingRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingDelegatorReward {
address: delegator.to_string(),
mix_id,
@@ -322,7 +322,7 @@ pub trait MixnetQueryClient {
&self,
mix_id: MixId,
estimated_performance: Performance,
) -> Result<EstimatedCurrentEpochRewardResponse, NymdError> {
) -> Result<EstimatedCurrentEpochRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetEstimatedCurrentEpochOperatorReward {
mix_id,
estimated_performance,
@@ -337,7 +337,7 @@ pub trait MixnetQueryClient {
mix_id: MixId,
proxy: Option<String>,
estimated_performance: Performance,
) -> Result<EstimatedCurrentEpochRewardResponse, NymdError> {
) -> Result<EstimatedCurrentEpochRewardResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetEstimatedCurrentEpochDelegatorReward {
address: delegator.to_string(),
mix_id,
@@ -353,7 +353,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<EpochEventId>,
limit: Option<u32>,
) -> Result<PendingEpochEventsResponse, NymdError> {
) -> Result<PendingEpochEventsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingEpochEvents { start_after, limit })
.await
}
@@ -362,7 +362,7 @@ pub trait MixnetQueryClient {
&self,
start_after: Option<IntervalEventId>,
limit: Option<u32>,
) -> Result<PendingIntervalEventsResponse, NymdError> {
) -> Result<PendingIntervalEventsResponse, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetPendingIntervalEvents { start_after, limit })
.await
}
@@ -370,21 +370,21 @@ pub trait MixnetQueryClient {
async fn get_mixnode_details_by_identity(
&self,
mix_identity: IdentityKey,
) -> Result<Option<MixNodeDetails>, NymdError> {
) -> Result<Option<MixNodeDetails>, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetBondedMixnodeDetailsByIdentity {
mix_identity,
})
.await
}
async fn get_node_family_by_label(&self, label: &str) -> Result<Option<Family>, NymdError> {
async fn get_node_family_by_label(&self, label: &str) -> Result<Option<Family>, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetFamilyByLabel {
label: label.to_string(),
})
.await
}
async fn get_node_family_by_head(&self, head: &str) -> Result<Option<Family>, NymdError> {
async fn get_node_family_by_head(&self, head: &str) -> Result<Option<Family>, NyxdError> {
self.query_mixnet_contract(MixnetQueryMsg::GetFamilyByHead {
head: head.to_string(),
})
@@ -393,11 +393,11 @@ pub trait MixnetQueryClient {
}
#[async_trait]
impl<C> MixnetQueryClient for NymdClient<C>
impl<C> MixnetQueryClient for NyxdClient<C>
where
C: CosmWasmClient + Sync + Send,
{
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NymdError>
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NyxdError>
where
for<'a> T: Deserialize<'a>,
{
@@ -412,10 +412,10 @@ impl<C> MixnetQueryClient for crate::Client<C>
where
C: CosmWasmClient + Sync + Send,
{
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NymdError>
async fn query_mixnet_contract<T>(&self, query: MixnetQueryMsg) -> Result<T, NyxdError>
where
for<'a> T: Deserialize<'a>,
{
self.nymd.query_mixnet_contract(query).await
self.nyxd.query_mixnet_contract(query).await
}
}
@@ -1,11 +1,11 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::coin::Coin;
pub use crate::nymd::cosmwasm_client::client::CosmWasmClient;
use crate::nymd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError;
use crate::nymd::{Fee, NymdClient, SigningCosmWasmClient};
use crate::nyxd::coin::Coin;
pub use crate::nyxd::cosmwasm_client::client::CosmWasmClient;
use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nyxd::error::NyxdError;
use crate::nyxd::{Fee, NyxdClient, SigningCosmWasmClient};
use async_trait::async_trait;
use cosmrs::AccountId;
use mixnet_contract_common::mixnode::{MixNodeConfigUpdate, MixNodeCostParams};
@@ -21,7 +21,7 @@ pub trait MixnetSigningClient {
fee: Option<Fee>,
msg: MixnetExecuteMsg,
funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
// state/sys-params-related
@@ -29,7 +29,7 @@ pub trait MixnetSigningClient {
&self,
address: AccountId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateRewardingValidatorAddress {
@@ -44,7 +44,7 @@ pub trait MixnetSigningClient {
&self,
updated_parameters: ContractStateParams,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateContractStateParams { updated_parameters },
@@ -58,7 +58,7 @@ pub trait MixnetSigningClient {
active_set_size: u32,
force_immediately: bool,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateActiveSetSize {
@@ -75,7 +75,7 @@ pub trait MixnetSigningClient {
updated_params: IntervalRewardingParamsUpdate,
force_immediately: bool,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateRewardingParams {
@@ -93,7 +93,7 @@ pub trait MixnetSigningClient {
epoch_duration_secs: u64,
force_immediately: bool,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateIntervalConfig {
@@ -111,7 +111,7 @@ pub trait MixnetSigningClient {
new_rewarded_set: Vec<LayerAssignment>,
expected_active_set_size: u32,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::AdvanceCurrentEpoch {
@@ -127,7 +127,7 @@ pub trait MixnetSigningClient {
&self,
limit: Option<u32>,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::ReconcileEpochEvents { limit },
@@ -142,7 +142,7 @@ pub trait MixnetSigningClient {
owner_signature: String,
label: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::CreateFamily {
@@ -160,7 +160,7 @@ pub trait MixnetSigningClient {
owner_signature: String,
label: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::CreateFamilyOnBehalf {
@@ -178,7 +178,7 @@ pub trait MixnetSigningClient {
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::JoinFamily {
@@ -196,7 +196,7 @@ pub trait MixnetSigningClient {
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::JoinFamilyOnBehalf {
@@ -214,7 +214,7 @@ pub trait MixnetSigningClient {
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::LeaveFamily {
@@ -232,7 +232,7 @@ pub trait MixnetSigningClient {
signature: String,
family_head: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::LeaveFamilyOnBehalf {
@@ -250,7 +250,7 @@ pub trait MixnetSigningClient {
signature: String,
member: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::KickFamilyMember { signature, member },
@@ -265,7 +265,7 @@ pub trait MixnetSigningClient {
signature: String,
member: String,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::KickFamilyMemberOnBehalf {
@@ -286,7 +286,7 @@ pub trait MixnetSigningClient {
owner_signature: String,
pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::BondMixnode {
@@ -307,7 +307,7 @@ pub trait MixnetSigningClient {
owner_signature: String,
pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::BondMixnodeOnBehalf {
@@ -325,7 +325,7 @@ pub trait MixnetSigningClient {
&self,
additional_pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::PledgeMore {},
@@ -339,7 +339,7 @@ pub trait MixnetSigningClient {
owner: AccountId,
additional_pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::PledgeMoreOnBehalf {
@@ -350,7 +350,7 @@ pub trait MixnetSigningClient {
.await
}
async fn unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> {
async fn unbond_mixnode(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(fee, MixnetExecuteMsg::UnbondMixnode {}, vec![])
.await
}
@@ -359,7 +359,7 @@ pub trait MixnetSigningClient {
&self,
owner: AccountId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UnbondMixnodeOnBehalf {
@@ -374,7 +374,7 @@ pub trait MixnetSigningClient {
&self,
new_costs: MixNodeCostParams,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateMixnodeCostParams { new_costs },
@@ -388,7 +388,7 @@ pub trait MixnetSigningClient {
owner: AccountId,
new_costs: MixNodeCostParams,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateMixnodeCostParamsOnBehalf {
@@ -404,7 +404,7 @@ pub trait MixnetSigningClient {
&self,
new_config: MixNodeConfigUpdate,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateMixnodeConfig { new_config },
@@ -418,7 +418,7 @@ pub trait MixnetSigningClient {
owner: AccountId,
new_config: MixNodeConfigUpdate,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UpdateMixnodeConfigOnBehalf {
@@ -438,7 +438,7 @@ pub trait MixnetSigningClient {
owner_signature: String,
pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::BondGateway {
@@ -457,7 +457,7 @@ pub trait MixnetSigningClient {
owner_signature: String,
pledge: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::BondGatewayOnBehalf {
@@ -470,7 +470,7 @@ pub trait MixnetSigningClient {
.await
}
async fn unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> {
async fn unbond_gateway(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(fee, MixnetExecuteMsg::UnbondGateway {}, vec![])
.await
}
@@ -479,7 +479,7 @@ pub trait MixnetSigningClient {
&self,
owner: AccountId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UnbondGatewayOnBehalf {
@@ -497,7 +497,7 @@ pub trait MixnetSigningClient {
mix_id: MixId,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::DelegateToMixnode { mix_id },
@@ -512,7 +512,7 @@ pub trait MixnetSigningClient {
mix_id: MixId,
amount: Coin,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::DelegateToMixnodeOnBehalf {
@@ -528,7 +528,7 @@ pub trait MixnetSigningClient {
&self,
mix_id: MixId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UndelegateFromMixnode { mix_id },
@@ -542,7 +542,7 @@ pub trait MixnetSigningClient {
delegate: AccountId,
mix_id: MixId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::UndelegateFromMixnodeOnBehalf {
@@ -561,7 +561,7 @@ pub trait MixnetSigningClient {
mix_id: MixId,
performance: Performance,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::RewardMixnode {
@@ -573,7 +573,7 @@ pub trait MixnetSigningClient {
.await
}
async fn withdraw_operator_reward(&self, fee: Option<Fee>) -> Result<ExecuteResult, NymdError> {
async fn withdraw_operator_reward(&self, fee: Option<Fee>) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(fee, MixnetExecuteMsg::WithdrawOperatorReward {}, vec![])
.await
}
@@ -582,7 +582,7 @@ pub trait MixnetSigningClient {
&self,
owner: AccountId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::WithdrawOperatorRewardOnBehalf {
@@ -597,7 +597,7 @@ pub trait MixnetSigningClient {
&self,
mix_id: MixId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::WithdrawDelegatorReward { mix_id },
@@ -611,7 +611,7 @@ pub trait MixnetSigningClient {
owner: AccountId,
mix_id: MixId,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
self.execute_mixnet_contract(
fee,
MixnetExecuteMsg::WithdrawDelegatorRewardOnBehalf {
@@ -625,7 +625,7 @@ pub trait MixnetSigningClient {
}
#[async_trait]
impl<C> MixnetSigningClient for NymdClient<C>
impl<C> MixnetSigningClient for NyxdClient<C>
where
C: SigningCosmWasmClient + Sync + Send,
{
@@ -634,7 +634,7 @@ where
fee: Option<Fee>,
msg: MixnetExecuteMsg,
funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let memo = msg.default_memo();
self.client
@@ -660,7 +660,7 @@ where
fee: Option<Fee>,
msg: MixnetExecuteMsg,
funds: Vec<Coin>,
) -> Result<ExecuteResult, NymdError> {
self.nymd.execute_mixnet_contract(fee, msg, funds).await
) -> Result<ExecuteResult, NyxdError> {
self.nyxd.execute_mixnet_contract(fee, msg, funds).await
}
}
@@ -1,8 +1,8 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nymd::{CosmWasmClient, NymdClient};
use crate::nyxd::error::NyxdError;
use crate::nyxd::{CosmWasmClient, NyxdClient};
use cw3::{ProposalListResponse, ProposalResponse};
use multisig_contract_common::msg::QueryMsg;
@@ -11,17 +11,17 @@ use async_trait::async_trait;
#[async_trait]
pub trait MultisigQueryClient {
async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NymdError>;
async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NyxdError>;
async fn list_proposals(
&self,
start_after: Option<u64>,
limit: Option<u32>,
) -> Result<ProposalListResponse, NymdError>;
) -> Result<ProposalListResponse, NyxdError>;
}
#[async_trait]
impl<C: CosmWasmClient + Sync + Send> MultisigQueryClient for NymdClient<C> {
async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NymdError> {
impl<C: CosmWasmClient + Sync + Send> MultisigQueryClient for NyxdClient<C> {
async fn get_proposal(&self, proposal_id: u64) -> Result<ProposalResponse, NyxdError> {
let request = QueryMsg::Proposal { proposal_id };
self.client
.query_contract_smart(self.multisig_contract_address(), &request)
@@ -32,7 +32,7 @@ impl<C: CosmWasmClient + Sync + Send> MultisigQueryClient for NymdClient<C> {
&self,
start_after: Option<u64>,
limit: Option<u32>,
) -> Result<ProposalListResponse, NymdError> {
) -> Result<ProposalListResponse, NyxdError> {
let request = QueryMsg::ListProposals { start_after, limit };
self.client
.query_contract_smart(self.multisig_contract_address(), &request)
@@ -1,10 +1,10 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub use crate::nymd::cosmwasm_client::signing_client::SigningCosmWasmClient;
use crate::nymd::cosmwasm_client::types::ExecuteResult;
use crate::nymd::error::NymdError;
use crate::nymd::{Fee, NymdClient};
pub use crate::nyxd::cosmwasm_client::signing_client::SigningCosmWasmClient;
use crate::nyxd::cosmwasm_client::types::ExecuteResult;
use crate::nyxd::error::NyxdError;
use crate::nyxd::{Fee, NyxdClient};
use coconut_bandwidth_contract_common::msg::ExecuteMsg as CoconutBandwidthExecuteMsg;
use cw3::Vote;
@@ -21,31 +21,31 @@ pub trait MultisigSigningClient {
blinded_serial_number: String,
voucher_value: u128,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn vote_proposal(
&self,
proposal_id: u64,
yes: bool,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
async fn execute_proposal(
&self,
proposal_id: u64,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError>;
) -> Result<ExecuteResult, NyxdError>;
}
#[async_trait]
impl<C: SigningCosmWasmClient + Sync + Send> MultisigSigningClient for NymdClient<C> {
impl<C: SigningCosmWasmClient + Sync + Send> MultisigSigningClient for NyxdClient<C> {
async fn propose_release_funds(
&self,
title: String,
blinded_serial_number: String,
voucher_value: u128,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let release_funds_req = CoconutBandwidthExecuteMsg::ReleaseFunds {
funds: Coin::new(
@@ -81,7 +81,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> MultisigSigningClient for NymdClien
proposal_id: u64,
vote_yes: bool,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let vote = if vote_yes { Vote::Yes } else { Vote::No };
let req = ExecuteMsg::Vote { proposal_id, vote };
@@ -101,7 +101,7 @@ impl<C: SigningCosmWasmClient + Sync + Send> MultisigSigningClient for NymdClien
&self,
proposal_id: u64,
fee: Option<Fee>,
) -> Result<ExecuteResult, NymdError> {
) -> Result<ExecuteResult, NyxdError> {
let fee = fee.unwrap_or(Fee::Auto(Some(self.simulated_gas_multiplier)));
let req = ExecuteMsg::Execute { proposal_id };
self.client

Some files were not shown because too many files have changed in this diff Show More