diff --git a/.eslintrc.cjs b/.eslintrc.cjs
new file mode 100644
index 000000000..4e8422ad1
--- /dev/null
+++ b/.eslintrc.cjs
@@ -0,0 +1,88 @@
+module.exports = {
+ env: {
+ browser: true,
+ es2020: true,
+ },
+ extends: [
+ 'plugin:prettier/recommended',
+ 'plugin:@typescript-eslint/recommended',
+ 'plugin:import/recommended',
+ 'plugin:import/typescript',
+ ],
+ parser: '@typescript-eslint/parser',
+ parserOptions: {
+ ecmaVersion: 2020,
+ sourceType: 'module',
+ tsconfigRootDir: __dirname,
+ project: [
+ './packages/**/tsconfig.json',
+ './docs/**/tsconfig.json',
+ '**/tsconfig.eslint.json',
+ ],
+ },
+ plugins: ['@typescript-eslint', 'import'],
+ rules: {
+ 'prettier/prettier': 'warn',
+ quotes: [
+ 2,
+ 'single',
+ {
+ avoidEscape: true,
+ },
+ ],
+ 'import/no-unresolved': [
+ 2,
+ {
+ ignore: [
+ '@concordium/rust-bindings',
+ 'grpc-api',
+ '^#.+$', // ESLint resolver does not support subpath imports: https://github.com/import-js/eslint-plugin-import/issues/1868.
+ ],
+ },
+ ],
+ 'import/no-extraneous-dependencies': [
+ 'error',
+ {
+ devDependencies: ['**/*/test/*', '**/*.config.js'],
+ },
+ ],
+ '@typescript-eslint/no-unused-vars': [
+ 'warn',
+ {
+ ignoreRestSiblings: true,
+ },
+ ],
+ },
+ overrides: [
+ {
+ files: ['*.config.js'],
+ rules: {
+ '@typescript-eslint/no-var-requires': 'off',
+ 'import/namespace': 'off',
+ },
+ },
+ ],
+ ignorePatterns: [
+ '**/pkg/**/',
+ '**/dist/**/',
+ '**/lib/**/',
+ 'deps/**/*',
+ '**/src/grpc-api/*',
+ 'typedoc/**',
+ ],
+ settings: {
+ 'import/ignore': ['bs58check'],
+ 'import/parsers': {
+ '@typescript-eslint/parser': ['.ts', '.tsx'],
+ },
+ 'import/resolver': {
+ exports: true,
+ typescript: {
+ project: ['packages/*/tsconfig.json'],
+ },
+ node: {
+ project: ['packages/*/tsconfig.json'],
+ },
+ },
+ },
+};
diff --git a/.eslintrc.json b/.eslintrc.json
deleted file mode 100644
index e9cd6365b..000000000
--- a/.eslintrc.json
+++ /dev/null
@@ -1,54 +0,0 @@
-{
- "env": {
- "browser": true,
- "es2020": true
- },
- "extends": [
- "plugin:prettier/recommended",
- "plugin:@typescript-eslint/recommended",
- "plugin:import/recommended",
- "plugin:import/typescript"
- ],
- "parser": "@typescript-eslint/parser",
- "parserOptions": {
- "ecmaVersion": 2020,
- "sourceType": "module",
- "project": [ "./packages/**/tsconfig.eslint.json", "./tsconfig.eslint.json", "./examples/tsconfig.eslint.json"]
- },
- "plugins": [
- "@typescript-eslint",
- "import"
- ],
- "rules": {
- "quotes": [2, "single", { "avoidEscape": true }],
- "import/no-unresolved": [2, { "ignore": ["@concordium/rust-bindings", "@concordium/common-sdk", "@concordium/node-sdk", "grpc"]}],
- "import/no-extraneous-dependencies": ["error", {"devDependencies": ["**/*.test.ts", "**/*.test.tsx", "**/*.config.js"]}],
- "@typescript-eslint/no-unused-vars": ["warn", { "ignoreRestSiblings": true }]
- },
- "overrides": [
- {
- "files": ["*.config.js"],
- "rules": {
- "@typescript-eslint/no-var-requires": "off",
- "import/namespace": "off"
- }
- }
- ],
- "ignorePatterns": ["**/pkg/**/", "**/lib/**/", "deps/**/*", "**/nodejs/grpc/*", "**/common/grpc/*", "typedoc/**"],
- "settings": {
- "import/ignore": [
- "bs58check"
- ],
- "import/parsers": {
- "@typescript-eslint/parser": [".ts", ".tsx"]
- },
- "import/resolver": {
- "typescript": {
- "project": ["packages/*/tsconfig.json"]
- },
- "node": {
- "project": ["packages/*/tsconfig.json"]
- }
- }
- }
-}
diff --git a/.github/workflows/deployment.yml b/.github/workflows/deployment.yml
index 5fb4c4d02..8d3187ba1 100644
--- a/.github/workflows/deployment.yml
+++ b/.github/workflows/deployment.yml
@@ -4,7 +4,7 @@ on:
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
-# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
+ # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
@@ -38,7 +38,8 @@ jobs:
with:
workspaces: |
packages/rust-bindings
- deps/concordium-deps
+ deps/concordium-base/rust-src
+ deps/concordium-base/concordium-contracts-common
- name: Get wasm-pack
uses: jetli/wasm-pack-action@v0.4.0
@@ -49,11 +50,22 @@ jobs:
id: yarn-cache
uses: actions/cache@v3
with:
- path: node_modules
+ path: |
+ ./node_modules
+ ./docs/node_modules
key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}
+ - name: Cache GRPC
+ id: cache-grpc
+ uses: actions/cache@v3
+ with:
+ path: |
+ ./packages/sdk/src/grpc-api
+ key: ${{ runner.os }}-grpc-${{ hashFiles('deps/concordium-base/concordium-grpc-api') }}
+ restore-keys: ${{ runner.os }}-grpc
+
- name: Get dependencies
if: steps.yarn-cache.outputs.cache-hit != 'true'
run: yarn install --immutable
@@ -66,19 +78,17 @@ jobs:
with:
name: build-release
path: |
- packages/*/lib
- packages/*/grpc
- packages/*/package.json
- packages/*/README.md
- packages/rust-bindings/pkg/*/concordium_rust_bindings*
+ ./packages/sdk/lib
+ ./packages/sdk/src
+ ./packages/rust-bindings/lib
+ ./packages/*/package.json
+ ./packages/*/README.md
build-typedoc:
runs-on: ubuntu-22.04
needs: build
steps:
- uses: actions/checkout@v3
- with:
- submodules: "recursive"
- uses: actions/setup-node@v3
with:
@@ -93,11 +103,13 @@ jobs:
- name: Restore cached dependencies
uses: actions/cache/restore@v3
with:
- path: node_modules
+ path: |
+ ./node_modules
+ ./docs/node_modules
key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}
- name: Generate typedoc documentation
- run: yarn typedoc
+ run: yarn build:docs
- name: Store typedoc
uses: ./.github/actions/upload-artifact
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
index d2d429624..6064a49e1 100644
--- a/.github/workflows/pipeline.yml
+++ b/.github/workflows/pipeline.yml
@@ -7,254 +7,315 @@ on:
pull_request:
branches: [main, release**, feature**]
# Don't run on draft PR's, see: https://github.com/orgs/community/discussions/25722#discussioncomment-3248917
- types: [opened, synchronize, reopened, ready_for_review]
+ types: [ opened, synchronize, reopened, ready_for_review ]
# Allows us to run the workflow manually from the Actions tab
workflow_dispatch:
env:
- NODE_VERSION: 18.16.0
- RUST_VERSION: 1.65
- RUST_FMT: nightly-2023-04-01-x86_64-unknown-linux-gnu
+ DUMMY: 2 # For cache busting.
+ NODE_VERSION: 18.16.0
+ RUST_VERSION: 1.65
+ RUST_FMT: nightly-2023-04-01-x86_64-unknown-linux-gnu
jobs:
- build:
- if: github.event.pull_request.draft == false
- runs-on: ubuntu-22.04
- steps:
- - uses: actions/checkout@v3
- with:
- submodules: "recursive"
-
- - uses: actions/setup-node@v3
- with:
- node-version: ${{ env.NODE_VERSION }}
- cache: yarn
-
- - name: Cache GRPC
- id: cache-grpc
- uses: actions/cache@v3
- with:
- path: |
- ./packages/common/grpc
- ./packages/nodejs/grpc
- key: ${{ runner.os }}-grpc-${{ hashFiles('deps/concordium-base/concordium-grpc-api') }}
-
- - name: Cache WebPack
- uses: actions/cache@v3
- with:
- path: ./packages/web/.webpack-cache
- # These two lines ensure that a fresh cache is generated after each run
- key: ${{ runner.os }}-webpack-${{ github.run_id }}
- restore-keys: ${{ runner.os }}-webpack
-
- - name: Get dependencies
- run: yarn install --immutable
-
- - name: Install rust
- run: rustup default ${{ env.RUST_VERSION }}
-
- - uses: Swatinem/rust-cache@v2
- with:
- workspaces: |
- packages/rust-bindings
- deps/concordium-deps
-
- - name: Get wasm-pack
- uses: jetli/wasm-pack-action@v0.4.0
- with:
- version: 'latest'
-
- - name: Build GRPC bindings
- if: steps.cache-grpc.outputs.cache-hit != 'true'
- run: |
- mkdir -p packages/common/grpc
- mkdir -p packages/nodejs/grpc
- yarn workspace @concordium/common-sdk generate
- yarn workspace @concordium/node-sdk generate
-
- - name: Build
- run: yarn build:dev
-
- - name: Store build-debug
- uses: ./.github/actions/upload-artifact
- with:
- name: build-debug
- path: |
- ./node_modules/@concordium
- ./packages/rust-bindings/pkg
- ./packages/common/lib
- ./packages/nodejs/lib
- ./packages/common/grpc
- ./packages/nodejs/grpc
- ./packages/ccd-js-gen/lib
-
- typecheck-examples:
- runs-on: ubuntu-22.04
- needs: build
- steps:
- - uses: actions/checkout@v3
-
- - uses: actions/setup-node@v3
- with:
- node-version: ${{ env.NODE_VERSION }}
- cache: yarn
-
- - name: Get build-debug
- uses: ./.github/actions/download-artifact
- with:
- name: build-debug
-
- - name: Get dependencies
- run: yarn install --immutable
-
- - name: Typecheck examples
- run: yarn workspace @concordium/examples typecheck
-
- common-tests:
- runs-on: ubuntu-22.04
- needs: build
- defaults:
- run:
- working-directory: packages/common
- steps:
- - uses: actions/checkout@v3
-
- - uses: actions/setup-node@v3
- with:
- node-version: ${{ env.NODE_VERSION }}
- cache: yarn
-
- - name: Get build-debug
- uses: ./.github/actions/download-artifact
- with:
- name: build-debug
-
- - name: Get dependencies
- run: yarn install --immutable
-
- - name: Run Tests
- run: yarn test
-
- typedoc:
- runs-on: ubuntu-22.04
- needs: build
- steps:
- - uses: actions/checkout@v3
-
- - uses: actions/setup-node@v3
- with:
- node-version: ${{ env.NODE_VERSION }}
- cache: yarn
-
- - name: Get build-debug
- uses: ./.github/actions/download-artifact
- with:
- name: build-debug
-
- - name: Get dependencies
- run: yarn install --immutable
-
- - name: Build typedoc
- run: yarn typedoc
-
- lint:
- runs-on: ubuntu-22.04
- needs: build
- if: github.event.pull_request.draft == false
- steps:
- - uses: actions/checkout@v3
-
- - uses: actions/setup-node@v3
- with:
- node-version: ${{ env.NODE_VERSION }}
- cache: yarn
-
- - name: Get build-debug
- uses: ./.github/actions/download-artifact
- with:
- name: build-debug
-
- - name: Install dependencies
- run: yarn install --immutable
-
- - name: Lint
- run: yarn lint
-
- markdown-lint:
- runs-on: ubuntu-22.04
- if: github.event.pull_request.draft == false
- steps:
- - uses: actions/checkout@v3
-
- - uses: actions/setup-node@v3
- with:
- node-version: ${{ env.NODE_VERSION }}
- cache: yarn
-
- - name: Install dependencies
- run: yarn install --immutable
-
- - name: Lint markdown
- run: yarn markdown:lint
-
- markdown-linkcheck:
- runs-on: ubuntu-22.04
- if: github.event.pull_request.draft == false
- steps:
- - uses: actions/checkout@v3
-
- - uses: actions/setup-node@v3
- with:
- node-version: ${{ env.NODE_VERSION }}
- cache: yarn
-
- - name: Install dependencies
- run: yarn install --immutable
-
- - name: Lint markdown
- run: yarn markdown:linkcheck
-
- rust_lint_fmt:
- runs-on: ubuntu-22.04
- if: github.event.pull_request.draft == false
- defaults:
- run:
- working-directory: packages/rust-bindings
- steps:
- - name: Checkout
- uses: actions/checkout@v3
-
- - name: Install formatter
- run: |
- rustup default ${{ env.RUST_FMT }}
- rustup component add rustfmt
-
- - name: Format
- run: cargo fmt -- --color=always --check
-
- rust_lint_clippy:
- runs-on: ubuntu-22.04
- needs: rust_lint_fmt
- if: github.event.pull_request.draft == false
- defaults:
- run:
- working-directory: packages/rust-bindings
- steps:
- - name: Checkout
- uses: actions/checkout@v3
- with:
- submodules: "recursive"
-
- - name: Install clippy
- run: |
- rustup default ${{ env.RUST_VERSION }}
- rustup component add clippy
-
- - uses: Swatinem/rust-cache@v2
- with:
- workspaces: |
- packages/rust-bindings
- deps/concordium-deps
-
- - name: Run clippy
- run: cargo clippy --color=always --tests --benches -- -Dclippy::all
+ deps:
+ if: github.event.pull_request.draft == false
+ runs-on: ubuntu-22.04
+ steps:
+ - uses: actions/checkout@v3
+ with:
+ submodules: 'recursive'
+
+ - uses: actions/setup-node@v3
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: yarn
+
+ - name: Cache dependencies
+ id: yarn-cache
+ uses: actions/cache@v3
+ with:
+ path: |
+ ./node_modules
+ ./docs/node_modules
+ key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}-${{ env.DUMMY }}
+ restore-keys: |
+ ${{ runner.os }}-yarn
+
+ - name: Get dependencies
+ run: yarn install --immutable
+
+ build:
+ if: github.event.pull_request.draft == false
+ runs-on: ubuntu-22.04
+ needs: deps
+ steps:
+ - uses: actions/checkout@v3
+ with:
+ submodules: 'recursive'
+
+ - uses: actions/setup-node@v3
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: yarn
+
+ - name: Cache GRPC
+ id: cache-grpc
+ uses: actions/cache@v3
+ with:
+ path: |
+ ./packages/sdk/src/grpc-api
+ key: ${{ runner.os }}-grpc-${{ hashFiles('deps/concordium-base/concordium-grpc-api') }}-${{ env.DUMMY }}
+ restore-keys: ${{ runner.os }}-grpc
+
+ - name: Cache WebPack
+ uses: actions/cache@v3
+ with:
+ path: ./packages/web/.webpack-cache
+ # These two lines ensure that a fresh cache is generated after each run
+ key: ${{ runner.os }}-webpack-${{ github.run_id }}
+ restore-keys: ${{ runner.os }}-webpack
+
+ - name: Restore dependencies
+ uses: actions/cache/restore@v3
+ with:
+ path: |
+ ./node_modules
+ ./docs/node_modules
+ key: ${{ runner.os }}-yarn
+
+ - name: Install rust
+ run: rustup default ${{ env.RUST_VERSION }}
+
+ - uses: Swatinem/rust-cache@v2
+ with:
+ workspaces: |
+ packages/rust-bindings
+ deps/concordium-base/rust-src
+ deps/concordium-base/concordium-contracts-common
+
+ - name: Build
+ run: yarn build
+
+ - name: Store build-debug
+ uses: ./.github/actions/upload-artifact
+ with:
+ name: build-debug
+ # sdk/src is needed here because of sdk/src/grpc-api
+ path: |
+ ./packages/rust-bindings/lib
+ ./packages/sdk/lib
+ ./packages/sdk/src
+ ./packages/ccd-js-gen/lib
+
+ typecheck-examples:
+ runs-on: ubuntu-22.04
+ needs: build
+ steps:
+ - uses: actions/checkout@v3
+
+ - uses: actions/setup-node@v3
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: yarn
+
+ - name: Restore dependencies
+ uses: actions/cache/restore@v3
+ with:
+ path: |
+ ./node_modules
+ ./docs/node_modules
+ key: ${{ runner.os }}-yarn
+
+ - name: Get build-debug
+ uses: ./.github/actions/download-artifact
+ with:
+ name: build-debug
+
+ - name: Typecheck examples
+ run: yarn workspace @concordium/examples typecheck
+
+ tests:
+ runs-on: ubuntu-22.04
+ needs: build
+ strategy:
+ matrix:
+ package: ['sdk', 'ccd-js-gen']
+ defaults:
+ run:
+ working-directory: packages/${{matrix.package}}
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v3
+ with:
+ submodules: 'recursive'
+
+ - uses: actions/setup-node@v3
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: yarn
+
+ - name: Restore dependencies
+ uses: actions/cache/restore@v3
+ with:
+ path: |
+ ./node_modules
+ ./docs/node_modules
+ key: ${{ runner.os }}-yarn
+
+ - name: Get build-debug
+ uses: ./.github/actions/download-artifact
+ with:
+ name: build-debug
+
+ - name: Run Tests
+ run: yarn test-ci
+
+ typedoc:
+ runs-on: ubuntu-22.04
+ needs: build
+ steps:
+ - uses: actions/checkout@v3
+
+ - uses: actions/setup-node@v3
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: yarn
+
+ - name: Restore dependencies
+ uses: actions/cache/restore@v3
+ with:
+ path: |
+ ./node_modules
+ ./docs/node_modules
+ key: ${{ runner.os }}-yarn
+
+ - name: Get build-debug
+ uses: ./.github/actions/download-artifact
+ with:
+ name: build-debug
+
+ - name: Build typedoc
+ run: yarn build:docs
+
+ lint:
+ runs-on: ubuntu-22.04
+ needs: build
+ if: github.event.pull_request.draft == false
+ steps:
+ - uses: actions/checkout@v3
+
+ - uses: actions/setup-node@v3
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: yarn
+
+ - name: Restore dependencies
+ uses: actions/cache/restore@v3
+ with:
+ path: |
+ ./node_modules
+ ./docs/node_modules
+ key: ${{ runner.os }}-yarn
+
+ - name: Get build-debug
+ uses: ./.github/actions/download-artifact
+ with:
+ name: build-debug
+
+ - name: Lint
+ run: yarn lint
+
+ markdown-lint:
+ runs-on: ubuntu-22.04
+ if: github.event.pull_request.draft == false
+ needs: deps
+ steps:
+ - uses: actions/checkout@v3
+
+ - uses: actions/setup-node@v3
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: yarn
+
+ - name: Restore dependencies
+ uses: actions/cache/restore@v3
+ with:
+ path: |
+ ./node_modules
+ ./docs/node_modules
+ key: ${{ runner.os }}-yarn
+
+ - name: Lint markdown
+ run: yarn markdown:lint
+
+ markdown-linkcheck:
+ runs-on: ubuntu-22.04
+ needs: deps
+ if: github.event.pull_request.draft == false
+ steps:
+ - uses: actions/checkout@v3
+
+ - uses: actions/setup-node@v3
+ with:
+ node-version: ${{ env.NODE_VERSION }}
+ cache: yarn
+
+ - name: Restore dependencies
+ uses: actions/cache/restore@v3
+ with:
+ path: |
+ ./node_modules
+ ./docs/node_modules
+ key: ${{ runner.os }}-yarn
+
+ - name: Lint markdown
+ run: yarn markdown:linkcheck
+
+ rust_lint_fmt:
+ runs-on: ubuntu-22.04
+ if: github.event.pull_request.draft == false
+ defaults:
+ run:
+ working-directory: packages/rust-bindings
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v3
+ with:
+ submodules: 'recursive'
+
+ - name: Install formatter
+ run: |
+ rustup default ${{ env.RUST_FMT }}
+ rustup component add rustfmt
+
+ - name: Format
+ run: cargo fmt -- --color=always --check
+
+ rust_lint_clippy:
+ runs-on: ubuntu-22.04
+ needs: rust_lint_fmt
+ if: github.event.pull_request.draft == false
+ defaults:
+ run:
+ working-directory: packages/rust-bindings
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v3
+ with:
+ submodules: 'recursive'
+
+ - name: Install clippy
+ run: |
+ rustup default ${{ env.RUST_VERSION }}
+ rustup component add clippy
+
+ - uses: Swatinem/rust-cache@v2
+ with:
+ workspaces: |
+ packages/rust-bindings
+ deps/concordium-base/rust-src
+ deps/concordium-base/concordium-contracts-common
+
+ - name: Run clippy
+ run: cargo clippy --color=always --tests --benches -- -Dclippy::all
diff --git a/.gitignore b/.gitignore
index b69a29000..15646c335 100644
--- a/.gitignore
+++ b/.gitignore
@@ -21,7 +21,7 @@ dist
doc
# Auto generate files from the gRPC proto file
-grpc
+grpc-api
# Webpack cache
.webpack-cache
diff --git a/.markdown-linkcheck.json b/.markdown-linkcheck.json
index 84e981113..72dc9011a 100644
--- a/.markdown-linkcheck.json
+++ b/.markdown-linkcheck.json
@@ -1,7 +1,7 @@
{
- "ignorePatterns": [
- {
- "pattern": "classes/Common_GRPC_Client.ConcordiumGRPCClient.html"
- }
- ]
+ "ignorePatterns": [
+ {
+ "pattern": "classes/grpc.ConcordiumGRPCClient.html"
+ }
+ ]
}
diff --git a/.markdownlint.yaml b/.markdownlint.yaml
index d93ada531..f3f457cbc 100644
--- a/.markdownlint.yaml
+++ b/.markdownlint.yaml
@@ -59,25 +59,26 @@ MD012:
maximum: 1
# MD013/line-length - Line length
-MD013:
- # Number of characters
- line_length: 80
- # Number of characters for headings
- heading_line_length: 80
- # Number of characters for code blocks
- code_block_line_length: 80
- # Include code blocks
- code_blocks: false
- # Include tables
- tables: false
- # Include headings
- headings: false
- # Include headings
- headers: false
- # Strict length checking
- strict: false
- # Stern length checking
- stern: false
+MD013: false
+# MD013:
+# # Number of characters
+# line_length: 120
+# # Number of characters for headings
+# heading_line_length: 120
+# # Number of characters for code blocks
+# code_block_line_length: 120
+# # Include code blocks
+# code_blocks: false
+# # Include tables
+# tables: false
+# # Include headings
+# headings: false
+# # Include headings
+# headers: false
+# # Strict length checking
+# strict: false
+# # Stern length checking
+# stern: false
# MD014/commands-show-output - Dollar signs used before commands without showing output
MD014: true
@@ -167,9 +168,9 @@ MD035:
style: "consistent"
# MD036/no-emphasis-as-heading/no-emphasis-as-header - Emphasis used instead of a heading
-MD036:
+MD036: false
# Punctuation characters
- punctuation: ".,;:!?。,;:!?"
+ # punctuation: ".,;:!?。,;:!?"
# MD037/no-space-in-emphasis - Spaces inside emphasis markers
MD037: true
diff --git a/.prettierrc b/.prettierrc
new file mode 100644
index 000000000..8db60caac
--- /dev/null
+++ b/.prettierrc
@@ -0,0 +1,3 @@
+{
+ "singleQuote": true
+}
diff --git a/README.md b/README.md
index 83fb004e4..ca9bd7ec0 100644
--- a/README.md
+++ b/README.md
@@ -10,19 +10,16 @@ Wrappers for interacting with the Concordium node.
- [Concordium SDK for Javascript](#concordium-sdk-for-javascript)
- [Documentation](#documentation)
- [Packages](#packages)
- - [Nodejs package](#nodejs-package)
- - [Web package](#web-package)
- - [Common package](#common-package)
+ - [SDK package](#sdk-package)
- [Rust-bindings package](#rust-bindings-package)
+ - [Ccd-js-gen package](#ccd-js-gen-package)
- [Install/updating dependencies](#installupdating-dependencies)
- [MacOS arm64](#macos-arm64)
- [Build](#build)
- [Building for a release](#building-for-a-release)
- [Building for development](#building-for-development)
- [Making a new release](#making-a-new-release)
- - [common](#common)
- - [nodejs](#nodejs)
- - [web](#web)
+ - [SDK](#sdk)
- [rust-bindings](#rust-bindings)
- [Test](#test)
@@ -37,27 +34,21 @@ for more information
Contains the different packages for the JS-SDKs.
-### Nodejs package
+### SDK package
-The [Nodejs package](./packages/nodejs) contains the Nodejs SDK, particularly
-the client that wraps the GRPC calls to the node, is located here.
+The [SDK](./packages/sdk) contains the actual SDK, which can used in
+both a web and NodeJS environment.
-### Web package
-
-The [Web package](./packages/web) contains the Web SDK, which can used in
-a web environment.
-
-### Common package
+### Rust-bindings package
-The [common package](./packages/common) contains the shared library for the
-Nodejs and Web SDK's. The GRPC-client, all serialization and most utility
-functions are located in this package.
+The [rust-bindings](./packages/rust-bindings) contains bindings for Rust code,
+which is used by the SDK through WASM. This package is a utility package that
+should not be used directly, only through the usage of the SDK.
-### Rust-bindings package
+### Ccd-js-gen package
-The [common package](./packages/common) contains bindings for Rust code,
-which is used by the common package. This package is a utility package that
-should not be used directly, only through the usage of the common package.
+The [ccd-js-gen](./packages/ccd-js-gen) contains a library and CLI for
+generating smart contract clients for TypeScript and JavaScript.
## Install/updating dependencies
@@ -96,9 +87,6 @@ yarn build
This will build all the subprojects.
-Note that you must have [wasm-pack](https://rustwasm.github.io/wasm-pack/)
-installed to build the project.
-
### Building for development
To build the project quickly during development run
@@ -115,60 +103,26 @@ Note that this skips generating the grpc API and optimizing the wasm modules.
The following describes the requirements for creating a new release for
each of the packages contained in this repository.
-### common
+### SDK
-- Bump the version in [package.json](./packages/common/package.json).
-- Update the [CHANGELOG](./packages/common/CHANGELOG.md) describing the
+- Bump the version in [package.json](./packages/sdk/package.json).
+- Update the [CHANGELOG](./packages/sdk/CHANGELOG.md) describing the
changes made.
-- Update the dependency to common in the [web](./packages/web/package.json)
- and [nodejs](./packages/nodejs/package.json) packages.
-- Update the CHANGELOG in the [web](./packages/web/CHANGELOG.md) and
- [nodejs](./packages/nodejs/CHANGELOG.md) packages.
- - Add a change entry: Bumped @concordium/common-sdk to x.y.z.
- Commit and tag the release.
- - Tag should be `common/x.y.z`.
+ - Tag should be `sdk/x.y.z`.
- Run the deploy workflow.
- Under github actions, run the "deploy" workflow and download the
`build-release` artifact. Unpack this file and use it for the release.
- Publish the release to NPM.
- - From the common package directory (packages/common) run `yarn npm publish`
-
-### nodejs
-
-- Bump the version in [package.json](./packages/nodejs/package.json).
-- Update the [CHANGELOG](./packages/nodejs/CHANGELOG.md) describing the
- changes made.
-- Commit and tag the release.
- - Tag should be `nodejs/x.y.z`.
-- Build the release.
- - Under github actions, run the "deploy" workflow and download the
- `build-release` artifact. Unpack this file and use it for the release.
-- Publish the release to NPM.
- - From the nodejs package directory (packages/nodejs) run `yarn npm publish`
-
-### web
-
-- Bump the version in [package.json](./packages/web/package.json).
-- Update the [CHANGELOG](./packages/web/CHANGELOG.md) describing the
- changes made.
-- Commit and tag the release.
- - Tag should be `web/x.y.z`.
-- Build the release.
- - Under github actions, run the "deploy" workflow and download the
- `build-release` artifact. Unpack this file and use it for the release.
-- Publish the release to NPM.
- - From the web package directory (packages/web) run `yarn npm publish`
+ - From the sdk package directory (packages/sdk) run `yarn npm publish`
### rust-bindings
- Bump the version in [package.json](./packages/rust-bindings/package.json).
- Update the [CHANGELOG](./packages/rust-bindings/CHANGELOG.md) describing
the changes made.
-- Update the dependency to rust-bindings in the
- [common](./packages/common/package.json) and
- [web](./packages/web/package.json) packages.
-- Update the CHANGELOG in the [common](./packages/common/CHANGELOG.md) and
- [web](./packages/web/CHANGELOG.md) packages.
+- Update the dependency to rust-bindings in the [sdk](./packages/sdk/package.json)
+- Update the CHANGELOG in the [sdk](./packages/sdk/CHANGELOG.md)
- Add a change entry: Bumped @concordium/rust-bindings to x.y.z.
- Commit and tag the release.
- Tag should be `rust-bindings/x.y.z`.
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 000000000..042c9bed1
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,10 @@
+# docs
+
+Holds documentation to be built into the documentation generated by typedoc.
+Currently, this needs to use its own version of typescript due to incompatibility
+with the version used in the rest of the workspace.
+
+## Project structure
+
+Pages reside in the `./pages` folder, and should be included by adding
+a corresponding entry in `typedoc.json`.
diff --git a/docs/package.json b/docs/package.json
new file mode 100644
index 000000000..d905e50bd
--- /dev/null
+++ b/docs/package.json
@@ -0,0 +1,16 @@
+{
+ "name": "docs",
+ "packageManager": "yarn@3.2.1",
+ "private": true,
+ "scripts": {
+ "build:docs": "typedoc"
+ },
+ "devDependencies": {
+ "@knodes/typedoc-plugin-code-blocks": "^0.23.0",
+ "@knodes/typedoc-plugin-pages": "^0.23.0",
+ "typedoc": "^0.23",
+ "typedoc-plugin-merge-modules": "^4.0.1",
+ "typedoc-plugin-missing-exports": "^0.23",
+ "typescript": "5.0"
+ }
+}
diff --git a/pages/cis2-contracts.md b/docs/pages/cis2-contracts.md
similarity index 99%
rename from pages/cis2-contracts.md
rename to docs/pages/cis2-contracts.md
index b05a0e713..06d830406 100644
--- a/pages/cis2-contracts.md
+++ b/docs/pages/cis2-contracts.md
@@ -21,7 +21,7 @@ This document describes the helper class for working with CIS-2 contracts
## CIS2Contract
The CIS2Contract class wraps the
-[ConcordiumGRPCClient](../classes/Common_GRPC_Client.ConcordiumGRPCClient.html),
+[ConcordiumGRPCClient](../classes/grpc.ConcordiumGRPCClient.html),
defining an interface matching the [CIS-2
standard](https://proposals.concordium.software/CIS/cis-2.html).
diff --git a/docs/pages/documentation.md b/docs/pages/documentation.md
new file mode 100644
index 000000000..cbc916063
--- /dev/null
+++ b/docs/pages/documentation.md
@@ -0,0 +1,75 @@
+This is the documentation for the Concordium Javascript SDK. Here we cover
+the JS wrappers for interacting with the Concordium nodes.
+
+Most functionality is provideded by the
+[GRPC-Client](../classes/grpc.ConcordiumGRPCClient.html)
+however there exists additional helper functions, for example to help with
+creating {@page transactions.md transactions}, or {@page identity-proofs.md
+creating identity proof statements}, or {@page utility-functions.md general
+utility functions}.
+
+A good way to get started is to check out the {@page runnable-examples.md
+runnable examples}.
+
+To create a GRPC-Client for use with nodeJS:
+
+```ts
+ import { ConcordiumGRPCNodeClient, credentials } from '@concordium/web-sdk/nodejs';
+ ...
+ return new ConcordiumGRPCNodeClient(
+ address,
+ port,
+ credentials.createSsl(),
+ { timeout: 15000 }
+ );
+```
+
+To create a GRPC-Client for use in a browser (requires GRPC-web enabled on the node):
+
+```ts
+ import { ConcordiumGRPCWebClient } from '@concordium/web-sdk';
+ ...
+ return new ConcordiumGRPCWebClient(
+ address,
+ port,
+ { timeout: 15000 }
+ );
+```
+
+## Compatibility
+
+As of version 7, the SDK's are compatible only with environments
+respecting the `exports` field of a modules `package.json`, i.e. taking this into
+account when resolving modules. This means
+
+- NodeJS versions **16** and later.
+- Bundlers resolving modules by `package.json` `exports`.
+
+### Typescript
+
+Typescript has support for resolving modules through `exports` of `package.json`
+from versions
+
+- NodeJS -> Typescript version **4.7** and later with
+`compilerOptions.moduleResolution: "node16" // Or "nodenext"`.
+- Bundlers -> Typescript version **5.0** and later with
+`compilerOptions.moduleResolution: "bundler"`.
+
+### NodeJS
+
+The web-sdk is published as an ES module, and as such packages using it must
+also be ES modules.
+
+The easiest way to run your node application as an ES module, is by setting
+the `type` field of `package.json` to be set to `"module"`:
+
+```json
+{
+ ...
+ "type": "module",
+ ...
+}
+```
+
+Alternatively, files names with the extension `mjs` (or `mts` for TypeScript)
+are always handled as ES modules.
diff --git a/pages/identity-proofs.md b/docs/pages/identity-proofs.md
similarity index 100%
rename from pages/identity-proofs.md
rename to docs/pages/identity-proofs.md
diff --git a/pages/misc-pages/account-creation.md b/docs/pages/misc-pages/account-creation.md
similarity index 97%
rename from pages/misc-pages/account-creation.md
rename to docs/pages/misc-pages/account-creation.md
index f4aa390cb..99c4800ef 100644
--- a/pages/misc-pages/account-creation.md
+++ b/docs/pages/misc-pages/account-creation.md
@@ -98,11 +98,12 @@ using a seed:
// The address, that the account created by the transaction will get, can
// be derived ahead of time.
const accountAddress: AccountAddress = getAccountAddress(credentialDeploymentTransaction.unsignedCdi.credId);
+ const payload = serializeCredentialDeploymentPayload(signatures, credentialDeploymentTransaction);
// Send the transaction to the node
const success = await client.sendCredentialDeploymentTransaction(
- credentialDeploymentTransaction,
- signatures
+ payload,
+ expiry
);
if (success) {
// The node accepted the transaction. This does not ensure that the transaction
diff --git a/docs/pages/misc-pages/bundler-optimizations.md b/docs/pages/misc-pages/bundler-optimizations.md
new file mode 100644
index 000000000..4bffeee80
--- /dev/null
+++ b/docs/pages/misc-pages/bundler-optimizations.md
@@ -0,0 +1,61 @@
+## Optimizing bundled applications with async WASM
+
+As part of the logic of the SDK's is implemented in rust, some functionality
+requires WASM modules to be loaded. By default, this is embedded in a UMD
+to make it easy to use, however the recommended way to load WASM into the browser
+is to asynchronously load and initiate the module. To facilitate this, each
+WASM module exposes by `@concordium/rust-bindings` have a corresponding
+`bundler` entrypoint, which can be used by aliasing `@concordium/rust-bindings`
+as `@concordium/rust-bindings/bundler`. This does require some special handling
+by the bundler, which is why it's not the default.
+
+### Webpack 5
+
+The following example shows how to optimize the produced bundle of your
+application with **Webpack 5**.
+
+```ts
+// webpack.config.ts
+import { Configuration } from 'webpack';
+
+const config: Configuration = {
+ ..., // Other webpack configuration options.
+ resolve: {
+ ...,
+ alias: {
+ // Resolve bundler-specific wasm entrypoints.
+ '@concordium/rust-bindings': '@concordium/rust-bindings/bundler',
+ }
+ },
+ experiments: {
+ // Needed to handle bundler-specific wasm entrypoint
+ asyncWebAssembly: true
+ }
+};
+
+export default config;
+```
+
+### Vite
+
+The following example shows how to optimize the produced bundle of your
+application with **Vite**.
+
+```ts
+// vite.config.ts
+import { defineConfig } from 'vite';
+import wasm from "vite-plugin-wasm";
+import topLevelAwait from "vite-plugin-top-level-await";
+
+export default defineConfig({
+ plugins: [
+ wasm(),
+ topLevelAwait() // For compatibility with older browsers.
+ ],
+ resolve: {
+ alias: {
+ '@concordium/rust-bindings': '@concordium/rust-bindings/bundler', // Resolve bundler-specific wasm entrypoints.
+ }
+ }
+});
+```
diff --git a/pages/misc-pages/grpc-migration.md b/docs/pages/misc-pages/grpc-migration.md
similarity index 100%
rename from pages/misc-pages/grpc-migration.md
rename to docs/pages/misc-pages/grpc-migration.md
diff --git a/pages/misc-pages/grpc-v1.md b/docs/pages/misc-pages/grpc-v1.md
similarity index 99%
rename from pages/misc-pages/grpc-v1.md
rename to docs/pages/misc-pages/grpc-v1.md
index fde400114..1650f82af 100644
--- a/pages/misc-pages/grpc-v1.md
+++ b/docs/pages/misc-pages/grpc-v1.md
@@ -1,5 +1,5 @@
> :warning: **This explains behaviour of the deprecated v1 concordium client**:
-check out [the documentation the v2 client](../../classes/Common_GRPC_Client.ConcordiumGRPCClient.html)
+check out [the documentation the v2 client](../../classes/grpc.ConcordiumGRPCClient.html)
This describes the JSON-RPC client, which can interact with the [Concordium
JSON-RPC server](https://github.com/Concordium/concordium-json-rpc)
@@ -49,6 +49,8 @@ interface as the grpc v1 node client:
## GRPCv1-Client
+_Only accessible prior to version 7 of the web SDK (and in all versions of the deprecated nodejs SDK)_
+
The ConcordiumNodeClient defines the interface to be used to send and receive
data from a concordium-node.
diff --git a/docs/pages/misc-pages/upgrade-guide.md b/docs/pages/misc-pages/upgrade-guide.md
new file mode 100644
index 000000000..8a24613ef
--- /dev/null
+++ b/docs/pages/misc-pages/upgrade-guide.md
@@ -0,0 +1,157 @@
+## web SDK version 7
+
+Several types have been replaced with a module containing the type itself together with functions for constructing and
+converting the type:
+
+- `AccountAddress` is now a module with functions related to account addresses:
+ - To refer to `AccountAddress` as a type use `AccountAddress.Type`.
+ - Constructing `new AccountAddress("
")` is now `AccountAddress.fromBase58("")`.
+ - `isAlias` and `getAlias` are now accessable from `AccountAddress.isAlias` and `AccountAddress.getAlias`.
+- `ContractAddresss` is now a module with functions related to contract addresses:
+ - To refer to `ContractAddress` as a type use `ContractAddress.Type`.
+ - To construct the type use `ContractAddress.create(index, subindex)`.
+- `CredentialRegistrationId` is now a module with functions related to credential registration IDs:
+ - To refer to `CredentialRegistrationId` as a type use `CredentialRegistrationId.Type`.
+ - Constructing `new CredentialRegistrationId("")` is now
+ `CredentialRegistrationId.fromHexString("")`.
+- `Duration` is now a module with functions related to durations of time.
+ - To refer to `Duration` as a type use `Duration.Type`.
+- `Timestamp` is now a module with functions related to timestamps.
+ - To refer to `Timestamp` as a type use `Timestamp.Type`.
+
+The API now uses dedicated types instead of language primitives:
+
+- Uses `AccountAddress` instead of a string with base58 encoding.
+ Can be constructed using `AccountAddress.fromBase58('')`.
+- Uses `BlockHash` instead of a string with hex encoding.
+ Can be constructed using `BlockHash.fromHexString('')`.
+- Uses `TranactionHash` instead of a string with hex encoding.
+ Can be constructed using `TransactionHash.fromHexString('')`.
+- Uses `Energy` instead of a bigint.
+ Can be constructed using `Energy.create()`.
+- Uses `ReceiveName` instead of a string.
+ Can be constructed using `ReceiveName.fromString('.')`.
+- Uses `InitName` instead of a string.
+ Can be constructed using `Init.fromString('init_')`.
+- Uses `ContractName` instead of a string.
+ Can be constructed using `ContractName.fromString('')`.
+- Uses `EntrypointName` instead of a string.
+ Can be constructed using `EntrypointName.fromString('')`.
+- Uses `Parameter` instead of a string with hex encoding.
+ Can be constructed using `Parameter.fromHexString('')`.
+- Uses `SequenceNumber` (formerly called nonce) instead of a bigint.
+ Can be constructed using `SequenceNumber.create()`.
+- Uses `Timestamp` instead of a bigint.
+ Can be constructed using `Timestamp.fromMillis()`.
+- Uses `Duration` instead of a bigint.
+ Can be constructed using `Duration.fromMillis()`.
+
+The `@concordium/web-sdk` now requires bundlers to respect `exports` field of
+`package.json` of a module. This is due to relying on entrypoints declared in
+the `exports` field of `@concordium/rust-bindings` to make it possible to select
+only parts of the SDK to include in your application.
+Furthermore, the SDK is now published as an ES module, making it possible to
+eliminate dead code.
+
+For **TypeScript** users, at least typescript version 5 is required along with
+the setting `compilerOptions.moduleResultion` to `"bundler"` to match the
+resolution strategy of modern bundlers.
+
+The following entrypoints are made available for consumers of
+`@concordium/web-sdk`:
+
+- `@concordium/web-sdk` exposes the full API of the SDK.
+This can safely be used by projects built with ES modules.
+- `@concordium/web-sdk/cis0` entrypoint exposes functionality for working with
+contracts adhering to the
+[CIS-0](https://proposals.concordium.software/CIS/cis-0.html) standard.
+- `@concordium/web-sdk/cis2` entrypoint exposes functionality for working with
+contracts adhering to the
+[CIS-2](https://proposals.concordium.software/CIS/cis-2.html) standard.
+- `@concordium/web-sdk/cis4` entrypoint exposes functionality for working with
+contracts adhering to the
+[CIS-4](https://proposals.concordium.software/CIS/cis-4.html) standard.
+- `@concordium/web-sdk/grpc` entrypoint exposes the grpc client for interacting
+with a nodes GRPCv2 interface.
+- `@concordium/web-sdk/id` entrypoint exposes functionality for working with
+ID proofs.
+- `@concordium/web-sdk/json-rpc` entrypoint exposes the **(deprecated)**
+json-rpc client for interacting with a nodes GPRCv1 interface.
+- `@concordium/web-sdk/schema` entrypoint exposes functionality for working
+with smart contract schemas, i.e.(de)serializing types using a smart
+contract schema.
+ - This uses the wasm entrypoint at `@concordium/rust-bindings/dapp`.
+- `@concordium/web-sdk/types` entrypoint exposes functionality for working
+with concordium domain types.
+- `@concordium/web-sdk/wasm` entrypoint exposes a variety of functionality for
+working with concordium domain types, which requires WASM.
+ - This uses the wasm entrypoint at `@concorodium/rust-bindings/wallet`.
+- `@concordium/web-sdk/web3-id` entrypoint exposes functionality for working
+with web3-id proofs.
+
+### NodeJS
+
+_The `@concordium/node-sdk` has been removed in favor of unifying both web and
+nodejs SDK's in a single platform agnostic SDK. This means users of
+`@concordium/node-sdk` looking to upgrade, will need to install
+`@concordium/web-sdk` instead._
+
+The `@concordium/web-sdk` module is not compatible with
+node versions <16 and is published only as an ES module.
+This, in turn, requires users to also run applications as ES modules.
+
+The easiest way to run your node application as an ES module, is by setting
+the `type` field of `package.json` to be set to `"module"`:
+
+```json
+{
+ ...
+ "type": "module",
+ ...
+}
+```
+
+Alternatively, files names with the extension `mjs` (or `mts` for TypeScript)
+are always handled as ES modules.
+
+For **TypeScript** users, at least typescript version 4.7 is required along
+with the setting `compilerOptions.moduleResultion` to `"node16"` or
+`"nodenext"` to match the resolution strategy of node version 16 and later.
+
+## Common SDK version 5 to 6 (Web 2->3) (Node 5->6)
+
+Some classes and types have been renamed or changed, and should be update if used.
+
+### AccountTransactionType
+
+Some types in the AccountTransactionType enum have been changed to align
+with other languages.
+
+- InitializeSmartContractInstance -> InitContract
+- UpdateSmartContractInstance -> Update
+- SimpleTransfer -> Transfer
+- EncryptedTransfer -> EncryptedAmountTransfer
+- SimpleTransferWithMemo -> TransferWithMemo
+- EncryptedTransferWithMemo -> EncryptedAmountTransferWithMemo
+
+### GtuAmount
+
+The `GtuAmount` class has been renamed to `CcdAmount` to reflect the current
+name of token. If an object was used in place of a class instance, the field
+`microGtuAmount` should be renamed to `microCcdAmount`.
+
+### DeployModule
+
+The field `content` has been renamed to `source` to align with other languages.
+
+### UpdateConcractPayload
+
+Field names have been renamed to align with other languages. `contractAddress`
+field has been renamed to `address`. `parameter` field has been renamed to
+`message`.
+
+### InitContractPayload
+
+Field names have been renamed to align with other languages. `contractName`
+field has been renamed to `initName`. `parameter` field has been renamed to
+`params`.
diff --git a/pages/runnable-examples.md b/docs/pages/runnable-examples.md
similarity index 100%
rename from pages/runnable-examples.md
rename to docs/pages/runnable-examples.md
diff --git a/pages/transactions.md b/docs/pages/transactions.md
similarity index 100%
rename from pages/transactions.md
rename to docs/pages/transactions.md
diff --git a/pages/utility-functions.md b/docs/pages/utility-functions.md
similarity index 98%
rename from pages/utility-functions.md
rename to docs/pages/utility-functions.md
index a85303da6..3939d190f 100644
--- a/pages/utility-functions.md
+++ b/docs/pages/utility-functions.md
@@ -233,7 +233,7 @@ and does not give any guarantees for whether the contract adheres to the
standard it claims to implement. The function returns `undefined` if the
contract does not support CIS-0.
-This requires a [`ConcordiumGRPCClient`](../classes/Common_GRPC_Client.ConcordiumGRPCClient.html).
+This requires a [`ConcordiumGRPCClient`](../classes/grpc.ConcordiumGRPCClient.html).
```ts
const client = ...; // `ConcordiumGRPCClient`
diff --git a/docs/tsconfig.json b/docs/tsconfig.json
new file mode 100644
index 000000000..d92fe122c
--- /dev/null
+++ b/docs/tsconfig.json
@@ -0,0 +1,14 @@
+{
+ "extends": "../tsconfig.json",
+ "compilerOptions": {
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext"
+ },
+ "include": [
+ "../packages/**/*",
+ "./typedoc.config.cjs"
+ ],
+ "exclude": [
+ "../packages/ccd-js-gen/**/*"
+ ]
+}
diff --git a/docs/typedoc.config.cjs b/docs/typedoc.config.cjs
new file mode 100644
index 000000000..a7fd163ad
--- /dev/null
+++ b/docs/typedoc.config.cjs
@@ -0,0 +1,76 @@
+/* eslint-disable @typescript-eslint/no-var-requires */
+const path = require('node:path');
+
+module.exports = {
+ name: 'Concordium JS-SDK',
+ out: path.resolve(__dirname, '../typedoc'),
+ entryPointStrategy: 'expand',
+ entryPoints: [path.resolve(__dirname, '../packages/sdk/src/pub')],
+ tsconfig: path.resolve(__dirname, '../tsconfig.json'),
+ readme: path.resolve(__dirname, './pages/documentation.md'),
+ plugin: [
+ '@knodes/typedoc-plugin-code-blocks',
+ '@knodes/typedoc-plugin-pages',
+ 'typedoc-plugin-merge-modules',
+ ],
+ mergeModulesMergeMode: 'module',
+ pluginCodeBlocks: {
+ source: path.resolve(__dirname, '../examples'),
+ },
+ pluginPages: {
+ source: path.resolve(__dirname, './pages'),
+ pages: [
+ {
+ name: 'Concordium JS-SDK',
+ children: [
+ {
+ name: 'CIS2-Contracts',
+ source: 'cis2-contracts.md',
+ },
+ {
+ name: 'Identity Proofs',
+ source: 'identity-proofs.md',
+ },
+ {
+ name: 'Runnable Examples',
+ source: 'runnable-examples.md',
+ },
+ {
+ name: 'Transactions',
+ source: 'transactions.md',
+ },
+ {
+ name: 'Utility Functions',
+ source: 'utility-functions.md',
+ },
+ {
+ name: 'Miscellaneous Pages',
+ childrenDir: 'misc-pages',
+ children: [
+ {
+ name: 'Account Creation',
+ source: 'account-creation.md',
+ },
+ {
+ name: 'Optimizing bundled applications',
+ source: 'bundler-optimizations.md',
+ },
+ {
+ name: 'GRPCv1 to GRPCv2 Migration Guide',
+ source: 'grpc-migration.md',
+ },
+ {
+ name: 'Old GRPC-Client',
+ source: 'grpc-v1.md',
+ },
+ {
+ name: 'Upgrade Guide',
+ source: 'upgrade-guide.md',
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+};
diff --git a/examples/ccd-js-gen/wCCD/client-error-message.ts b/examples/ccd-js-gen/wCCD/client-error-message.ts
new file mode 100644
index 000000000..aeabebed7
--- /dev/null
+++ b/examples/ccd-js-gen/wCCD/client-error-message.ts
@@ -0,0 +1,107 @@
+import { credentials } from '@grpc/grpc-js';
+import * as SDK from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
+import meow from 'meow';
+import { parseEndpoint } from '../../shared/util.js';
+
+// The generated module could be imported directly like below,
+// but for this example it is imported dynamicly to improve
+// the error message when not generated.
+// import * as wCCDContractClient from './lib/cis2_wCCD';
+
+const cli = meow(
+ `
+ This example uses a generated smart contract client for the wCCD smart contract.
+
+ Usage
+ $ yarn run-example [options]
+
+ Required
+ --index, -i The index of the smart contract. Defaults to 2059, which is wCCD on testnet.
+
+ Options
+ --help, -h Displays this message
+ --endpoint, -e Specify endpoint of a grpc2 interface of a Concordium node in the format "://:". Defaults to 'http://localhost:20000'
+ --subindex, The subindex of the smart contract. Defaults to 0
+`,
+ {
+ importMeta: import.meta,
+ flags: {
+ endpoint: {
+ type: 'string',
+ alias: 'e',
+ default: 'http://localhost:20000',
+ },
+ index: {
+ type: 'number',
+ alias: 'i',
+ default: 2059,
+ },
+ subindex: {
+ type: 'number',
+ default: 0,
+ },
+ },
+ }
+);
+
+const [address, port, scheme] = parseEndpoint(cli.flags.endpoint);
+const grpcClient = new ConcordiumGRPCNodeClient(
+ address,
+ Number(port),
+ scheme === 'https' ? credentials.createSsl() : credentials.createInsecure()
+);
+
+const contractAddress = SDK.ContractAddress.create(
+ cli.flags.index,
+ cli.flags.subindex
+);
+
+(async () => {
+ // Importing the generated smart contract module client.
+ /* eslint-disable import/no-unresolved */
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+ // @ts-ignore
+ const wCCDContractClient = await import('./lib/wCCD_cis2_wCCD.js').catch(
+ (e) => {
+ /* eslint-enable import/no-unresolved */
+ console.error(
+ '\nFailed to load the generated wCCD module, did you run the `generate` script?\n'
+ );
+ throw e;
+ }
+ );
+
+ const wCCDTokenId = '';
+ const fromAddress = SDK.AccountAddress.fromBuffer(
+ new Uint8Array(32).fill(0)
+ );
+ const toAddress = SDK.AccountAddress.fromBuffer(new Uint8Array(32).fill(1));
+ const parameter = [
+ {
+ token_id: wCCDTokenId,
+ amount: 1000,
+ from: { type: 'Account', content: fromAddress },
+ to: { type: 'Account', content: toAddress },
+ data: '',
+ } as const,
+ ];
+ const contract = await wCCDContractClient.create(
+ grpcClient,
+ contractAddress
+ );
+
+ const unauthorizedInvoker = SDK.AccountAddress.fromBase58(
+ '357EYHqrmMiJBmUZTVG5FuaMq4soAhgtgz6XNEAJaXHW3NHaUf'
+ );
+
+ const result = await wCCDContractClient.dryRunTransfer(
+ contract,
+ parameter,
+ {
+ invoker: unauthorizedInvoker,
+ }
+ );
+ const errorMessage = wCCDContractClient.parseErrorMessageTransfer(result);
+ console.log('Transfer failed with error: ', errorMessage);
+})();
diff --git a/examples/ccd-js-gen/wCCD/client-events.ts b/examples/ccd-js-gen/wCCD/client-events.ts
new file mode 100644
index 000000000..9f156f42a
--- /dev/null
+++ b/examples/ccd-js-gen/wCCD/client-events.ts
@@ -0,0 +1,113 @@
+import { credentials } from '@grpc/grpc-js';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
+import * as SDK from '@concordium/web-sdk';
+import meow from 'meow';
+import { parseEndpoint } from '../../shared/util.js';
+
+// The generated module could be imported directly like below,
+// but for this example it is imported dynamicly to improve
+// the error message when not generated.
+// import * as wCCDContractClient from './lib/cis2_wCCD.js';
+
+const cli = meow(
+ `
+ This example uses a generated smart contract client for the wCCD smart contract to display events.
+
+ Usage
+ $ yarn run-example [options]
+
+ Required
+ --index, -i The index of the smart contract. Defaults to 2059, which is wCCD on testnet.
+
+ Options
+ --help, -h Displays this message
+ --endpoint, -e Specify endpoint of a grpc2 interface of a Concordium node in the format "://:". Defaults to 'http://localhost:20000'
+ --subindex, The subindex of the smart contract. Defaults to 0
+`,
+ {
+ importMeta: import.meta,
+ flags: {
+ endpoint: {
+ type: 'string',
+ alias: 'e',
+ default: 'http://localhost:20000',
+ },
+ index: {
+ type: 'number',
+ alias: 'i',
+ default: 2059,
+ },
+ subindex: {
+ type: 'number',
+ default: 0,
+ },
+ },
+ }
+);
+
+const [address, port, scheme] = parseEndpoint(cli.flags.endpoint);
+const grpcClient = new ConcordiumGRPCNodeClient(
+ address,
+ Number(port),
+ scheme === 'https' ? credentials.createSsl() : credentials.createInsecure()
+);
+
+const contractAddress = SDK.ContractAddress.create(
+ cli.flags.index,
+ cli.flags.subindex
+);
+
+(async () => {
+ // Importing the generated smart contract module client.
+ /* eslint-disable import/no-unresolved */
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+ // @ts-ignore
+ const wCCDContractClient = await import('./lib/wCCD_cis2_wCCD.js').catch(
+ (e) => {
+ /* eslint-enable import/no-unresolved */
+ console.error(
+ '\nFailed to load the generated wCCD module, did you run the `generate` script?\n'
+ );
+ throw e;
+ }
+ );
+
+ // The sender of the transaction, i.e the one updating an operator.
+ const senderAccount = SDK.AccountAddress.fromBase58(
+ '357EYHqrmMiJBmUZTVG5FuaMq4soAhgtgz6XNEAJaXHW3NHaUf'
+ );
+ // The parameter adding the wCCD contract as an operator of sender.
+ const parameter = [
+ {
+ update: { type: 'Add' },
+ operator: { type: 'Contract', content: contractAddress },
+ } as const,
+ ];
+
+ // The client for the wCCD contract
+ const contract = await wCCDContractClient.create(
+ grpcClient,
+ contractAddress
+ );
+
+ // Dry run the update of operator.
+ const result = await wCCDContractClient.dryRunUpdateOperator(
+ contract,
+ parameter,
+ { invoker: senderAccount }
+ );
+ if (result.tag !== 'success') {
+ throw new Error('Unexpected failure');
+ }
+ for (const traceEvent of result.events) {
+ if (
+ traceEvent.tag === SDK.TransactionEventTag.Updated ||
+ traceEvent.tag === SDK.TransactionEventTag.Interrupted
+ ) {
+ for (const contractEvent of traceEvent.events) {
+ const parsed = wCCDContractClient.parseEvent(contractEvent);
+ console.log(parsed);
+ }
+ }
+ }
+})();
diff --git a/examples/ccd-js-gen/wCCD/client-tokenMetadata.ts b/examples/ccd-js-gen/wCCD/client-tokenMetadata.ts
index 6692991b3..262321ff4 100644
--- a/examples/ccd-js-gen/wCCD/client-tokenMetadata.ts
+++ b/examples/ccd-js-gen/wCCD/client-tokenMetadata.ts
@@ -1,12 +1,13 @@
import { credentials } from '@grpc/grpc-js';
-import * as SDK from '@concordium/node-sdk';
+import * as SDK from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import meow from 'meow';
-import { parseEndpoint } from '../../shared/util';
+import { parseEndpoint } from '../../shared/util.js';
// The generated module could be imported directly like below,
// but for this example it is imported dynamicly to improve
// the error message when not generated.
-// import * as wCCDModule from './lib/wCCD';
+// import * as wCCDContractClient from './lib/cis2_wCCD';
const cli = meow(
`
@@ -45,33 +46,47 @@ const cli = meow(
);
const [address, port, scheme] = parseEndpoint(cli.flags.endpoint);
-const grpcClient = SDK.createConcordiumClient(
+const grpcClient = new ConcordiumGRPCNodeClient(
address,
Number(port),
scheme === 'https' ? credentials.createSsl() : credentials.createInsecure()
);
-const contractAddress: SDK.ContractAddress = {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
-};
+const contractAddress = SDK.ContractAddress.create(
+ cli.flags.index,
+ cli.flags.subindex
+);
(async () => {
// Importing the generated smart contract module client.
/* eslint-disable import/no-unresolved */
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
- const wCCDModule = await import('./lib/wCCD').catch((e) => {
- /* eslint-enable import/no-unresolved */
- console.error(
- '\nFailed to load the generated wCCD module, did you run the `generate` script?\n'
- );
- throw e;
- });
+ const wCCDContractClient = await import('./lib/wCCD_cis2_wCCD.js').catch(
+ (e) => {
+ /* eslint-enable import/no-unresolved */
+ console.error(
+ '\nFailed to load the generated wCCD module, did you run the `generate` script?\n'
+ );
+ throw e;
+ }
+ );
- const parameter = '010000'; // First 2 bytes for number of tokens to query, 1 byte for the token ID.
- const contract = new wCCDModule.Cis2WCCD(grpcClient, contractAddress);
+ const wCCDTokenId = '';
+ const parameter = [wCCDTokenId];
+ const contract = await wCCDContractClient.create(
+ grpcClient,
+ contractAddress
+ );
- const responseHex = await contract.dryRun.tokenMetadata(parameter);
- console.log({ responseHex });
+ const result = await wCCDContractClient.dryRunTokenMetadata(
+ contract,
+ parameter
+ );
+ const returnValue =
+ wCCDContractClient.parseReturnValueTokenMetadata(result);
+ console.log(
+ 'The token metadata for wCCD can be found at: ',
+ returnValue?.[0].url
+ );
})();
diff --git a/examples/ccd-js-gen/wCCD/generate.ts b/examples/ccd-js-gen/wCCD/generate.ts
index b7c621192..41ff7529a 100644
--- a/examples/ccd-js-gen/wCCD/generate.ts
+++ b/examples/ccd-js-gen/wCCD/generate.ts
@@ -1,10 +1,11 @@
import { credentials } from '@grpc/grpc-js';
-import * as SDK from '@concordium/node-sdk';
+import * as SDK from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import * as Gen from '@concordium/ccd-js-gen';
import * as Path from 'node:path';
import * as Url from 'node:url';
import meow from 'meow';
-import { parseEndpoint } from '../../shared/util';
+import { parseEndpoint } from '../../shared/util.js';
const cli = meow(
`
@@ -13,13 +14,9 @@ const cli = meow(
Usage
$ yarn run-example [options]
- Required
- --index, -i The index of the smart contract. Defaults to 2059, which is wCCD on Testnet.
-
Options
--help, -h Displays this message
--endpoint, -e Specify endpoint of a grpc2 interface of a Concordium node in the format "address:port". Defaults to 'localhost:20000'
- --subindex, The subindex of the smart contract. Defaults to 0
`,
{
importMeta: import.meta,
@@ -29,39 +26,26 @@ const cli = meow(
alias: 'e',
default: 'localhost:20000',
},
- index: {
- type: 'number',
- alias: 'i',
- isRequired: true,
- default: 2059,
- },
- subindex: {
- type: 'number',
- default: 0,
- },
},
}
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const grpcClient = SDK.createConcordiumClient(
+const grpcClient = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
);
-const contractAddress: SDK.ContractAddress = {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
-};
+const wCCDModuleRef = SDK.ModuleReference.fromHexString(
+ 'cc285180b45d7695db75c29dee004d2e81a1383880c9b122399bea809196c98f'
+);
(async () => {
- console.info(`Fetching instance information for ${contractAddress.index}.`);
- const info = await grpcClient.getInstanceInfo(contractAddress);
console.info(
- `Fetching smart contract module source with reference '${info.sourceModule.moduleRef}'.`
+ `Fetching smart contract module source with reference '${wCCDModuleRef.moduleRef}'.`
);
- const moduleSource = await grpcClient.getModuleSource(info.sourceModule);
+ const moduleSource = await grpcClient.getModuleSource(wCCDModuleRef);
const filePath = Url.fileURLToPath(import.meta.url);
const outDir = Path.join(Path.dirname(filePath), 'lib');
console.info(`Generating smart contract module client at '${outDir}'.`);
diff --git a/examples/cis2/balanceOf.ts b/examples/cis2/balanceOf.ts
index 85a5ee13d..ab41b19db 100644
--- a/examples/cis2/balanceOf.ts
+++ b/examples/cis2/balanceOf.ts
@@ -1,7 +1,8 @@
-import { createConcordiumClient, CIS2Contract } from '@concordium/node-sdk';
+import { CIS2Contract, ContractAddress } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
-import { parseAddress, parseEndpoint } from '../shared/util';
+import { parseAddress, parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -50,17 +51,17 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
);
(async () => {
- const contract = await CIS2Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS2Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const accountBalance = await contract.balanceOf({
address: parseAddress(cli.flags.address),
diff --git a/examples/cis2/dryRun.transfer.ts b/examples/cis2/dryRun.transfer.ts
index 36abb7ce5..258993f14 100644
--- a/examples/cis2/dryRun.transfer.ts
+++ b/examples/cis2/dryRun.transfer.ts
@@ -1,11 +1,14 @@
import {
- createConcordiumClient,
CIS2,
CIS2Contract,
-} from '@concordium/node-sdk';
+ ContractAddress,
+ AccountAddress,
+ EntrypointName,
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
-import { parseAddress, parseEndpoint } from '../shared/util';
+import { parseAddress, parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -67,28 +70,29 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
);
(async () => {
- const contract = await CIS2Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS2Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const tokenId = cli.flags.tokenId;
- const from = cli.flags.from;
+ const from = AccountAddress.fromBase58(cli.flags.from);
const toAddress = parseAddress(cli.flags.to);
- const to: CIS2.Receiver =
- typeof toAddress === 'string'
- ? toAddress
- : {
- address: toAddress,
- hookName: cli.flags.receiveHookName ?? '',
- };
+ const to: CIS2.Receiver = AccountAddress.instanceOf(toAddress)
+ ? toAddress
+ : {
+ address: toAddress,
+ hookName: EntrypointName.fromString(
+ cli.flags.receiveHookName ?? ''
+ ),
+ };
const result = await contract.dryRun.transfer(from, {
from,
diff --git a/examples/cis2/dryRun.updateOperator.ts b/examples/cis2/dryRun.updateOperator.ts
index 17e216d63..54412ae06 100644
--- a/examples/cis2/dryRun.updateOperator.ts
+++ b/examples/cis2/dryRun.updateOperator.ts
@@ -1,7 +1,8 @@
-import { createConcordiumClient, CIS2Contract } from '@concordium/node-sdk';
+import { CIS2Contract, ContractAddress } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
-import { parseAddress, parseEndpoint } from '../shared/util';
+import { parseAddress, parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -50,17 +51,17 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
);
(async () => {
- const contract = await CIS2Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS2Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const owner = parseAddress(cli.flags.owner);
const address = parseAddress(cli.flags.address);
diff --git a/examples/cis2/operatorOf.ts b/examples/cis2/operatorOf.ts
index 023dd8a11..186f1fa6d 100644
--- a/examples/cis2/operatorOf.ts
+++ b/examples/cis2/operatorOf.ts
@@ -1,7 +1,8 @@
-import { createConcordiumClient, CIS2Contract } from '@concordium/node-sdk';
+import { CIS2Contract, ContractAddress } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
-import { parseAddress, parseEndpoint } from '../shared/util';
+import { parseAddress, parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -50,17 +51,17 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
);
(async () => {
- const contract = await CIS2Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS2Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const owner = parseAddress(cli.flags.owner);
const address = parseAddress(cli.flags.address);
diff --git a/examples/cis2/tokenMetadata.ts b/examples/cis2/tokenMetadata.ts
index 8d6220603..dbfad7221 100644
--- a/examples/cis2/tokenMetadata.ts
+++ b/examples/cis2/tokenMetadata.ts
@@ -1,6 +1,8 @@
-import { createConcordiumClient, CIS2Contract } from '@concordium/node-sdk';
+import { CIS2Contract, ContractAddress } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
+import fetch from 'node-fetch';
const cli = meow(
`
@@ -43,7 +45,7 @@ const cli = meow(
);
const [address, port] = cli.flags.endpoint.split(':');
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -54,10 +56,10 @@ if (cli.flags.h) {
}
(async () => {
- const contract = await CIS2Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS2Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const url = await contract.tokenMetadata(cli.flags.tokenId);
console.log('url object:', url);
diff --git a/examples/cis2/transfer.ts b/examples/cis2/transfer.ts
index 43c591fe6..3a6ced7c9 100644
--- a/examples/cis2/transfer.ts
+++ b/examples/cis2/transfer.ts
@@ -1,12 +1,16 @@
import {
- createConcordiumClient,
CIS2,
CIS2Contract,
buildBasicAccountSigner,
-} from '@concordium/node-sdk';
+ ContractAddress,
+ AccountAddress,
+ EntrypointName,
+ Energy,
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
-import { parseAddress, parseEndpoint } from '../shared/util';
+import { parseAddress, parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -74,34 +78,35 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
);
(async () => {
- const contract = await CIS2Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS2Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const signer = buildBasicAccountSigner(cli.flags.privateKey);
const tokenId = cli.flags.tokenId;
- const from = cli.flags.from;
+ const from = AccountAddress.fromBase58(cli.flags.from);
const toAddress = parseAddress(cli.flags.to);
- const to: CIS2.Receiver =
- typeof toAddress === 'string'
- ? toAddress
- : {
- address: toAddress,
- hookName: cli.flags.receiveHookName ?? '',
- };
+ const to: CIS2.Receiver = AccountAddress.instanceOf(toAddress)
+ ? toAddress
+ : {
+ address: toAddress,
+ hookName: EntrypointName.fromString(
+ cli.flags.receiveHookName ?? ''
+ ),
+ };
const txHash = await contract.transfer(
{
senderAddress: from,
- energy: 10000n,
+ energy: Energy.create(10000),
},
{
from,
diff --git a/examples/cis2/updateOperator.ts b/examples/cis2/updateOperator.ts
index dd762e6ec..e599b5b31 100644
--- a/examples/cis2/updateOperator.ts
+++ b/examples/cis2/updateOperator.ts
@@ -1,11 +1,14 @@
import {
- createConcordiumClient,
CIS2Contract,
buildBasicAccountSigner,
-} from '@concordium/node-sdk';
+ ContractAddress,
+ AccountAddress,
+ Energy,
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
-import { parseAddress, parseEndpoint } from '../shared/util';
+import { parseAddress, parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -64,26 +67,26 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
);
(async () => {
- const contract = await CIS2Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS2Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const signer = buildBasicAccountSigner(cli.flags.privateKey);
- const owner = cli.flags.owner;
+ const owner = AccountAddress.fromBase58(cli.flags.owner);
const address = parseAddress(cli.flags.address);
const txHash = await contract.updateOperator(
{
senderAddress: owner,
- energy: 10000n,
+ energy: Energy.create(10000),
},
{
type: cli.flags.updateType as 'add' | 'remove',
diff --git a/examples/cis4/credentialEntry.ts b/examples/cis4/credentialEntry.ts
index 5fc208235..8378ccea4 100644
--- a/examples/cis4/credentialEntry.ts
+++ b/examples/cis4/credentialEntry.ts
@@ -1,8 +1,9 @@
import meow from 'meow';
import { credentials } from '@grpc/grpc-js';
-import { CIS4Contract, createConcordiumClient } from '@concordium/node-sdk';
-import { parseEndpoint } from '../shared/util';
+import { CIS4Contract, ContractAddress } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
+import { parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -45,17 +46,17 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
);
(async () => {
- const contract = await CIS4Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS4Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const credentialEntry = await contract.credentialEntry(cli.flags.credId);
console.log('Credential entry:', credentialEntry);
diff --git a/examples/cis4/credentialStatus.ts b/examples/cis4/credentialStatus.ts
index a681a7d1d..c159dbef5 100644
--- a/examples/cis4/credentialStatus.ts
+++ b/examples/cis4/credentialStatus.ts
@@ -1,12 +1,9 @@
import meow from 'meow';
import { credentials } from '@grpc/grpc-js';
-import {
- CIS4,
- CIS4Contract,
- createConcordiumClient,
-} from '@concordium/node-sdk';
-import { parseEndpoint } from '../shared/util';
+import { CIS4, CIS4Contract, ContractAddress } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
+import { parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -49,17 +46,17 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
);
(async () => {
- const contract = await CIS4Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS4Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const credentialStatus = await contract.credentialStatus(cli.flags.credId);
diff --git a/examples/cis4/issuer.ts b/examples/cis4/issuer.ts
index e17719a88..097faa4b5 100644
--- a/examples/cis4/issuer.ts
+++ b/examples/cis4/issuer.ts
@@ -1,8 +1,9 @@
import meow from 'meow';
import { credentials } from '@grpc/grpc-js';
-import { CIS4Contract, createConcordiumClient } from '@concordium/node-sdk';
-import { parseEndpoint } from '../shared/util';
+import { CIS4Contract, ContractAddress } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
+import { parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -39,17 +40,17 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
);
(async () => {
- const contract = await CIS4Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS4Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const issuer = await contract.issuer();
console.log('Issuer public key:', issuer);
diff --git a/examples/cis4/registerCredential.ts b/examples/cis4/registerCredential.ts
index 1978ff54b..0d1a64811 100644
--- a/examples/cis4/registerCredential.ts
+++ b/examples/cis4/registerCredential.ts
@@ -2,17 +2,21 @@ import fs from 'fs';
import path from 'path';
import meow from 'meow';
import { credentials } from '@grpc/grpc-js';
-import * as ed25519 from '@noble/ed25519';
+import * as ed25519 from '#ed25519';
import {
+ AccountAddress,
buildAccountSigner,
CIS4,
CIS4Contract,
- createConcordiumClient,
+ ContractAddress,
+ Energy,
HexString,
parseWallet,
-} from '@concordium/node-sdk';
-import { parseEndpoint } from '../shared/util';
+ Timestamp,
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
+import { parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -78,7 +82,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -92,15 +96,15 @@ const wallet = parseWallet(walletFile);
const signer = buildAccountSigner(wallet);
(async () => {
- const contract = await CIS4Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS4Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
let holderPubKey: HexString;
if (!cli.flags.holderPubKey) {
const prv = ed25519.utils.randomPrivateKey();
- const pub = Buffer.from(await ed25519.getPublicKey(prv)).toString(
+ const pub = Buffer.from(await ed25519.getPublicKeyAsync(prv)).toString(
'hex'
);
@@ -121,16 +125,19 @@ const signer = buildAccountSigner(wallet);
const credential: CIS4.CredentialInfo = {
holderPubKey,
holderRevocable: cli.flags.holderRevoke,
- validFrom,
- validUntil,
+ validFrom: Timestamp.fromDate(validFrom),
+ validUntil:
+ validUntil === undefined
+ ? undefined
+ : Timestamp.fromDate(validUntil),
metadataUrl: { url: cli.flags.metadataUrl },
};
const txHash = await contract.registerCredential(
signer,
{
- senderAddress: wallet.value.address,
- energy: 10000n,
+ senderAddress: AccountAddress.fromBase58(wallet.value.address),
+ energy: Energy.create(10000),
},
credential,
cli.flags.data
diff --git a/examples/cis4/registerRevocationKeys.ts b/examples/cis4/registerRevocationKeys.ts
index 24432eb43..c7c780cb2 100644
--- a/examples/cis4/registerRevocationKeys.ts
+++ b/examples/cis4/registerRevocationKeys.ts
@@ -1,17 +1,20 @@
import fs from 'fs';
import path from 'path';
import meow from 'meow';
-import * as ed25519 from '@noble/ed25519';
+import * as ed25519 from '#ed25519';
import { credentials } from '@grpc/grpc-js';
import {
+ AccountAddress,
buildAccountSigner,
CIS4Contract,
- createConcordiumClient,
+ ContractAddress,
+ Energy,
HexString,
parseWallet,
-} from '@concordium/node-sdk';
-import { parseEndpoint } from '../shared/util';
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
+import { parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -63,7 +66,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -77,15 +80,15 @@ const wallet = parseWallet(walletFile);
const signer = buildAccountSigner(wallet);
(async () => {
- const contract = await CIS4Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS4Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
let keys: HexString[] = cli.flags.keys ?? [];
if (!cli.flags.keys?.length) {
const prv = ed25519.utils.randomPrivateKey();
- const pub = Buffer.from(await ed25519.getPublicKey(prv)).toString(
+ const pub = Buffer.from(await ed25519.getPublicKeyAsync(prv)).toString(
'hex'
);
@@ -99,8 +102,8 @@ const signer = buildAccountSigner(wallet);
const txHash = await contract.registerRevocationKeys(
signer,
{
- senderAddress: wallet.value.address,
- energy: 10000n,
+ senderAddress: AccountAddress.fromBase58(wallet.value.address),
+ energy: Energy.create(10000),
},
keys,
cli.flags.data
diff --git a/examples/cis4/registryMetadata.ts b/examples/cis4/registryMetadata.ts
index 1fbb735f5..0bec48350 100644
--- a/examples/cis4/registryMetadata.ts
+++ b/examples/cis4/registryMetadata.ts
@@ -1,8 +1,9 @@
import meow from 'meow';
import { credentials } from '@grpc/grpc-js';
-import { CIS4Contract, createConcordiumClient } from '@concordium/node-sdk';
-import { parseEndpoint } from '../shared/util';
+import { CIS4Contract, ContractAddress } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
+import { parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -39,17 +40,17 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
);
(async () => {
- const contract = await CIS4Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS4Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const metadata = await contract.registryMetadata();
console.log('Metadata:', metadata);
diff --git a/examples/cis4/removeRevocationKeys.ts b/examples/cis4/removeRevocationKeys.ts
index a6b433506..c23e66030 100644
--- a/examples/cis4/removeRevocationKeys.ts
+++ b/examples/cis4/removeRevocationKeys.ts
@@ -4,12 +4,15 @@ import meow from 'meow';
import { credentials } from '@grpc/grpc-js';
import {
+ AccountAddress,
buildAccountSigner,
CIS4Contract,
- createConcordiumClient,
+ ContractAddress,
+ Energy,
parseWallet,
-} from '@concordium/node-sdk';
-import { parseEndpoint } from '../shared/util';
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
+import { parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -62,7 +65,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -76,16 +79,16 @@ const wallet = parseWallet(walletFile);
const signer = buildAccountSigner(wallet);
(async () => {
- const contract = await CIS4Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS4Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const txHash = await contract.removeRevocationKeys(
signer,
{
- senderAddress: wallet.value.address,
- energy: 10000n,
+ senderAddress: AccountAddress.fromBase58(wallet.value.address),
+ energy: Energy.create(10000),
},
cli.flags.keys,
cli.flags.data
diff --git a/examples/cis4/revocationKeys.ts b/examples/cis4/revocationKeys.ts
index 57437b05f..6c3971157 100644
--- a/examples/cis4/revocationKeys.ts
+++ b/examples/cis4/revocationKeys.ts
@@ -1,8 +1,9 @@
import meow from 'meow';
import { credentials } from '@grpc/grpc-js';
-import { CIS4Contract, createConcordiumClient } from '@concordium/node-sdk';
-import { parseEndpoint } from '../shared/util';
+import { CIS4Contract, ContractAddress } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
+import { parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -39,17 +40,17 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
);
(async () => {
- const contract = await CIS4Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS4Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const keys = await contract.revocationKeys();
console.log('Revocation keys:', keys);
diff --git a/examples/cis4/revokeCredentialAsHolder.ts b/examples/cis4/revokeCredentialAsHolder.ts
index c28090cf0..aa2577588 100644
--- a/examples/cis4/revokeCredentialAsHolder.ts
+++ b/examples/cis4/revokeCredentialAsHolder.ts
@@ -4,13 +4,16 @@ import meow from 'meow';
import { credentials } from '@grpc/grpc-js';
import {
+ AccountAddress,
buildAccountSigner,
CIS4Contract,
- createConcordiumClient,
+ ContractAddress,
+ Energy,
parseWallet,
Web3IdSigner,
-} from '@concordium/node-sdk';
-import { parseEndpoint } from '../shared/util';
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
+import { parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -71,7 +74,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -85,18 +88,18 @@ const wallet = parseWallet(walletFile);
const signer = buildAccountSigner(wallet);
(async () => {
- const contract = await CIS4Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS4Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const hSigner = await Web3IdSigner.from(cli.flags.holderPrivateKey);
const nonce = BigInt(cli.flags.nonce);
const txHash = await contract.revokeCredentialAsHolder(
signer,
{
- senderAddress: wallet.value.address,
- energy: 10000n,
+ senderAddress: AccountAddress.fromBase58(wallet.value.address),
+ energy: Energy.create(10000),
},
hSigner,
nonce,
diff --git a/examples/cis4/revokeCredentialAsIssuer.ts b/examples/cis4/revokeCredentialAsIssuer.ts
index f5c1c9939..fc56bdbdc 100644
--- a/examples/cis4/revokeCredentialAsIssuer.ts
+++ b/examples/cis4/revokeCredentialAsIssuer.ts
@@ -4,12 +4,15 @@ import meow from 'meow';
import { credentials } from '@grpc/grpc-js';
import {
+ AccountAddress,
buildAccountSigner,
CIS4Contract,
- createConcordiumClient,
+ ContractAddress,
+ Energy,
parseWallet,
-} from '@concordium/node-sdk';
-import { parseEndpoint } from '../shared/util';
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
+import { parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -66,7 +69,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -80,16 +83,16 @@ const wallet = parseWallet(walletFile);
const signer = buildAccountSigner(wallet);
(async () => {
- const contract = await CIS4Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS4Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const txHash = await contract.revokeCredentialAsIssuer(
signer,
{
- senderAddress: wallet.value.address,
- energy: 10000n,
+ senderAddress: AccountAddress.fromBase58(wallet.value.address),
+ energy: Energy.create(10000),
},
cli.flags.credId,
cli.flags.reason,
diff --git a/examples/cis4/revokeCredentialAsOther.ts b/examples/cis4/revokeCredentialAsOther.ts
index ac4e7d351..07769b379 100644
--- a/examples/cis4/revokeCredentialAsOther.ts
+++ b/examples/cis4/revokeCredentialAsOther.ts
@@ -4,13 +4,16 @@ import meow from 'meow';
import { credentials } from '@grpc/grpc-js';
import {
+ AccountAddress,
buildAccountSigner,
CIS4Contract,
- createConcordiumClient,
+ ContractAddress,
+ Energy,
parseWallet,
Web3IdSigner,
-} from '@concordium/node-sdk';
-import { parseEndpoint } from '../shared/util';
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
+import { parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -77,7 +80,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -91,18 +94,18 @@ const wallet = parseWallet(walletFile);
const signer = buildAccountSigner(wallet);
(async () => {
- const contract = await CIS4Contract.create(client, {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contract = await CIS4Contract.create(
+ client,
+ ContractAddress.create(cli.flags.index, cli.flags.subindex)
+ );
const rSigner = await Web3IdSigner.from(cli.flags.revokerPrivateKey);
const nonce = BigInt(cli.flags.nonce);
const txHash = await contract.revokeCredentialAsOther(
signer,
{
- senderAddress: wallet.value.address,
- energy: 10000n,
+ senderAddress: AccountAddress.fromBase58(wallet.value.address),
+ energy: Energy.create(10000),
},
rSigner,
cli.flags.credId,
diff --git a/examples/client/banPeer.ts b/examples/client/banPeer.ts
index 73bacd71b..27cb9dca1 100644
--- a/examples/client/banPeer.ts
+++ b/examples/client/banPeer.ts
@@ -1,5 +1,5 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -35,7 +35,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/dumpStart.ts b/examples/client/dumpStart.ts
index 41db83030..0b3ebe173 100644
--- a/examples/client/dumpStart.ts
+++ b/examples/client/dumpStart.ts
@@ -1,5 +1,5 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -41,7 +41,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/dumpStop.ts b/examples/client/dumpStop.ts
index 5c2e97c54..0dffb33e4 100644
--- a/examples/client/dumpStop.ts
+++ b/examples/client/dumpStop.ts
@@ -1,5 +1,5 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -27,7 +27,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/findFirstFinalizedBlockNoLaterThan.ts b/examples/client/findFirstFinalizedBlockNoLaterThan.ts
index b28111268..b9b9035b3 100644
--- a/examples/client/findFirstFinalizedBlockNoLaterThan.ts
+++ b/examples/client/findFirstFinalizedBlockNoLaterThan.ts
@@ -1,5 +1,5 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -42,7 +42,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/findFirstNonGenesisAccount.ts b/examples/client/findFirstNonGenesisAccount.ts
index 80695f553..b4149fe6d 100644
--- a/examples/client/findFirstNonGenesisAccount.ts
+++ b/examples/client/findFirstNonGenesisAccount.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, streamToList } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { streamToList } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -34,7 +35,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/findInstanceCreation.ts b/examples/client/findInstanceCreation.ts
index 13dd290b8..06449ed0b 100644
--- a/examples/client/findInstanceCreation.ts
+++ b/examples/client/findInstanceCreation.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { ContractAddress, createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ContractAddress } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -47,7 +48,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -63,10 +64,7 @@ const client = createConcordiumClient(
cli.flags.from !== undefined ? BigInt(cli.flags.from) : undefined;
const to =
cli.flags.from !== undefined ? BigInt(cli.flags.from) : undefined;
- const address: ContractAddress = {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- };
+ const address = ContractAddress.create(cli.flags.index, cli.flags.subindex);
const instanceCreation = await client.findInstanceCreation(
address,
from,
diff --git a/examples/client/getAccountInfo.ts b/examples/client/getAccountInfo.ts
index 93bced81b..575371382 100644
--- a/examples/client/getAccountInfo.ts
+++ b/examples/client/getAccountInfo.ts
@@ -1,10 +1,11 @@
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import {
AccountAddress,
AccountInfo,
- createConcordiumClient,
- isDelegatorAccount,
-} from '@concordium/node-sdk';
+ AccountInfoType,
+ BlockHash,
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -45,7 +46,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -61,17 +62,21 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const accountAddress = new AccountAddress(cli.flags.account);
+ const accountAddress = AccountAddress.fromBase58(cli.flags.account);
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const accountInfo: AccountInfo = await client.getAccountInfo(
accountAddress,
- cli.flags.block
+ blockHash
);
console.log('Account balance:', accountInfo.accountAmount);
console.log('Account address:', accountInfo.accountAddress);
// If the account is a delegator print delegator information
- if (isDelegatorAccount(accountInfo)) {
+ if (accountInfo.type === AccountInfoType.Delegator) {
console.log(
'Delegated stake amount:',
accountInfo.accountDelegation.stakedAmount
diff --git a/examples/client/getAccountList.ts b/examples/client/getAccountList.ts
index a013bfb1f..a0cf49390 100644
--- a/examples/client/getAccountList.ts
+++ b/examples/client/getAccountList.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, Base58String } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, AccountAddress } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -32,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -48,13 +49,16 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const accounts: AsyncIterable = client.getAccountList(
- cli.flags.block
- );
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
+ const accounts: AsyncIterable =
+ client.getAccountList(blockHash);
// #endregion documentation-snippet
console.log('Accounts that exists at the end of the given block:');
for await (const account of accounts) {
- console.log(account);
+ console.log(AccountAddress.toBase58(account));
}
})();
diff --git a/examples/client/getAccountNonFinalizedTransactions.ts b/examples/client/getAccountNonFinalizedTransactions.ts
index 65c430504..6d17c3f3a 100644
--- a/examples/client/getAccountNonFinalizedTransactions.ts
+++ b/examples/client/getAccountNonFinalizedTransactions.ts
@@ -1,9 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- AccountAddress,
- createConcordiumClient,
- HexString,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { AccountAddress, TransactionHash } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -39,7 +36,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -57,8 +54,8 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const accountAddress = new AccountAddress(cli.flags.account);
- const transactions: AsyncIterable =
+ const accountAddress = AccountAddress.fromBase58(cli.flags.account);
+ const transactions: AsyncIterable =
client.getAccountNonFinalizedTransactions(accountAddress);
// #endregion documentation-snippet
diff --git a/examples/client/getAncestors.ts b/examples/client/getAncestors.ts
index 1b5849ccd..02efc5b2e 100644
--- a/examples/client/getAncestors.ts
+++ b/examples/client/getAncestors.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, HexString } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -40,7 +41,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -58,9 +59,13 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const ancestors: AsyncIterable = client.getAncestors(
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
+ const ancestors: AsyncIterable = client.getAncestors(
BigInt(cli.flags.maxAncestors),
- cli.flags.block
+ blockHash
);
// #endregion documentation-snippet
diff --git a/examples/client/getAnonymityRevokers.ts b/examples/client/getAnonymityRevokers.ts
index c67f0ab3b..e3adcb6df 100644
--- a/examples/client/getAnonymityRevokers.ts
+++ b/examples/client/getAnonymityRevokers.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { ArInfo, createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ArInfo, BlockHash } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -32,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -48,9 +49,11 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const ars: AsyncIterable = client.getAnonymityRevokers(
- cli.flags.block
- );
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
+ const ars: AsyncIterable = client.getAnonymityRevokers(blockHash);
for await (const ar of ars) {
console.log('Anonymity Revoker ID:', ar.arIdentity);
diff --git a/examples/client/getBakerList.ts b/examples/client/getBakerList.ts
index 2aaaeba47..c7f0f0e87 100644
--- a/examples/client/getBakerList.ts
+++ b/examples/client/getBakerList.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { BakerId, createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BakerId, BlockHash } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -32,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -48,9 +49,11 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const bakerIds: AsyncIterable = client.getBakerList(
- cli.flags.block
- );
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
+ const bakerIds: AsyncIterable = client.getBakerList(blockHash);
// #endregion documentation-snippet
console.log('List of BakerID at the specified block:');
diff --git a/examples/client/getBannedPeers.ts b/examples/client/getBannedPeers.ts
index d7b44927f..5e8d465f3 100644
--- a/examples/client/getBannedPeers.ts
+++ b/examples/client/getBannedPeers.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, IpAddressString } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { IpAddressString } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -27,7 +28,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/getBlockChainParameters.ts b/examples/client/getBlockChainParameters.ts
index 8eb666eab..54b3de953 100644
--- a/examples/client/getBlockChainParameters.ts
+++ b/examples/client/getBlockChainParameters.ts
@@ -1,10 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- ChainParameters,
- createConcordiumClient,
- isChainParametersV1,
- isChainParametersV2,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, ChainParameters } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -37,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -49,9 +45,11 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const cp: ChainParameters = await client.getBlockChainParameters(
- cli.flags.block
- );
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
+ const cp: ChainParameters = await client.getBlockChainParameters(blockHash);
const euroPerEnergy =
cp.euroPerEnergy.numerator + '/' + cp.euroPerEnergy.denominator;
@@ -59,9 +57,9 @@ const client = createConcordiumClient(
console.log('Euro per Energy:', euroPerEnergy);
// Check version of chain parameters
- if (isChainParametersV2(cp)) {
+ if (cp.version === 2) {
console.log('Minimum block time', cp.minBlockTime);
- } else if (isChainParametersV1(cp)) {
+ } else if (cp.version === 1) {
console.log('Minimum equity capital:', cp.minimumEquityCapital);
} else {
console.log(
diff --git a/examples/client/getBlockFinalizationSummary.ts b/examples/client/getBlockFinalizationSummary.ts
index fe8d66262..b61d2d273 100644
--- a/examples/client/getBlockFinalizationSummary.ts
+++ b/examples/client/getBlockFinalizationSummary.ts
@@ -1,8 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- BlockFinalizationSummary,
- createConcordiumClient,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockFinalizationSummary, BlockHash } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -35,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -51,8 +49,12 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const summary: BlockFinalizationSummary =
- await client.getBlockFinalizationSummary(cli.flags.block);
+ await client.getBlockFinalizationSummary(blockHash);
if (summary.tag === 'record') {
// Response contains finalization summary for the given block:
diff --git a/examples/client/getBlockInfo.ts b/examples/client/getBlockInfo.ts
index c7f1f4702..bf9b99d09 100644
--- a/examples/client/getBlockInfo.ts
+++ b/examples/client/getBlockInfo.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { BlockInfo, createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, BlockInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -32,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
port,
credentials.createInsecure()
@@ -45,7 +46,11 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const blockInfo: BlockInfo = await client.getBlockInfo(cli.flags.block);
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
+ const blockInfo: BlockInfo = await client.getBlockInfo(blockHash);
// #endregion documentation-snippet
console.dir(blockInfo, { depth: null, colors: true });
diff --git a/examples/client/getBlockItemStatus.ts b/examples/client/getBlockItemStatus.ts
index 5843a6afd..173625bbb 100644
--- a/examples/client/getBlockItemStatus.ts
+++ b/examples/client/getBlockItemStatus.ts
@@ -1,5 +1,10 @@
-import { parseEndpoint } from '../shared/util';
-import { BlockItemStatus, createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import {
+ BlockItemStatus,
+ CcdAmount,
+ TransactionHash,
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -35,7 +40,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -52,8 +57,9 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+
const blockItemStatus: BlockItemStatus = await client.getBlockItemStatus(
- cli.flags.transaction
+ TransactionHash.fromHexString(cli.flags.transaction)
);
console.log('Status of the transaction:', cli.flags.transaction, '\n');
@@ -84,7 +90,7 @@ const client = createConcordiumClient(
case 'transfer':
// The transaction is a simple transfer
const { amount, to } = summary.transfer;
- const ccdAmount = Number(amount / 1000000n);
+ const ccdAmount = CcdAmount.toCcd(amount);
console.log(ccdAmount, 'CCD sent to', to);
break;
case 'failed':
diff --git a/examples/client/getBlockPendingUpdates.ts b/examples/client/getBlockPendingUpdates.ts
index 69a7af3b7..bcdeb447f 100644
--- a/examples/client/getBlockPendingUpdates.ts
+++ b/examples/client/getBlockPendingUpdates.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, PendingUpdate } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, PendingUpdate } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -32,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -51,8 +52,12 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const pendingUpdates: AsyncIterable =
- client.getBlockPendingUpdates(cli.flags.block);
+ client.getBlockPendingUpdates(blockHash);
// #endregion documentation-snippet
for await (const pendingUpdate of pendingUpdates) {
diff --git a/examples/client/getBlockSpecialEvents.ts b/examples/client/getBlockSpecialEvents.ts
index 639a71412..50a9b8213 100644
--- a/examples/client/getBlockSpecialEvents.ts
+++ b/examples/client/getBlockSpecialEvents.ts
@@ -1,8 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- BlockSpecialEvent,
- createConcordiumClient,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, BlockSpecialEvent } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -35,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -55,8 +53,12 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const events: AsyncIterable =
- client.getBlockSpecialEvents(cli.flags.block);
+ client.getBlockSpecialEvents(blockHash);
// #endregion documentation-snippet
for await (const event of events) {
diff --git a/examples/client/getBlockTransactionEvents.ts b/examples/client/getBlockTransactionEvents.ts
index b2dd89837..d312fca62 100644
--- a/examples/client/getBlockTransactionEvents.ts
+++ b/examples/client/getBlockTransactionEvents.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { BlockItemSummary, createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, BlockItemSummary } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -32,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -50,8 +51,12 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const events: AsyncIterable =
- client.getBlockTransactionEvents(cli.flags.block);
+ client.getBlockTransactionEvents(blockHash);
// #endregion documentation-snippet
for await (const event of events) {
diff --git a/examples/client/getBlocks.ts b/examples/client/getBlocks.ts
index 8f13b2b57..a4e0204ac 100644
--- a/examples/client/getBlocks.ts
+++ b/examples/client/getBlocks.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { ArrivedBlockInfo, createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ArrivedBlockInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -27,7 +28,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/getBlocksAbort.ts b/examples/client/getBlocksAbort.ts
index 646761fc8..c82f6b2c7 100644
--- a/examples/client/getBlocksAbort.ts
+++ b/examples/client/getBlocksAbort.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, ArrivedBlockInfo } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ArrivedBlockInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -27,7 +28,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/getBlocksAtHeightAbsolute.ts b/examples/client/getBlocksAtHeightAbsolute.ts
index 2a1fa8649..219cf36bc 100644
--- a/examples/client/getBlocksAtHeightAbsolute.ts
+++ b/examples/client/getBlocksAtHeightAbsolute.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, HexString } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -35,7 +36,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -47,7 +48,7 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const blocks: HexString[] = await client.getBlocksAtHeight(
+ const blocks: BlockHash.Type[] = await client.getBlocksAtHeight(
BigInt(cli.flags.height)
);
// #endregion documentation-snippet
diff --git a/examples/client/getBlocksAtHeightRelative.ts b/examples/client/getBlocksAtHeightRelative.ts
index f7c6364c0..23423635e 100644
--- a/examples/client/getBlocksAtHeightRelative.ts
+++ b/examples/client/getBlocksAtHeightRelative.ts
@@ -1,9 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- BlocksAtHeightRequest,
- createConcordiumClient,
- HexString,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, BlocksAtHeightRequest } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -53,7 +50,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -70,7 +67,7 @@ const client = createConcordiumClient(
height: BigInt(cli.flags.height),
restrict: cli.flags.restrict,
};
- const blocks: HexString[] = await client.getBlocksAtHeight(request);
+ const blocks: BlockHash.Type[] = await client.getBlocksAtHeight(request);
// #endregion documentation-snippet
for (const block of blocks) {
diff --git a/examples/client/getBranches.ts b/examples/client/getBranches.ts
index 4ce830789..c64a84223 100644
--- a/examples/client/getBranches.ts
+++ b/examples/client/getBranches.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { Branch, createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { Branch } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -27,7 +28,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/getConsensusStatus.ts b/examples/client/getConsensusStatus.ts
index e2065a364..e3192a547 100644
--- a/examples/client/getConsensusStatus.ts
+++ b/examples/client/getConsensusStatus.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { ConsensusStatus, createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ConsensusStatus } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -27,7 +28,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/getCryptographicParameters.ts b/examples/client/getCryptographicParameters.ts
index 72ceaf046..618da9363 100644
--- a/examples/client/getCryptographicParameters.ts
+++ b/examples/client/getCryptographicParameters.ts
@@ -1,8 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- createConcordiumClient,
- CryptographicParameters,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, CryptographicParameters } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -35,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -48,8 +46,12 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const parameters: CryptographicParameters =
- await client.getCryptographicParameters(cli.flags.block);
+ await client.getCryptographicParameters(blockHash);
// #endregion documentation-snippet
console.log('Genesis string:', parameters.genesisString);
diff --git a/examples/client/getElectionInfo.ts b/examples/client/getElectionInfo.ts
index 43ae5aaf9..09097b5c1 100644
--- a/examples/client/getElectionInfo.ts
+++ b/examples/client/getElectionInfo.ts
@@ -1,9 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- createConcordiumClient,
- ElectionInfo,
- isElectionInfoV0,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, ElectionInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -36,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -49,9 +46,11 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const electionInfo: ElectionInfo = await client.getElectionInfo(
- cli.flags.block
- );
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
+ const electionInfo: ElectionInfo = await client.getElectionInfo(blockHash);
// Discard address, convert to tuple:
const bakers: [bigint, number][] = electionInfo.bakerElectionInfo.map(
@@ -63,7 +62,7 @@ const client = createConcordiumClient(
console.log('Bakers sorted by lottery power:', sortedBakers);
console.log('Election nonce:', electionInfo.electionNonce);
- if (isElectionInfoV0(electionInfo)) {
+ if (electionInfo.version === 0) {
console.log('Election difficulty:', electionInfo.electionDifficulty);
}
// #endregion documentation-snippet
diff --git a/examples/client/getEmbeddedSchema.ts b/examples/client/getEmbeddedSchema.ts
index 87cddbeab..dcb81bb27 100644
--- a/examples/client/getEmbeddedSchema.ts
+++ b/examples/client/getEmbeddedSchema.ts
@@ -1,4 +1,5 @@
-import { createConcordiumClient, ModuleReference } from '@concordium/node-sdk';
+import { ModuleReference } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -40,7 +41,7 @@ const cli = meow(
);
const [address, port] = cli.flags.endpoint.split(':');
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -52,7 +53,7 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const moduleRef = new ModuleReference(cli.flags.module);
+ const moduleRef = ModuleReference.fromHexString(cli.flags.module);
const schema = await client.getEmbeddedSchema(moduleRef);
// #endregion documentation-snippet
diff --git a/examples/client/getFinalizedBlocks.ts b/examples/client/getFinalizedBlocks.ts
index 1220ee3bc..1336f77fd 100644
--- a/examples/client/getFinalizedBlocks.ts
+++ b/examples/client/getFinalizedBlocks.ts
@@ -1,8 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- createConcordiumClient,
- FinalizedBlockInfo,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { FinalizedBlockInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -30,7 +28,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/getFinalizedBlocksFrom.ts b/examples/client/getFinalizedBlocksFrom.ts
index 406b43bce..ec0a636ac 100644
--- a/examples/client/getFinalizedBlocksFrom.ts
+++ b/examples/client/getFinalizedBlocksFrom.ts
@@ -1,5 +1,5 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -39,7 +39,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/getIdentityProviders.ts b/examples/client/getIdentityProviders.ts
index 1a7b3939d..9bf97fe9d 100644
--- a/examples/client/getIdentityProviders.ts
+++ b/examples/client/getIdentityProviders.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, IpInfo } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, IpInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -32,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -48,9 +49,11 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const ips: AsyncIterable = client.getIdentityProviders(
- cli.flags.block
- );
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
+ const ips: AsyncIterable = client.getIdentityProviders(blockHash);
for await (const ip of ips) {
console.log('Identity Provider ID:', ip.ipIdentity);
diff --git a/examples/client/getInstanceInfo.ts b/examples/client/getInstanceInfo.ts
index 3c5ad4ce6..99a361eee 100644
--- a/examples/client/getInstanceInfo.ts
+++ b/examples/client/getInstanceInfo.ts
@@ -1,9 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- ContractAddress,
- createConcordiumClient,
- InstanceInfo,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, ContractAddress, InstanceInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -44,7 +41,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -57,14 +54,15 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const contractAddress: ContractAddress = {
- index: BigInt(cli.flags.contract),
- subindex: 0n,
- };
+ const contractAddress = ContractAddress.create(cli.flags.contract);
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const instanceInfo: InstanceInfo = await client.getInstanceInfo(
contractAddress,
- cli.flags.block
+ blockHash
);
console.log('Name:', instanceInfo.name);
diff --git a/examples/client/getInstanceState.ts b/examples/client/getInstanceState.ts
index 7c2fc74a2..be557aa81 100644
--- a/examples/client/getInstanceState.ts
+++ b/examples/client/getInstanceState.ts
@@ -1,8 +1,10 @@
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import {
- createConcordiumClient,
+ BlockHash,
+ ContractAddress,
InstanceStateKVPair,
-} from '@concordium/node-sdk';
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -43,7 +45,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -60,13 +62,14 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const contractAddress = {
- index: BigInt(cli.flags.contract),
- subindex: 0n,
- };
+ const contractAddress = ContractAddress.create(cli.flags.contract);
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const states: AsyncIterable = client.getInstanceState(
contractAddress,
- cli.flags.block
+ blockHash
);
// #endregion documentation-snippet
diff --git a/examples/client/getModuleList.ts b/examples/client/getModuleList.ts
index 59ec10c31..0d678ac32 100644
--- a/examples/client/getModuleList.ts
+++ b/examples/client/getModuleList.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, HexString } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, ModuleReference } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -32,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -49,13 +50,16 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const moduleRefs: AsyncIterable = client.getModuleList(
- cli.flags.block
- );
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
+ const moduleRefs: AsyncIterable =
+ client.getModuleList(blockHash);
// #endregion documentation-snippet
// Prints module references
for await (const moduleRef of moduleRefs) {
- console.log(moduleRef);
+ console.log(ModuleReference.toHexString(moduleRef));
}
})();
diff --git a/examples/client/getModuleSource.ts b/examples/client/getModuleSource.ts
index b2da89935..6d53dd54c 100644
--- a/examples/client/getModuleSource.ts
+++ b/examples/client/getModuleSource.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, ModuleReference } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, ModuleReference } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import fs from 'fs';
@@ -47,7 +48,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -60,8 +61,12 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const ref = new ModuleReference(cli.flags.module);
- const versionedSource = await client.getModuleSource(ref, cli.flags.block);
+ const ref = ModuleReference.fromHexString(cli.flags.module);
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
+ const versionedSource = await client.getModuleSource(ref, blockHash);
// #endregion documentation-snippet
fs.writeFileSync(cli.flags.outPath, versionedSource.source);
diff --git a/examples/client/getNextAccountSequenceNumber.ts b/examples/client/getNextAccountSequenceNumber.ts
index 9d9068f39..84b9216ba 100644
--- a/examples/client/getNextAccountSequenceNumber.ts
+++ b/examples/client/getNextAccountSequenceNumber.ts
@@ -1,9 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- AccountAddress,
- createConcordiumClient,
- NextAccountNonce,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { AccountAddress, NextAccountNonce } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -39,7 +36,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -55,7 +52,7 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const account = new AccountAddress(cli.flags.account);
+ const account = AccountAddress.fromBase58(cli.flags.account);
const nextNonce: NextAccountNonce = await client.getNextAccountNonce(
account
);
diff --git a/examples/client/getNextUpdateSequenceNumbers.ts b/examples/client/getNextUpdateSequenceNumbers.ts
index 2a7365f8c..7a2fd324a 100644
--- a/examples/client/getNextUpdateSequenceNumbers.ts
+++ b/examples/client/getNextUpdateSequenceNumbers.ts
@@ -1,8 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- createConcordiumClient,
- NextUpdateSequenceNumbers,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, NextUpdateSequenceNumbers } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -35,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -48,8 +46,12 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const updateSeqNums: NextUpdateSequenceNumbers =
- await client.getNextUpdateSequenceNumbers(cli.flags.block);
+ await client.getNextUpdateSequenceNumbers(blockHash);
// #endregion documentation-snippet
console.dir(updateSeqNums, { depth: null, colors: true });
diff --git a/examples/client/getNodeInfo.ts b/examples/client/getNodeInfo.ts
index 477ce7d74..80423fad8 100644
--- a/examples/client/getNodeInfo.ts
+++ b/examples/client/getNodeInfo.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, NodeInfo } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { NodeInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -32,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/getPassiveDelegationInfo.ts b/examples/client/getPassiveDelegationInfo.ts
index 8855ce952..175947b59 100644
--- a/examples/client/getPassiveDelegationInfo.ts
+++ b/examples/client/getPassiveDelegationInfo.ts
@@ -1,8 +1,10 @@
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import {
- createConcordiumClient,
+ BlockHash,
+ CcdAmount,
PassiveDelegationStatus,
-} from '@concordium/node-sdk';
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -35,7 +37,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -49,16 +51,20 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const passiveDelegationInfo: PassiveDelegationStatus =
- await client.getPassiveDelegationInfo(cli.flags.block);
+ await client.getPassiveDelegationInfo(blockHash);
console.log(
'CCD provided by the delegators to the pool:',
- passiveDelegationInfo.delegatedCapital / 1000000n
+ CcdAmount.toCcd(passiveDelegationInfo.delegatedCapital)
);
console.log(
'Total capital in CCD of ALL pools:',
- passiveDelegationInfo.allPoolTotalCapital / 1000000n
+ CcdAmount.toCcd(passiveDelegationInfo.allPoolTotalCapital)
);
console.log('Pool commision rates:', passiveDelegationInfo.commissionRates);
// #endregion documentation-snippet
diff --git a/examples/client/getPassiveDelegators.ts b/examples/client/getPassiveDelegators.ts
index da7815d51..68d27d338 100644
--- a/examples/client/getPassiveDelegators.ts
+++ b/examples/client/getPassiveDelegators.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, DelegatorInfo } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, DelegatorInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -32,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -54,8 +55,12 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const delegators: AsyncIterable =
- client.getPassiveDelegators(cli.flags.block);
+ client.getPassiveDelegators(blockHash);
console.log('Each staking account and the amount of stake they have:\n');
for await (const delegatorInfo of delegators) {
diff --git a/examples/client/getPassiveDelegatorsPendingChanges.ts b/examples/client/getPassiveDelegatorsPendingChanges.ts
index 90a48ce44..8880b2f0c 100644
--- a/examples/client/getPassiveDelegatorsPendingChanges.ts
+++ b/examples/client/getPassiveDelegatorsPendingChanges.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, DelegatorInfo } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, DelegatorInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -32,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -54,8 +55,12 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const delegators: AsyncIterable =
- client.getPassiveDelegators(cli.flags.block);
+ client.getPassiveDelegators(blockHash);
console.log('Each staking account and the amount of stake they have:\n');
for await (const delegatorInfo of delegators) {
diff --git a/examples/client/getPassiveDelegatorsRewardPeriod.ts b/examples/client/getPassiveDelegatorsRewardPeriod.ts
index 380f9a34c..c64499e88 100644
--- a/examples/client/getPassiveDelegatorsRewardPeriod.ts
+++ b/examples/client/getPassiveDelegatorsRewardPeriod.ts
@@ -1,8 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- createConcordiumClient,
- DelegatorRewardPeriodInfo,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, DelegatorRewardPeriodInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -35,7 +33,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -56,8 +54,12 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const delegators: AsyncIterable =
- client.getPassiveDelegatorsRewardPeriod(cli.flags.block);
+ client.getPassiveDelegatorsRewardPeriod(blockHash);
console.log('Each staking account and the amount of stake they have:\n');
for await (const delegatorInfo of delegators) {
diff --git a/examples/client/getPeersInfo.ts b/examples/client/getPeersInfo.ts
index b6f402b15..ad736fad5 100644
--- a/examples/client/getPeersInfo.ts
+++ b/examples/client/getPeersInfo.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, PeerInfo } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { PeerInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -27,7 +28,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/getPoolDelegators.ts b/examples/client/getPoolDelegators.ts
index db7bba9a5..e4d4817f0 100644
--- a/examples/client/getPoolDelegators.ts
+++ b/examples/client/getPoolDelegators.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient, DelegatorInfo } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, DelegatorInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -10,7 +11,7 @@ const cli = meow(
$ yarn run-example [options]
Required:
- --pool-owner, -p The BakerId of the pool owner
+ --pool-owner, -p The BakerId of the pool owner
Options
--help, -h Displays this message
@@ -40,7 +41,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -62,9 +63,13 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const delegators: AsyncIterable = client.getPoolDelegators(
BigInt(cli.flags.poolOwner),
- cli.flags.block
+ blockHash
);
console.log('Each staking account and the amount of stake they have:\n');
diff --git a/examples/client/getPoolDelegatorsRewardPeriod.ts b/examples/client/getPoolDelegatorsRewardPeriod.ts
index 016fa2230..d535bcfb9 100644
--- a/examples/client/getPoolDelegatorsRewardPeriod.ts
+++ b/examples/client/getPoolDelegatorsRewardPeriod.ts
@@ -1,8 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- createConcordiumClient,
- DelegatorRewardPeriodInfo,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, DelegatorRewardPeriodInfo } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -13,7 +11,7 @@ const cli = meow(
$ yarn run-example [options]
Required:
- --pool-owner, -p The BakerId of the pool owner
+ --pool-owner, -p The BakerId of the pool owner
Options
--help, -h Displays this message
@@ -43,7 +41,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -64,10 +62,14 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const delegators: AsyncIterable =
client.getPoolDelegatorsRewardPeriod(
BigInt(cli.flags.poolOwner),
- cli.flags.block
+ blockHash
);
console.log('Each staking account and the amount of stake they have:\n');
diff --git a/examples/client/getPoolInfo.ts b/examples/client/getPoolInfo.ts
index c33e7e2bc..70c1636ae 100644
--- a/examples/client/getPoolInfo.ts
+++ b/examples/client/getPoolInfo.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { BakerPoolStatus, createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BakerPoolStatus, BlockHash, CcdAmount } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -10,7 +11,7 @@ const cli = meow(
$ yarn run-example [options]
Required:
- --pool-owner, -p The BakerId of the pool owner
+ --pool-owner, -p The BakerId of the pool owner
Options
--help, -h Displays this message
@@ -40,7 +41,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -53,24 +54,28 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const bakerPool: BakerPoolStatus = await client.getPoolInfo(
BigInt(cli.flags.poolOwner),
- cli.flags.block
+ blockHash
);
console.log('Open status:', bakerPool.poolInfo.openStatus);
console.log('Baker address:', bakerPool.bakerAddress);
console.log(
'CCD provided by the baker to the pool:',
- bakerPool.bakerEquityCapital / 1000000n
+ CcdAmount.toCcd(bakerPool.bakerEquityCapital)
);
console.log(
'CCD provided by the delegators to the pool:',
- bakerPool.delegatedCapital / 1000000n
+ CcdAmount.toCcd(bakerPool.delegatedCapital)
);
console.log(
'Total capital in CCD of ALL pools:',
- bakerPool.allPoolTotalCapital / 1000000n
+ CcdAmount.toCcd(bakerPool.allPoolTotalCapital)
);
console.log('Pool commision rates:', bakerPool.poolInfo.commissionRates);
// #endregion documentation-snippet
diff --git a/examples/client/getTokenomicsInfo.ts b/examples/client/getTokenomicsInfo.ts
index a4d81be24..a7d0a0f74 100644
--- a/examples/client/getTokenomicsInfo.ts
+++ b/examples/client/getTokenomicsInfo.ts
@@ -1,5 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import { isRewardStatusV1, createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -10,7 +11,7 @@ const cli = meow(
$ yarn run-example [options]
Required:
- --pool-owner, -p The BakerId of the pool owner
+ --pool-owner, -p The BakerId of the pool owner
Options
--help, Displays this message
@@ -40,7 +41,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -53,11 +54,15 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const tokenomics = await client.getTokenomicsInfo(cli.flags.block);
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
+ const tokenomics = await client.getTokenomicsInfo(blockHash);
// Protocol version 4 expanded the amount of information in the response, so one should check the type to access that.
// This information includes information about the payday and total amount of funds staked.
- if (isRewardStatusV1(tokenomics)) {
+ if (tokenomics.version === 1) {
console.log('Next payday time:', tokenomics.nextPaydayTime);
console.log(
'Total staked amount by bakers and delegators',
diff --git a/examples/client/healthCheck.ts b/examples/client/healthCheck.ts
index bca2d96da..c49b22a25 100644
--- a/examples/client/healthCheck.ts
+++ b/examples/client/healthCheck.ts
@@ -1,5 +1,5 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -27,7 +27,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/instanceStateLookup.ts b/examples/client/instanceStateLookup.ts
index cbbbdcddc..0d4a038e7 100644
--- a/examples/client/instanceStateLookup.ts
+++ b/examples/client/instanceStateLookup.ts
@@ -1,9 +1,6 @@
-import { parseEndpoint } from '../shared/util';
-import {
- ContractAddress,
- HexString,
- createConcordiumClient,
-} from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { BlockHash, ContractAddress, HexString } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -50,7 +47,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -65,15 +62,16 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const contract: ContractAddress = {
- index: BigInt(cli.flags.contract),
- subindex: 0n,
- };
+ const contract = ContractAddress.create(cli.flags.contract);
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
const state: HexString = await client.instanceStateLookup(
contract,
cli.flags.key,
- cli.flags.block
+ blockHash
);
// #endregion documentation-snippet
diff --git a/examples/client/invokeContract.ts b/examples/client/invokeContract.ts
index e6b4d863c..b7b9936c8 100644
--- a/examples/client/invokeContract.ts
+++ b/examples/client/invokeContract.ts
@@ -1,13 +1,18 @@
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import {
AccountAddress,
+ BlockHash,
CcdAmount,
+ ContractAddress,
ContractContext,
ContractTraceEvent,
- createConcordiumClient,
-} from '@concordium/node-sdk';
+ Energy,
+ Parameter,
+ ReceiveName,
+ ReturnValue,
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
-import { Buffer } from 'buffer/index.js';
import meow from 'meow';
@@ -27,7 +32,7 @@ const cli = meow(
--energy, -n The maximum amount of energy to allow for execution, defaults to 1000000
--invoker, -i The address of the invoker, defaults to the zero account address
--endpoint, -e Specify endpoint of the form "address:port", defaults to localhost:20000
- --parameter, -p The serialized parameters that the contract will be invoked with, as a
+ --parameter, -p The serialized parameters that the contract will be invoked with, as a
hex string. Will default to an empty hex string meaning no parameters
`,
{
@@ -74,7 +79,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -92,23 +97,22 @@ const client = createConcordiumClient(
// #region documentation-snippet
// Handle the optional arguments
const invoker = cli.flags.invoker
- ? new AccountAddress(cli.flags.invoker)
+ ? AccountAddress.fromBase58(cli.flags.invoker)
: undefined;
const amount = cli.flags.amount
- ? new CcdAmount(BigInt(cli.flags.amount))
+ ? CcdAmount.fromMicroCcd(cli.flags.amount)
: undefined;
const parameter = cli.flags.parameter
- ? Buffer.from(cli.flags.parameter, 'hex')
+ ? Parameter.fromHexString(cli.flags.parameter)
+ : undefined;
+ const energy = cli.flags.energy
+ ? Energy.create(cli.flags.energy)
: undefined;
- const energy = cli.flags.energy ? BigInt(cli.flags.energy) : undefined;
- const contract = {
- index: BigInt(cli.flags.contract),
- subindex: 0n,
- };
+ const contract = ContractAddress.create(cli.flags.contract);
const context: ContractContext = {
// Required
- method: cli.flags.receive,
+ method: ReceiveName.fromString(cli.flags.receive),
contract,
// Optional
invoker,
@@ -116,8 +120,12 @@ const client = createConcordiumClient(
parameter,
energy,
};
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
- const result = await client.invokeContract(context, cli.flags.block);
+ const result = await client.invokeContract(context, blockHash);
// We can inspect the result
if (result.tag === 'failure') {
@@ -126,9 +134,12 @@ const client = createConcordiumClient(
} else if (result.tag === 'success') {
console.log('Invoke was succesful');
- const returnValue: string | undefined = result.returnValue; // If the invoked method has return value
+ const returnValue = result.returnValue; // If the invoked method has return value
if (returnValue) {
- console.log('The return value of the invoked method:', returnValue);
+ console.log(
+ 'The return value of the invoked method:',
+ ReturnValue.toHexString(returnValue)
+ );
}
const events: ContractTraceEvent[] = result.events;
diff --git a/examples/client/peerConnect.ts b/examples/client/peerConnect.ts
index 17f516fcc..461e14654 100644
--- a/examples/client/peerConnect.ts
+++ b/examples/client/peerConnect.ts
@@ -1,5 +1,5 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -41,7 +41,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/peerDisconnect.ts b/examples/client/peerDisconnect.ts
index c3005644c..eddbf1190 100644
--- a/examples/client/peerDisconnect.ts
+++ b/examples/client/peerDisconnect.ts
@@ -1,5 +1,5 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -41,7 +41,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/shutdown.ts b/examples/client/shutdown.ts
index 5fc872e7c..ac326179a 100644
--- a/examples/client/shutdown.ts
+++ b/examples/client/shutdown.ts
@@ -1,5 +1,5 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -27,7 +27,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/client/unbanPeer.ts b/examples/client/unbanPeer.ts
index dc99232f9..1d54805f1 100644
--- a/examples/client/unbanPeer.ts
+++ b/examples/client/unbanPeer.ts
@@ -1,5 +1,5 @@
-import { parseEndpoint } from '../shared/util';
-import { createConcordiumClient } from '@concordium/node-sdk';
+import { parseEndpoint } from '../shared/util.js';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -35,7 +35,7 @@ const cli = meow(
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/common/aliases.ts b/examples/common/aliases.ts
index 71aff6a98..c20a4fa5b 100644
--- a/examples/common/aliases.ts
+++ b/examples/common/aliases.ts
@@ -1,4 +1,4 @@
-import { AccountAddress, getAlias, isAlias } from '@concordium/node-sdk';
+import { AccountAddress } from '@concordium/web-sdk';
/**
* The following shows how to generate an account alias, and how to test
@@ -8,26 +8,29 @@ import { AccountAddress, getAlias, isAlias } from '@concordium/node-sdk';
*/
// #region documentation-snippet
-const accountAddress = new AccountAddress(
+const accountAddress = AccountAddress.fromBase58(
'3sAHwfehRNEnXk28W7A3XB3GzyBiuQkXLNRmDwDGPUe8JsoAcU'
);
-const seperateAccount = new AccountAddress(
+const seperateAccount = AccountAddress.fromBase58(
'4ZJBYQbVp3zVZyjCXfZAAYBVkJMyVj8UKUNj9ox5YqTCBdBq2M'
);
const aliasCounter = 0;
-const alias: AccountAddress = getAlias(accountAddress, aliasCounter);
+const alias: AccountAddress.Type = AccountAddress.getAlias(
+ accountAddress,
+ aliasCounter
+);
console.log('Original address:', accountAddress.address);
console.log('Alias address:', alias.address);
// The function `isAlias` can be used to check if two acounts are aliases
-if (!isAlias(alias, accountAddress)) {
+if (!AccountAddress.isAlias(alias, accountAddress)) {
throw Error('Expected accounts to be aliases!');
}
// Of course, using `isAlias` on a completely seperate account returns false
-if (isAlias(accountAddress, seperateAccount)) {
+if (AccountAddress.isAlias(accountAddress, seperateAccount)) {
throw Error('Two seperate accounts are claimed to be aliases!');
}
// #endregion documentation-snippet
diff --git a/examples/common/bakerAdd.ts b/examples/common/bakerAdd.ts
index 99c9bc13d..e37f41dbe 100644
--- a/examples/common/bakerAdd.ts
+++ b/examples/common/bakerAdd.ts
@@ -5,17 +5,17 @@ import {
AccountTransactionType,
signTransaction,
TransactionExpiry,
- createConcordiumClient,
CcdAmount,
generateBakerKeys,
ConfigureBakerPayload,
OpenStatus,
parseWallet,
buildAccountSigner,
-} from '@concordium/node-sdk';
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import { readFileSync } from 'node:fs';
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import meow from 'meow';
@@ -55,7 +55,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -71,11 +71,11 @@ const client = createConcordiumClient(
// Read wallet-file
const walletFile = readFileSync(cli.flags.walletFile, 'utf8');
const wallet = parseWallet(walletFile);
- const sender = new AccountAddress(wallet.value.address);
+ const sender = AccountAddress.fromBase58(wallet.value.address);
const signer = buildAccountSigner(wallet);
const header: AccountTransactionHeader = {
- expiry: new TransactionExpiry(new Date(Date.now() + 3600000)),
+ expiry: TransactionExpiry.futureMinutes(60),
nonce: (await client.getNextAccountNonce(sender)).nonce,
sender,
};
@@ -83,7 +83,7 @@ const client = createConcordiumClient(
const bakerKeys = generateBakerKeys(sender);
const configureBakerPayload: ConfigureBakerPayload = {
- stake: new CcdAmount(BigInt(cli.flags.stake)),
+ stake: CcdAmount.fromMicroCcd(cli.flags.stake),
restakeEarnings: true,
openForDelegation: OpenStatus.OpenForAll,
keys: bakerKeys,
diff --git a/examples/common/bakerRemove.ts b/examples/common/bakerRemove.ts
index 9ffd40ca8..8c109ca28 100644
--- a/examples/common/bakerRemove.ts
+++ b/examples/common/bakerRemove.ts
@@ -5,15 +5,15 @@ import {
AccountTransactionType,
signTransaction,
TransactionExpiry,
- createConcordiumClient,
CcdAmount,
ConfigureBakerPayload,
parseWallet,
buildAccountSigner,
-} from '@concordium/node-sdk';
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import { readFileSync } from 'node:fs';
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import meow from 'meow';
@@ -47,7 +47,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -62,17 +62,17 @@ const client = createConcordiumClient(
// Read wallet-file
const walletFile = readFileSync(cli.flags.walletFile, 'utf8');
const wallet = parseWallet(walletFile);
- const sender = new AccountAddress(wallet.value.address);
+ const sender = AccountAddress.fromBase58(wallet.value.address);
const signer = buildAccountSigner(wallet);
const header: AccountTransactionHeader = {
- expiry: new TransactionExpiry(new Date(Date.now() + 3600000)),
+ expiry: TransactionExpiry.futureMinutes(60),
nonce: (await client.getNextAccountNonce(sender)).nonce,
sender,
};
const configureBakerPayload: ConfigureBakerPayload = {
- stake: new CcdAmount(0n),
+ stake: CcdAmount.zero(),
};
const configureBakerAccountTransaction: AccountTransaction = {
diff --git a/examples/common/buildAccountSigner.ts b/examples/common/buildAccountSigner.ts
index 912c0ac34..0655ae9a4 100644
--- a/examples/common/buildAccountSigner.ts
+++ b/examples/common/buildAccountSigner.ts
@@ -6,7 +6,7 @@ import {
signMessage,
buildAccountSigner,
parseWallet,
-} from '@concordium/node-sdk';
+} from '@concordium/web-sdk';
const cli = meow(
`
@@ -45,9 +45,11 @@ const wallet = parseWallet(walletFile);
try {
const signer = buildAccountSigner(wallet);
- signMessage(new AccountAddress(wallet.value.address), 'test', signer).then(
- console.log
- );
+ signMessage(
+ AccountAddress.fromBase58(wallet.value.address),
+ 'test',
+ signer
+ ).then(console.log);
} catch {
console.error('File passed does not conform to a supported JSON format');
}
diff --git a/examples/common/cis0Supports.ts b/examples/common/cis0Supports.ts
index caa6d4450..20461ccdf 100644
--- a/examples/common/cis0Supports.ts
+++ b/examples/common/cis0Supports.ts
@@ -1,11 +1,8 @@
-import {
- createConcordiumClient,
- cis0Supports,
- ContractAddress,
-} from '@concordium/node-sdk';
+import { cis0Supports, ContractAddress } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -50,17 +47,17 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
);
(async () => {
- const contractAddress: ContractAddress = {
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- };
+ const contractAddress = ContractAddress.create(
+ cli.flags.index,
+ cli.flags.subindex
+ );
const response = await cis0Supports(
client,
contractAddress,
diff --git a/examples/common/delegationAdd.ts b/examples/common/delegationAdd.ts
index 75cff2311..480f34749 100644
--- a/examples/common/delegationAdd.ts
+++ b/examples/common/delegationAdd.ts
@@ -5,18 +5,18 @@ import {
AccountTransactionType,
signTransaction,
TransactionExpiry,
- createConcordiumClient,
ConfigureDelegationPayload,
CcdAmount,
DelegationTargetType,
parseWallet,
buildAccountSigner,
-} from '@concordium/node-sdk';
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import { readFileSync } from 'node:fs';
import meow from 'meow';
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
const cli = meow(
`
@@ -60,7 +60,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -76,17 +76,17 @@ const client = createConcordiumClient(
// Read wallet-file
const walletFile = readFileSync(cli.flags.walletFile, 'utf8');
const wallet = parseWallet(walletFile);
- const sender = new AccountAddress(wallet.value.address);
+ const sender = AccountAddress.fromBase58(wallet.value.address);
const signer = buildAccountSigner(wallet);
const header: AccountTransactionHeader = {
- expiry: new TransactionExpiry(new Date(Date.now() + 3600000)),
+ expiry: TransactionExpiry.futureMinutes(60),
nonce: (await client.getNextAccountNonce(sender)).nonce,
sender: sender,
};
const configureDelegationPayload: ConfigureDelegationPayload = {
- stake: new CcdAmount(BigInt(cli.flags.stake)),
+ stake: CcdAmount.fromMicroCcd(cli.flags.stake),
delegationTarget: {
delegateType: DelegationTargetType.PassiveDelegation,
},
diff --git a/examples/common/delegationRemove.ts b/examples/common/delegationRemove.ts
index 30229177f..9b8a495ce 100644
--- a/examples/common/delegationRemove.ts
+++ b/examples/common/delegationRemove.ts
@@ -5,15 +5,15 @@ import {
AccountTransactionType,
signTransaction,
TransactionExpiry,
- createConcordiumClient,
ConfigureDelegationPayload,
CcdAmount,
parseWallet,
buildAccountSigner,
-} from '@concordium/node-sdk';
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import { readFileSync } from 'node:fs';
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import meow from 'meow';
@@ -47,7 +47,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -62,16 +62,16 @@ const client = createConcordiumClient(
// Read wallet-file
const walletFile = readFileSync(cli.flags.walletFile, 'utf8');
const wallet = parseWallet(walletFile);
- const sender = new AccountAddress(wallet.value.address);
+ const sender = AccountAddress.fromBase58(wallet.value.address);
const header: AccountTransactionHeader = {
- expiry: new TransactionExpiry(new Date(Date.now() + 3600000)),
+ expiry: TransactionExpiry.futureMinutes(60),
nonce: (await client.getNextAccountNonce(sender)).nonce,
sender: sender,
};
const configureDelegationPayload: ConfigureDelegationPayload = {
- stake: new CcdAmount(0n),
+ stake: CcdAmount.zero(),
};
const configureDelegationTransaction: AccountTransaction = {
diff --git a/examples/common/deployModule.ts b/examples/common/deployModule.ts
index baf53243e..d740412cd 100644
--- a/examples/common/deployModule.ts
+++ b/examples/common/deployModule.ts
@@ -7,14 +7,13 @@ import {
DeployModulePayload,
signTransaction,
TransactionExpiry,
- createConcordiumClient,
parseWallet,
buildAccountSigner,
-} from '@concordium/node-sdk';
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import { readFileSync } from 'node:fs';
-import { Buffer } from 'buffer/index.js';
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import meow from 'meow';
@@ -54,7 +53,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -68,7 +67,7 @@ const client = createConcordiumClient(
// #region documentation-snippet
const walletFile = readFileSync(cli.flags.walletFile, 'utf8');
const wallet = parseWallet(walletFile);
- const sender = new AccountAddress(wallet.value.address);
+ const sender = AccountAddress.fromBase58(wallet.value.address);
// Get the wasm file as a buffer.
const wasmModule = Buffer.from(readFileSync(cli.flags.moduleFile));
@@ -82,7 +81,7 @@ const client = createConcordiumClient(
};
const header: AccountTransactionHeader = {
- expiry: new TransactionExpiry(new Date(Date.now() + 3600000)),
+ expiry: TransactionExpiry.futureMinutes(60),
nonce: (await client.getNextAccountNonce(sender)).nonce,
sender,
};
diff --git a/examples/common/simpleTransfer.ts b/examples/common/simpleTransfer.ts
index 1bae14443..1b3417046 100644
--- a/examples/common/simpleTransfer.ts
+++ b/examples/common/simpleTransfer.ts
@@ -9,14 +9,13 @@ import {
NextAccountNonce,
signTransaction,
TransactionExpiry,
- createConcordiumClient,
parseWallet,
buildAccountSigner,
-} from '@concordium/node-sdk';
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import { readFileSync } from 'node:fs';
-import { Buffer } from 'buffer/index.js';
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import meow from 'meow';
@@ -68,7 +67,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -82,15 +81,15 @@ const client = createConcordiumClient(
// #region documentation-snippet
const walletFile = readFileSync(cli.flags.walletFile, 'utf8');
const walletExport = parseWallet(walletFile);
- const sender = new AccountAddress(walletExport.value.address);
+ const sender = AccountAddress.fromBase58(walletExport.value.address);
- const toAddress = new AccountAddress(cli.flags.receiver);
+ const toAddress = AccountAddress.fromBase58(cli.flags.receiver);
const nextNonce: NextAccountNonce = await client.getNextAccountNonce(
sender
);
const header: AccountTransactionHeader = {
- expiry: new TransactionExpiry(new Date(Date.now() + 3600000)),
+ expiry: TransactionExpiry.futureMinutes(60),
nonce: nextNonce.nonce,
sender,
};
@@ -99,13 +98,13 @@ const client = createConcordiumClient(
let simpleTransfer = undefined;
if (cli.flags.memo) {
simpleTransfer = {
- amount: new CcdAmount(BigInt(cli.flags.amount)),
+ amount: CcdAmount.fromMicroCcd(cli.flags.amount),
toAddress,
memo: new DataBlob(Buffer.from(cli.flags.memo, 'hex')),
};
} else {
simpleTransfer = {
- amount: new CcdAmount(BigInt(cli.flags.amount)),
+ amount: CcdAmount.fromMicroCcd(cli.flags.amount),
toAddress,
};
}
diff --git a/examples/common/statements.ts b/examples/common/statements.ts
index 2a33d6035..c79447832 100644
--- a/examples/common/statements.ts
+++ b/examples/common/statements.ts
@@ -2,7 +2,7 @@ import {
IdStatementBuilder,
verifyIdstatement,
AttributesKeys,
-} from '@concordium/node-sdk';
+} from '@concordium/web-sdk';
/**
* The following example shows how a proof statement can be built up.
diff --git a/examples/common/streamToList.ts b/examples/common/streamToList.ts
index dd3353594..66d8c4988 100644
--- a/examples/common/streamToList.ts
+++ b/examples/common/streamToList.ts
@@ -1,10 +1,7 @@
-import {
- BakerId,
- createConcordiumClient,
- streamToList,
-} from '@concordium/node-sdk';
+import { BakerId, BlockHash, streamToList } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import meow from 'meow';
@@ -36,7 +33,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -48,9 +45,12 @@ const client = createConcordiumClient(
*/
async () => {
- const bakerIds: AsyncIterable = client.getBakerList(
- cli.flags.block
- );
+ const blockHash =
+ cli.flags.block === undefined
+ ? undefined
+ : BlockHash.fromHexString(cli.flags.block);
+
+ const bakerIds: AsyncIterable = client.getBakerList(blockHash);
const bakerList = await streamToList(bakerIds);
diff --git a/examples/composed-examples/findAccountCreationBlock.ts b/examples/composed-examples/findAccountCreationBlock.ts
index 8f6115c9e..0f2af7991 100644
--- a/examples/composed-examples/findAccountCreationBlock.ts
+++ b/examples/composed-examples/findAccountCreationBlock.ts
@@ -1,10 +1,7 @@
-import {
- AccountAddress,
- createConcordiumClient,
- isRpcError,
-} from '@concordium/node-sdk';
+import { AccountAddress, isRpcError } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import meow from 'meow';
@@ -43,7 +40,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -54,7 +51,7 @@ const client = createConcordiumClient(
*/
(async () => {
- const account = new AccountAddress(cli.flags.account);
+ const account = AccountAddress.fromBase58(cli.flags.account);
const accBlock = await client.findEarliestFinalized(async (bi) => {
try {
@@ -84,7 +81,7 @@ const client = createConcordiumClient(
for await (const summary of summaries) {
if (
summary.type === 'accountCreation' &&
- summary.address === account.address
+ AccountAddress.equals(summary.address, account)
) {
console.log(
'Hash of transaction that created the account:',
diff --git a/examples/composed-examples/getEmbeddedSchemaFromInstance.ts b/examples/composed-examples/getEmbeddedSchemaFromInstance.ts
index cf8e96e1b..c1dea6d12 100644
--- a/examples/composed-examples/getEmbeddedSchemaFromInstance.ts
+++ b/examples/composed-examples/getEmbeddedSchemaFromInstance.ts
@@ -1,4 +1,5 @@
-import { createConcordiumClient } from '@concordium/node-sdk';
+import { ContractAddress } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import meow from 'meow';
@@ -45,7 +46,7 @@ const cli = meow(
);
const [address, port] = cli.flags.endpoint.split(':');
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -57,10 +58,11 @@ const client = createConcordiumClient(
(async () => {
// #region documentation-snippet
- const info = await client.getInstanceInfo({
- index: BigInt(cli.flags.index),
- subindex: BigInt(cli.flags.subindex),
- });
+ const contractAddress = ContractAddress.create(
+ cli.flags.index,
+ cli.flags.subindex
+ );
+ const info = await client.getInstanceInfo(contractAddress);
const moduleRef = info.sourceModule;
const schema = await client.getEmbeddedSchema(moduleRef);
// #endregion documentation-snippet
diff --git a/examples/composed-examples/initAndUpdateContract.ts b/examples/composed-examples/initAndUpdateContract.ts
index b2390ab82..c61a63a8f 100644
--- a/examples/composed-examples/initAndUpdateContract.ts
+++ b/examples/composed-examples/initAndUpdateContract.ts
@@ -5,7 +5,6 @@ import {
AccountTransactionType,
CcdAmount,
ContractContext,
- createConcordiumClient,
deserializeReceiveReturnValue,
InitContractPayload,
ModuleReference,
@@ -18,11 +17,16 @@ import {
parseWallet,
buildAccountSigner,
affectedContracts,
-} from '@concordium/node-sdk';
+ ContractName,
+ ReceiveName,
+ Energy,
+ EntrypointName,
+ ReturnValue,
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
import { readFileSync } from 'node:fs';
-import { Buffer } from 'buffer/index.js';
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import meow from 'meow';
@@ -56,7 +60,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -73,15 +77,15 @@ const client = createConcordiumClient(
const walletFile = readFileSync(cli.flags.walletFile, 'utf8');
const wallet = parseWallet(walletFile);
- const sender = new AccountAddress(wallet.value.address);
+ const sender = AccountAddress.fromBase58(wallet.value.address);
const signer = buildAccountSigner(wallet);
- const moduleRef = new ModuleReference(
+ const moduleRef = ModuleReference.fromHexString(
'44434352ddba724930d6b1b09cd58bd1fba6ad9714cf519566d5fe72d80da0d1'
);
- const maxCost = 30000n;
- const contractName = 'weather';
- const receiveName = 'weather.set';
+ const maxCost = Energy.create(30000);
+ const contractName = ContractName.fromStringUnchecked('weather');
+ const receiveName = ReceiveName.fromStringUnchecked('weather.set');
const schema = await client.getEmbeddedSchema(moduleRef);
// --- Initialize Contract --- //
@@ -91,7 +95,7 @@ const client = createConcordiumClient(
// #region documentation-snippet-init-contract
const initHeader: AccountTransactionHeader = {
- expiry: new TransactionExpiry(new Date(Date.now() + 3600000)),
+ expiry: TransactionExpiry.futureMinutes(60),
nonce: (await client.getNextAccountNonce(sender)).nonce,
sender,
};
@@ -103,7 +107,7 @@ const client = createConcordiumClient(
);
const initPayload: InitContractPayload = {
- amount: new CcdAmount(0n),
+ amount: CcdAmount.zero(),
moduleRef: moduleRef,
initName: contractName,
param: initParams,
@@ -142,20 +146,20 @@ const client = createConcordiumClient(
// #region documentation-snippet-update-contract
const updateHeader: AccountTransactionHeader = {
- expiry: new TransactionExpiry(new Date(Date.now() + 3600000)),
+ expiry: TransactionExpiry.futureMinutes(60),
nonce: (await client.getNextAccountNonce(sender)).nonce,
sender,
};
const updateParams = serializeUpdateContractParameters(
contractName,
- 'set',
+ EntrypointName.fromString('set'),
rainyWeather,
schema
);
const updatePayload: UpdateContractPayload = {
- amount: new CcdAmount(0n),
+ amount: CcdAmount.zero(),
address: unwrap(contractAddress),
receiveName,
message: updateParams,
@@ -192,21 +196,18 @@ const client = createConcordiumClient(
const contextPostInit: ContractContext = {
contract: unwrap(contractAddress),
invoker: sender,
- method: 'weather.get',
+ method: ReceiveName.fromString('weather.get'),
};
const invokedPostInit = await client.invokeContract(contextPostInit);
if (invokedPostInit.tag === 'success') {
- const rawReturnValue = Buffer.from(
- unwrap(invokedPostInit.returnValue),
- 'hex'
- );
+ const rawReturnValue = unwrap(invokedPostInit.returnValue);
const returnValue = deserializeReceiveReturnValue(
- rawReturnValue,
+ ReturnValue.toBuffer(rawReturnValue),
schema,
- 'weather',
- 'get'
+ contractName,
+ EntrypointName.fromString('get')
);
console.log('\nThe weather is now:');
console.dir(returnValue, { depth: null, colors: true });
diff --git a/examples/composed-examples/listAccountCreation.ts b/examples/composed-examples/listAccountCreation.ts
index 801fa1c5e..af6e65ade 100644
--- a/examples/composed-examples/listAccountCreation.ts
+++ b/examples/composed-examples/listAccountCreation.ts
@@ -1,10 +1,7 @@
-import {
- createConcordiumClient,
- streamToList,
- unwrap,
-} from '@concordium/node-sdk';
+import { streamToList, unwrap } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import meow from 'meow';
@@ -42,7 +39,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/composed-examples/listInitialAccounts.ts b/examples/composed-examples/listInitialAccounts.ts
index 9e0a2d2b5..73fc8df95 100644
--- a/examples/composed-examples/listInitialAccounts.ts
+++ b/examples/composed-examples/listInitialAccounts.ts
@@ -1,6 +1,7 @@
-import { createConcordiumClient, unwrap } from '@concordium/node-sdk';
+import { unwrap } from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import { credentials } from '@grpc/grpc-js';
-import { parseEndpoint } from '../shared/util';
+import { parseEndpoint } from '../shared/util.js';
import meow from 'meow';
@@ -38,7 +39,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
diff --git a/examples/composed-examples/listNumberAccountTransactions.ts b/examples/composed-examples/listNumberAccountTransactions.ts
index 6837d2c25..c9b21bc99 100644
--- a/examples/composed-examples/listNumberAccountTransactions.ts
+++ b/examples/composed-examples/listNumberAccountTransactions.ts
@@ -1,15 +1,14 @@
import {
AccountAddress,
- createConcordiumClient,
- isAlias,
isTransferLikeSummary,
unwrap,
-} from '@concordium/node-sdk';
-import { credentials } from '@grpc/grpc-js';
-import { parseEndpoint } from '../shared/util';
-
+} from '@concordium/web-sdk';
+import { ConcordiumGRPCNodeClient } from '@concordium/web-sdk/nodejs';
import meow from 'meow';
+import { credentials } from '@grpc/grpc-js';
+import { parseEndpoint } from '../shared/util.js';
+
const cli = meow(
`
Usage
@@ -44,7 +43,7 @@ const cli = meow(
);
const [address, port] = parseEndpoint(cli.flags.endpoint);
-const client = createConcordiumClient(
+const client = new ConcordiumGRPCNodeClient(
address,
Number(port),
credentials.createInsecure()
@@ -90,20 +89,20 @@ const client = createConcordiumClient(
// For each transaction in the block:
trxLoop: for await (const trx of trxStream) {
if (isTransferLikeSummary(trx)) {
- const trxAcc = new AccountAddress(trx.sender);
+ const trxAcc = trx.sender;
// Loop over account dictionary entries to check if account
// is already in dictionary:
for (const [addr, trxSent] of Object.entries(dict)) {
- const acc = new AccountAddress(addr);
- if (isAlias(acc, trxAcc)) {
+ const acc = AccountAddress.fromBase58(addr);
+ if (AccountAddress.isAlias(acc, trxAcc)) {
dict[addr] = trxSent + 1;
break trxLoop;
}
}
// If account is not in dictionary, then add it:
- dict[trx.sender] = 1;
+ dict[AccountAddress.toBase58(trx.sender)] = 1;
}
}
}
diff --git a/examples/package.json b/examples/package.json
index 68896a721..b4b66b555 100644
--- a/examples/package.json
+++ b/examples/package.json
@@ -1,29 +1,31 @@
{
"name": "@concordium/examples",
+ "private": true,
"type": "module",
+ "imports": {
+ "#ed25519": {
+ "node": "./shims/ed25519.node.ts",
+ "default": "@noble/ed25519"
+ }
+ },
"dependencies": {
"@concordium/ccd-js-gen": "workspace:^",
- "@concordium/common-sdk": "workspace:^",
- "@concordium/node-sdk": "workspace:^",
+ "@concordium/web-sdk": "workspace:^",
"@grpc/grpc-js": "^1.3.4",
- "@noble/ed25519": "^1.7.1",
- "@typescript-eslint/eslint-plugin": "^4.28.1",
- "@typescript-eslint/parser": "^4.28.1",
+ "@noble/ed25519": "^2.0.0",
"buffer": "^6.0.3",
- "eslint": "^7.29.0",
- "eslint-config-prettier": "^8.3.0",
- "eslint-plugin-import": "^2.23.4",
- "eslint-plugin-prettier": "^3.4.0",
- "lint-staged": "^12.0.2",
"meow": "11.0",
- "prettier": "^2.3.2",
+ "node-fetch": "^3.3.2"
+ },
+ "devDependencies": {
+ "eslint": "^8.50.0",
"ts-node": "10.9",
- "typescript": "^4.3.5"
+ "typescript": "^5.2.2"
},
"scripts": {
"lint": "eslint . --cache --ext .ts,.tsx --max-warnings 0",
"lint-fix": "yarn lint --fix; exit 0",
"typecheck": "tsc --noEmit",
- "run-example": "node --experimental-specifier-resolution=node --loader ts-node/esm"
+ "run-example": "ts-node"
}
}
diff --git a/examples/readme.md b/examples/readme.md
index 0d5606cd0..c06c8bb33 100644
--- a/examples/readme.md
+++ b/examples/readme.md
@@ -2,8 +2,12 @@
This is a collection of scripts/examples that utilizes the SDK. There are
three directories with examples:
-- `client` containing examples that utilize the client to interact with a Concordium node.
+
+- `ccd-js-gen` containing examples with generate and using smart contract clients.
+- `client` containing examples that utilize the client to interact with
+a Concordium node.
- `cis2` containing examples that helps interact with CIS-2 compliant smart contracts.
+- `cis4` containing examples that helps interact with CIS-4 compliant smart contracts.
- `common` that use various general functions from the library.
To run an example call:
diff --git a/examples/shared/util.ts b/examples/shared/util.ts
index 658665c15..35e45c5dc 100644
--- a/examples/shared/util.ts
+++ b/examples/shared/util.ts
@@ -1,12 +1,19 @@
-import { Base58String, ContractAddress } from '@concordium/node-sdk';
+import { ContractAddress, AccountAddress } from '@concordium/web-sdk';
-export const parseAddress = (input: string): Base58String | ContractAddress => {
+export const parseAddress = (
+ input: string
+): AccountAddress.Type | ContractAddress.Type => {
if (!input.includes(',')) {
- return input;
+ return AccountAddress.fromBase58(input);
}
const [i, si] = input.split(',');
- return { index: BigInt(i), subindex: BigInt(si) };
+ const index = parseInt(i);
+ const subindex = parseInt(si);
+ if (isNaN(index) || isNaN(subindex)) {
+ throw new Error('Invalid address');
+ }
+ return ContractAddress.create(index, subindex);
};
// Regular expression for matching the scheme prefix of a URL.
diff --git a/examples/shims/ed25519.node.ts b/examples/shims/ed25519.node.ts
new file mode 100644
index 000000000..2ebf319b4
--- /dev/null
+++ b/examples/shims/ed25519.node.ts
@@ -0,0 +1,9 @@
+// To add support for node versions <19.
+// From https://www.npmjs.com/package/@noble/ed25519#usage
+import { webcrypto } from 'node:crypto';
+
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore
+if (!globalThis.crypto) globalThis.crypto = webcrypto;
+
+export * from '@noble/ed25519';
diff --git a/examples/tsconfig.json b/examples/tsconfig.json
index e702c49b7..5e3e50075 100644
--- a/examples/tsconfig.json
+++ b/examples/tsconfig.json
@@ -1,5 +1,5 @@
{
- "extends": "ts-node/node12/tsconfig.json",
+ "extends": "ts-node/node16/tsconfig.json",
"ts-node": {
"files": true,
"esm": true
@@ -10,7 +10,8 @@
"esnext"
],
"baseUrl": ".",
- "module": "es2020",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
"target": "es2020"
}
}
diff --git a/package.json b/package.json
index 33d900797..11ab2f2a9 100644
--- a/package.json
+++ b/package.json
@@ -2,12 +2,9 @@
"private": true,
"workspaces": {
"packages": [
- "./packages/rust-bindings",
- "./packages/common",
- "./packages/nodejs",
- "./packages/web",
- "./packages/ccd-js-gen",
- "./examples"
+ "./packages/*",
+ "./examples",
+ "./docs"
]
},
"husky": {
@@ -32,45 +29,31 @@
"singleQuote": true,
"tabWidth": 4
},
+ "type": "module",
"devDependencies": {
- "@babel/core": "^7.17.10",
- "@babel/plugin-transform-modules-commonjs": "^7.12.1",
- "@babel/plugin-transform-runtime": "^7.12.1",
- "@babel/preset-env": "^7.12.1",
- "@knodes/typedoc-plugin-code-blocks": "^0.23.0",
- "@knodes/typedoc-plugin-pages": "^0.23.0",
- "@typescript-eslint/eslint-plugin": "^4.28.1",
- "@typescript-eslint/parser": "^4.28.1",
- "babel-jest": "^27.0.6",
- "babel-loader": "^8.1.0",
- "eslint": "^7.29.0",
+ "@typescript-eslint/eslint-plugin": "^6.7.0",
+ "@typescript-eslint/parser": "^6.7.0",
+ "eslint": "^8.51.0",
"eslint-config-prettier": "^8.3.0",
+ "eslint-import-resolver-exports": "^1.0.0-beta.5",
"eslint-import-resolver-typescript": "^2.7.1",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-prettier": "^3.4.0",
"husky": "^4.2.5",
- "jest": "^27.0.6",
"lint-staged": "^12.0.2",
"markdown-link-check": "^3.1.4",
"markdownlint-cli": "^0.34.0",
- "prettier": "^2.3.2",
- "stream-browserify": "^3.0.0",
- "ts-jest": "^27.0.3",
- "typedoc": "^0.23",
- "typedoc-plugin-merge-modules": "^4.0.1",
- "typedoc-plugin-missing-exports": "^0.23",
- "typescript": "^4.3.5",
- "webpack": "^5.72.0",
- "webpack-cli": "^4.9.2"
+ "prettier": "^2.3.2"
},
"scripts": {
"test": "FORCE_COLOR=true yarn workspaces foreach --no-private run test --passWithNoTests",
"lint": "FORCE_COLOR=true yarn workspaces foreach --no-private run lint",
"lint-fix": "eslint --cache . --fix",
- "markdown:lint": "yarn markdownlint pages/**/*.md packages/*/README.md README.md",
- "markdown:lint-fix": "yarn markdownlint --fix pages/**/*.md packages/*/README.md README.md",
- "markdown:linkcheck": "yarn markdown-link-check --config .markdown-linkcheck.json pages/**/*.md packages/*/README.md README.md",
+ "markdown:lint": "yarn markdownlint docs/README.md docs/pages/**/*.md packages/*/README.md examples/readme.md README.md",
+ "markdown:lint-fix": "yarn markdownlint --fix docs/README.md docs/pages/**/*.md packages/*/README.md examples/readme.md README.md",
+ "markdown:linkcheck": "yarn markdown-link-check --config .markdown-linkcheck.json docs/README.md docs/pages/**/*.md packages/*/README.md examples/readme.md README.md",
"build": "FORCE_COLOR=true yarn workspaces foreach -v -t --no-private run build",
- "build:dev": "FORCE_COLOR=true yarn workspaces foreach -v -t --no-private run build-dev"
+ "build:dev": "FORCE_COLOR=true yarn workspaces foreach -v -t --no-private run build-dev",
+ "clean": "FORCE_COLOR=true yarn workspaces foreach -p --no-private run clean"
}
}
diff --git a/packages/ccd-js-gen/README.md b/packages/ccd-js-gen/README.md
new file mode 100644
index 000000000..27021edba
--- /dev/null
+++ b/packages/ccd-js-gen/README.md
@@ -0,0 +1,561 @@
+
+# Smart Contract Client Generator
+
+Generate TypeScript/JavaScript code for interating with smart contracts and modules on the Concordium blockchain.
+
+- Functions for instantiating new smart contract instances from a module.
+- Functions for dry-running and calling entrypoints of the smart contract.
+- Functions for constructing parameters.
+- Parsing logged events, return values and error messages.
+- Structured types for parameter, logged events, return values and error messages.
+
+The code is generated from deployable smart contract modules, meaning it can be done with any smart contract available
+locally and any smart contract deployed on chain.
+
+## Example usage of a generated client
+
+An example of using a generated client for a token smart contract implementing the
+[CIS-2 standard](https://proposals.concordium.software/CIS/cis-2.html).
+In the example, a contract client is constructed and a transaction calling the
+[`transfer` entrypoint](https://proposals.concordium.software/CIS/cis-2.html#transfer)
+of the smart contract. The parameter includes a transfer of 10 tokens from `sender` address to `receiver` address.
+
+```typescript
+import * as SDK from "@concordium/web-sdk";
+import * as MyContract from "./generated/my-contract.js"; // Code generated from a smart contract module.
+
+const grpcClient = // Setup gRPC client code here ...
+const contractAddress = // Address of the smart contract instance.
+const signer = // Keys for signing an account transaction.
+const sender = // The AccountAddress sending the tokens and signing the transaction.
+const receiver = // The AccountAddress receiving the tokens.
+
+// Create a client for 'my-contract' smart contract.
+const contractClient = await MyContract.create(
+ grpcClient,
+ contractAddress
+);
+
+// Construct the parameter for the 'transfer' entrypoint. The structure of the parameter depends on the contract.
+const parameter: MyContract.TransferParameter = [{
+ tokenId: "",
+ amount: 10,
+ from: { type: 'Account', content: sender },
+ to: { type: 'Account', content: receiver },
+ data: "",
+}];
+
+// Send transaction for invoking the 'transfer' entrypoint of the smart contract.
+const transactionHash = await MyContract.sendTransfer(contractClient, {
+ senderAddress: sender,
+ energy: SDK.Energy.create(12000) // The amount of energy needed will depend on the contract.
+}, parameter, signer);
+```
+
+
+- [Example usage of a generated client](#example-usage-of-a-generated-client)
+- [Install the package](#install-the-package)
+- [Using the CLI](#using-the-cli)
+ - [Example](#example)
+- [Using the library](#using-the-library)
+ - [Generate from smart contract module file](#generate-from-smart-contract-module-file)
+ - [Generate from smart contract module on chain](#generate-from-smart-contract-module-on-chain)
+- [Using the generated client](#using-the-generated-client)
+ - [Generated module client](#generated-module-client)
+ - [The client type](#the-client-type)
+ - [function `create`](#function-create)
+ - [function `createUnchecked`](#function-createunchecked)
+ - [const `moduleReference`](#const-modulereference)
+ - [function `getModuleSource`](#function-getmodulesource)
+ - [type `Parameter`](#type-contractnameparameter)
+ - [function `instantiate`](#function-instantiatecontractname)
+ - [Generated contract client](#generated-contract-client)
+ - [The contract client type](#the-contract-client-type)
+ - [function `create`](#function-create-1)
+ - [function `createUnchecked`](#function-createunchecked-1)
+ - [const `moduleReference`](#const-modulereference-1)
+ - [type `Event`](#type-event)
+ - [function `parseEvent`](#function-parseevent)
+ - [type `Parameter`](#type-entrypointnameparameter)
+ - [function `send`](#function-sendentrypointname)
+ - [function `dryRun`](#function-dryrunentrypointname)
+ - [type `ReturnValue`](#type-returnvalueentrypointname)
+ - [function `parseReturnValue`](#function-parsereturnvalueentrypointname)
+ - [type `ErrorMessage`](#type-errormessageentrypointname)
+ - [function `parseErrorMessage`](#function-parseerrormessageentrypointname)
+
+
+## Install the package
+
+Install the package, saving it to `devDependencies`:
+
+**npm**
+
+```bash
+npm install --save-dev @concordium/ccd-js-gen
+```
+
+**yarn**
+
+```bash
+yarn add --dev @concordium/ccd-js-gen
+```
+
+**pnpm**
+
+```bash
+pnpm install --save-dev @concordium/ccd-js-gen
+```
+
+> The package can also be used directly using `npx`, without first adding it as a dependency,
+however it is recommended to add it in `package.json` to keep track the exact version used when
+generating the code, as different version might produce different code.
+
+## Using the CLI
+
+This package provides the `ccd-js-gen` command, which can be used from the commandline.
+
+**Options**:
+
+- `-m, --module ` Path to the smart contract module.
+- `-o, --out-dir ` Directory to use for the generated code.
+
+### Example
+
+To generate smart contract clients into a directory `generated` from the smart contract
+module `./my-contract.wasm.v1`:
+
+```bash
+ccd-js-gen --module ./my-contract.wasm.v1 --out-dir ./generated
+```
+
+> For a dapp project, it is recommended to have this as part of a script in `package.json`.
+
+## Using the library
+
+This package can be used programmatically as well.
+
+```typescript
+import * as ccdJsGen from "@concordium/ccd-js-gen"
+```
+
+### Generate from smart contract module file
+
+To generate smart contract clients for a smart contract module file,
+either downloaded from the blockchain or build from the smart contract source code:
+
+```typescript
+import * as ccdJsGen from "@concordium/ccd-js-gen"
+
+const moduleFilePath = "./my-contract.wasm.v1"; // Path to smart contract module.
+const outDirPath = "./generated"; // The directory to use for the generated files.
+
+// Read the module and generate the smart contract clients.
+console.log('Generating smart contract module clients.')
+await ccdJsGen.generateContractClientsFromFile(moduleFilePath, outDirPath);
+console.log('Code generation was successful.')
+```
+
+### Generate from smart contract module on chain
+
+To generate smart contract clients for a smart contract module on chain,
+you need access to the gRPC of a Concordium node.
+Use `@concordium/web-sdk` to download the smart contract module and use it to generate the clients.
+
+```typescript
+import * as ccdJsGen from "@concordium/ccd-js-gen"
+import * as SDK from "@concordium/web-sdk"
+
+const outDirPath = "./generated"; // The directory to use for the generated files.
+const outputModuleName = "wCCD-module"; // The name to give the output smart contract module.
+
+const grpcClient = ...; // A Concordium gRPC client from @concordium/web-sdk.
+const moduleRef = SDK.ModuleReference.fromHexString('');
+
+// Fetch the smart contract module source from chain.
+const moduleSource = await grpcClient.getModuleSource(moduleRef);
+
+// Generate the smart contract clients from module source.
+console.info('Generating smart contract module clients.');
+await ccdJsGen.generateContractClients(moduleSource, outputModuleName, outDirPath);
+console.info('Code generation was successful.');
+```
+
+## Using the generated client
+
+The generator produces a file with functions for interacting with the smart contract module and files
+for each smart contract in the smart contract module used.
+
+For example: generating clients for a smart contract module `my-module` containing
+the smart contracts `my-contract-a` and `my-contract-b`.
+into the directory `./generated` produces the following structure:
+
+```bash
+generated/
+├─ my-module.js // Functions for interacting with the 'my-module' smart contract module on chain.
+├─ my-module_my-contract-a.js // Functions for interacting with the 'my-contract-a' smart contract.
+└─ my-module_my-contract-b.js // Functions for interacting with the 'my-contract-b' smart contract.
+```
+
+> There might also be type declarations (`.d.ts`) for TypeScript, depending on the provided options.
+
+### Generated module client
+
+A file is produced with a client for interacting with the smart contract module.
+This provides functions for instantiating smart contract instances.
+
+An example of importing a smart contract module generated from a `my-module.wasm.v1` file:
+
+```typescript
+import * as MyModule from "./generated/my-module.js";
+```
+
+#### The client type
+
+The type representing the client for the smart contract module is accessable using `MyModule.Type`.
+
+#### function `create`
+
+Construct a module client for interacting with a smart contract module on chain.
+This function ensures the smart contract module is deployed on chain and throws an error otherwise.
+
+**Parameter:** The function takes a gRPC client from '@concordium/web-sdk'.
+
+```typescript
+const grpcClient = ...; // Concordium gRPC client from '@concordium/web-sdk'.
+const myModule: MyModule.Type = await MyModule.create(grpcClient);
+```
+
+#### function `createUnchecked`
+
+Construct a module client for interacting with a smart contract module on chain.
+This function _skips_ the check of the smart contract module being deployed on chain and leaves it
+up to the caller to ensure this.
+
+**Parameter:** The function takes a gRPC client from '@concordium/web-sdk'.
+
+```typescript
+const grpcClient = ...; // Concordium gRPC client from '@concordium/web-sdk'.
+const myModule: MyModule.Type = MyModule.createUnchecked(grpcClient);
+```
+
+> To run the checks manually use `await MyModule.checkOnChain(myModule);`.
+
+#### const `moduleReference`
+
+Variable with the reference of the smart contract module.
+
+```typescript
+const ref = MyModule.moduleReference;
+```
+
+#### function `getModuleSource`
+
+Get the module source of the deployed smart contract module from chain.
+
+```typescript
+const myModule: MyModule.Type = ...; // Generated module client
+const moduleSource = await MyModule.getModuleSource(myModule);
+```
+
+#### type `Parameter`
+
+Type representing the parameter for when instantiating a smart contract.
+The type is named `Parameter` where `` is the smart contract name in Pascal case.
+
+_This is only generated when the schema contains init-function parameter type._
+
+#### function `instantiate`
+
+For each smart contract in module a function for instantiating new instance is produced.
+These are named `instantiate` where `` is the smart contract name in Pascal case.
+
+An example for a smart contract module containing a smart contract named `my-contract`,
+the function becomes `instantiateMyContract`.
+
+**Parameters**
+
+The function parameters are:
+
+- `moduleClient` The client of the on-chain smart contract module.
+- `transactionMetadata` Metadata related to constructing the transaction, such as energy and CCD amount to include.
+ - `senderAddress` The address invoking this call.
+ - `energy` The energy reserved for executing this transaction.
+ - `amount` The amount of CCD included in the transaction. Defaults to 0.
+ - `expiry` Expiry date of the transaction. Defaults to 5 minutes from when constructing the transaction.
+- `parameter` Parameter to provide the smart contract module for the instantiation.
+
+ _With schema type:_
+ If the schema contains type information for the parameter,
+ a type for the parameter is generated and used for this function.
+ The type is named `Parameter` where `` is the smart contract name in Pascal case.
+
+ _Without schema type:_
+ If no schema information is present, the function uses the generic `Parameter` from `@concordium/web-sdk`.
+
+- `signer` The keys to use for signing the transaction.
+
+**Returns**: Promise with the hash of the transaction.
+
+```typescript
+// Generated module client.
+const myModule: MyModule.Type = await MyModule.create(grpcClient);
+// The keys to use for signing the transaction.
+const signer = ...;
+// Transaction meta information.
+const transactionMeta = {
+ // The account address signing the transaction.
+ senderAddress: SDK.AccountAddress.fromBase58("357EYHqrmMiJBmUZTVG5FuaMq4soAhgtgz6XNEAJaXHW3NHaUf"),
+ // The amount of energy needed will depend on the contract.
+ energy: SDK.Energy.create(12000),
+};
+// Parameter to pass the smart contract init-function. The structure depends on the contract.
+const parameter = ...;
+const transactionHash = await MyModule.instantiateMyContract(myModule, transactionMeta, parameter, signer);
+```
+
+### Generated contract client
+
+For each of the smart contracts in the module a file is produced named after the smart contract.
+Each file contains functions for interacting with an instance of this smart contract.
+
+An example of importing a smart contract contract client generated from a module containing a
+smart contract named `my-contract`:
+
+```typescript
+import * as MyContract from "./generated/my-module_my-contract.js";
+```
+
+#### The contract client type
+
+The type representing the client for the smart contract instance is accessable using `MyContract.Type`.
+
+#### function `create`
+
+Construct a client for interacting with a smart contract instance on chain.
+This function ensures the smart contract instance exists on chain, and that it is using a
+smart contract module with a matching reference.
+
+**Parameters:**
+
+- `grpcClient` The function takes a gRPC client from `@concordium/web-sdk`.
+- `contractAddress` The contract address of the smart contract instance.
+
+```typescript
+const grpcClient = ...; // Concordium gRPC client from '@concordium/web-sdk'.
+const contractAddress = SDK.ContractAddress.create(...); // The address of the contract instance.
+const myContract: MyContract.Type = await MyContract.create(grpcClient, contractAddress);
+```
+
+#### function `createUnchecked`
+
+Construct a client for interacting with a smart contract instance on chain.
+This function _skips_ the check ensuring the smart contract instance exists on chain,
+and that it is using a smart contract module with a matching reference, leaving it up to the caller to ensure this.
+
+**Parameters:**
+
+- `grpcClient` The function takes a gRPC client from `@concordium/web-sdk`.
+- `contractAddress` The contract address of the smart contract instance.
+
+```typescript
+const grpcClient = ...; // Concordium gRPC client from '@concordium/web-sdk'.
+const contractAddress = SDK.ContractAddress.create(...); // The address of the contract instance.
+const myContract: MyContract.Type = MyContract.createUnchecked(grpcClient, contractAddress);
+```
+
+> To run the checks manually use `await MyContract.checkOnChain(myContract);`.
+
+#### const `moduleReference`
+
+Variable with the reference of the smart contract module used by this contract.
+
+```typescript
+const ref = MyContract.moduleReference;
+```
+
+#### type `Event`
+
+Type representing the structured event logged by this smart contract.
+
+_This is only generated when the schema contains contract event type._
+
+#### function `parseEvent`
+
+Parse a raw contract event logged by this contract into a structured representation.
+
+_This is only generated when the schema contains contract event type._
+
+**Parameter:** `event` The contract event to parse.
+
+**Returns:** The structured event of the `Event` type (see type above).
+
+```typescript
+const rawContractEvent = ...; // The unparsed contract event from some transaction.
+const event: MyContract.Event = MyContract.parseEvent(rawContractEvent);
+```
+
+#### type `Parameter`
+
+Type representing the parameter of for an entrypoint.
+The type is named `Parameter` where `` is the name of the entrypoint in Pascal case.
+
+_This is only generated when the schema contains contract entrypoint parameter type._
+
+#### function `send`
+
+For each entrypoint of the smart contract a function for sending a transaction calling this entrypoint is produced.
+These are named `send` where `` is the name of the entrypoint in Pascal case.
+
+An example for a smart contract with an entrypoint named `launch-rocket`, the function becomes `sendLaunchRocket`.
+
+**Parameters**
+
+The function parameters are:
+
+- `contractClient` The client of the smart contract instance.
+- `transactionMetadata` Metadata related to constructing the transaction, such as energy and CCD amount to include.
+ - `senderAddress` The address invoking this call.
+ - `energy` The energy reserved for executing this transaction.
+ - `amount` The amount of CCD included in the transaction. Defaults to 0.
+ - `expiry` Expiry date of the transaction. Defaults to 5 minutes from when constructing the transaction.
+- `parameter` Parameter to provide to the smart contract entrypoint.
+
+ _With schema type:_
+ If the schema contains type information for the parameter,
+ a type for the parameter is generated and used for this function (see type above).
+
+ _Without schema type:_
+ If no schema information is present, the function uses the generic `Parameter` from `@concordium/web-sdk`.
+
+- `signer` The keys of to use for signing the transaction.
+
+**Returns**: Promise with the hash of the transaction.
+
+```typescript
+// Generated contract client.
+const myContract: MyContract.Type = await MyContract.create(grpcClient, contractAddress);
+// The keys to use for signing the transaction.
+const signer = ...;
+// Transaction meta information.
+const transactionMeta = {
+ // The account address signing the transaction.
+ senderAddress: SDK.AccountAddress.fromBase58("357EYHqrmMiJBmUZTVG5FuaMq4soAhgtgz6XNEAJaXHW3NHaUf"),
+ // The amount of energy needed will depend on the contract.
+ energy: SDK.Energy.create(12000),
+};
+// Parameter to pass the smart contract entrypoint. The structure depends on the contract.
+const parameter = ...;
+// Send the transaction calling the `launch-rockets` entrypoint.
+const transactionHash = await MyContract.sendLaunchRocket(myContract, transactionMeta, parameter, signer);
+```
+
+#### function `dryRun`
+
+For each entrypoint of the smart contract a function for dry-running a transaction calling this entrypoint is produced.
+These are named `dryRun` where `` is the name of the entrypoint in Pascal case.
+
+An example for a smart contract with an entrypoint named `launch-rocket`, the function becomes `dryRunLaunchRocket`.
+
+**Parameters**
+
+The function parameters are:
+
+- `contractClient` The client of the smart contract instance.
+- `parameter` Parameter to provide to the smart contract entrypoint.
+
+ _With schema type:_
+ If the schema contains type information for the parameter,
+ a type for the parameter is generated and used for this function (see type above).
+
+ _Without schema type:_
+ If no schema information is present, the function uses the generic `Parameter` from `@concordium/web-sdk`.
+
+- `invokeMetadata` Optional transaction metadata object with the following optional properties:
+ - `invoker` The address invoking this call, can be either an `AccountAddress` or `ContractAddress`.
+ Defaults to an `AccountAddress` (Base58check encoding of 32 bytes with value zero).
+ - `amount` The amount of CCD included in the transaction. Defaults to 0.
+ - `energy` The energy reserved for executing this transaction. Defaults to max energy possible.
+- `blockHash` (optional) Provide to specify the block hash, for which the state will be used for dry-running.
+ When not provided, the last finalized block is used.
+
+**Returns**: Promise with the invoke result.
+
+```typescript
+const myContract: MyContract.Type = ...; // Generated contract client.
+const parameter = ...; // Parameter to pass the smart contract entrypoint.
+// Transaction metadata for invoking.
+const metadata = {
+ // Amount of CCD to include in the transaction.
+ amount: SDK.CcdAmount.fromCcd(10),
+ // Invoker of the transaction
+ invoker: SDK.AccountAddress.fromBase58("357EYHqrmMiJBmUZTVG5FuaMq4soAhgtgz6XNEAJaXHW3NHaUf")
+};
+const invokeResult = await MyContract.dryRunLaunchRocket(myContract, parameter, metadata);
+```
+
+#### type `ReturnValue`
+
+Type representing the return value from a successful dry-run/invocation of an entrypoint.
+The type is named `ReturnValue` where `` is the name of
+the relevant entrypoint in Pascal case.
+
+_This is only generated when the schema contains entrypoint return value type._
+
+#### function `parseReturnValue`
+
+For each entrypoint of the smart contract a function for parsing the return value in a
+successful invocation/dry-running.
+These are named `parseReturnValue` where `` is the name
+of the entrypoint in Pascal case.
+
+_This is only generated when the schema contains entrypoint return value type._
+
+An example for a smart contract with an entrypoint named `launch-rocket`, the function
+becomes `parseReturnValueLaunchRocket`.
+
+**Parameter:** `invokeResult` The result from dry-running a transactions calling the entrypoint.
+
+**Returns:** Undefined if the invocation was not successful otherwise the parsed return
+value of the type `ReturnValue`.
+
+```typescript
+// Dry run the entrypoint
+const invokeResult = await MyContract.dryRunLaunchRocket(myContract, invoker, parameter);
+
+// Parse the return value
+const returnValue: MyContract.ReturnValueLaunchRocket | undefined = parseReturnValueLaunchRocket(invokeResult);
+```
+
+#### type `ErrorMessage`
+
+Type representing the error message from a rejected dry-run/invocation of an entrypoint.
+The type is named `ErrorMessage` where `` is the name of
+the relevant entrypoint in Pascal case.
+
+_This is only generated when the schema contains entrypoint error message type._
+
+#### function `parseErrorMessage`
+
+For each entrypoint of the smart contract a function for parsing the error message in a
+rejected invocation/dry-running.
+These are named `parseErrorMessage` where `` is the name
+of the entrypoint in Pascal case.
+
+_This is only generated when the schema contains entrypoint error message type._
+
+An example for a smart contract with an entrypoint named `launch-rocket`, the function
+becomes `parseErrorMessageLaunchRocket`.
+
+**Parameter:** `invokeResult` The result from dry-running a transactions calling some entrypoint.
+
+**Returns:** Undefined if the invocation was not rejected, otherwise the parsed error
+message of the type `ReturnValue`.
+
+```typescript
+// Dry run the entrypoint
+const invokeResult = await MyContract.dryRunLaunchRocket(myContract, invoker, parameter);
+
+// Parse the error message
+const message: MyContract.ErrorMessageLaunchRocket | undefined = MyContract.parseErrorMessageLaunchRocket(invokeResult);
+```
diff --git a/packages/ccd-js-gen/bin/ccd-js-gen.js b/packages/ccd-js-gen/bin/ccd-js-gen.js
index 76a857b7c..295dba800 100755
--- a/packages/ccd-js-gen/bin/ccd-js-gen.js
+++ b/packages/ccd-js-gen/bin/ccd-js-gen.js
@@ -1,4 +1,3 @@
-#!/usr/bin/env node
-// eslint-disable-next-line @typescript-eslint/no-var-requires
-const cli = require('../lib/src/cli.js');
-cli.main();
+#!/usr/bin/env -S node --no-warnings
+import { main } from '../lib/src/cli.js';
+main();
diff --git a/packages/ccd-js-gen/jest.config.ts b/packages/ccd-js-gen/jest.config.ts
new file mode 100644
index 000000000..f9cd4484d
--- /dev/null
+++ b/packages/ccd-js-gen/jest.config.ts
@@ -0,0 +1,14 @@
+import type { Config } from 'jest';
+import type {} from 'ts-jest';
+
+const config: Config = {
+ preset: 'ts-jest/presets/js-with-ts-esm',
+ moduleNameMapper: {
+ '^(\\.\\.?\\/.+)\\.js$': '$1', // Remap esmodule file extensions
+ },
+ transformIgnorePatterns: [
+ 'node_modules/(?!@noble/ed25519)', // @noble/ed25519 is an ES module only
+ ],
+};
+
+export default config;
diff --git a/packages/ccd-js-gen/package.json b/packages/ccd-js-gen/package.json
index 79336522c..f277741c8 100644
--- a/packages/ccd-js-gen/package.json
+++ b/packages/ccd-js-gen/package.json
@@ -2,16 +2,19 @@
"name": "@concordium/ccd-js-gen",
"version": "1.0.0",
"description": "Generate JS clients for the Concordium Blockchain",
+ "type": "module",
"bin": "bin/ccd-js-gen.js",
"main": "lib/src/lib.js",
+ "module": "lib/src/lib.js",
"typings": "lib/src/lib.d.ts",
"scripts": {
- "build": "tsc",
+ "build": "tsc -p tsconfig.build.json",
"build-dev": "yarn build",
"clean": "rm -r lib",
"lint": "eslint src/** bin/** --cache --ext .ts,.js --max-warnings 0",
"lint-fix": "yarn --silent lint --fix; exit 0",
- "test": "echo \"Error: no test specified\" && exit 1"
+ "test": "jest",
+ "test-ci": "yarn test"
},
"keywords": [
"concordium",
@@ -28,22 +31,23 @@
"url": "https://concordium.com"
},
"license": "Apache-2.0",
+ "peerDependencies": {
+ "@concordium/web-sdk": "7.0.0"
+ },
"dependencies": {
- "@concordium/common-sdk": "9.4.0",
+ "@concordium/web-sdk": "7.0.0",
"buffer": "^6.0.3",
"commander": "^11.0.0",
+ "sanitize-filename": "^1.6.3",
"ts-morph": "^19.0.0"
},
"devDependencies": {
+ "@types/jest": "^26.0.23",
"@types/node": "^20.5.0",
- "@typescript-eslint/eslint-plugin": "^4.28.1",
- "@typescript-eslint/parser": "^4.28.1",
- "eslint": "^7.29.0",
- "eslint-config-prettier": "^8.3.0",
- "eslint-plugin-import": "^2.23.4",
- "eslint-plugin-prettier": "^3.4.0",
- "prettier": "^2.3.2",
- "typescript": "^4.3.5"
+ "eslint": "^8.50.0",
+ "jest": "^29.6.2",
+ "ts-jest": "^29.1.1",
+ "typescript": "^5.2.2"
},
"prettier": {
"singleQuote": true,
diff --git a/packages/ccd-js-gen/src/cli.ts b/packages/ccd-js-gen/src/cli.ts
index fe66d0c6a..a86a82a98 100644
--- a/packages/ccd-js-gen/src/cli.ts
+++ b/packages/ccd-js-gen/src/cli.ts
@@ -2,8 +2,8 @@
This file contains code for building the command line inferface to the ccd-js-gen library.
*/
import { Command } from 'commander';
-import packageJson from '../package.json';
-import * as lib from './lib';
+import packageJson from '../package.json' assert { type: 'json' };
+import * as lib from './lib.js';
/** Type representing the CLI options/arguments and needs to match the options set with commander.js */
type Options = {
@@ -13,11 +13,11 @@ type Options = {
outDir: string;
};
-// Main function, which is called be the executable script in `bin`.
+// Main function, which is called in the executable script in `bin`.
export async function main(): Promise {
const program = new Command();
program
- .name(packageJson.name)
+ .name('ccd-js-gen')
.description(packageJson.description)
.version(packageJson.version)
.requiredOption(
@@ -30,5 +30,18 @@ export async function main(): Promise {
)
.parse(process.argv);
const options = program.opts();
- await lib.generateContractClientsFromFile(options.module, options.outDir);
+ console.log('Generating smart contract clients...');
+
+ const startTime = Date.now();
+ await lib.generateContractClientsFromFile(options.module, options.outDir, {
+ onProgress(update) {
+ if (update.type === 'Progress') {
+ console.log(
+ `[${update.doneItems}/${update.totalItems}] ${update.spentTime}ms`
+ );
+ }
+ },
+ });
+
+ console.log(`Done in ${Date.now() - startTime}ms`);
}
diff --git a/packages/ccd-js-gen/src/lib.ts b/packages/ccd-js-gen/src/lib.ts
index dcab02646..1798c9a83 100644
--- a/packages/ccd-js-gen/src/lib.ts
+++ b/packages/ccd-js-gen/src/lib.ts
@@ -1,7 +1,8 @@
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import * as tsm from 'ts-morph';
-import * as SDK from '@concordium/common-sdk';
+import * as SDK from '@concordium/web-sdk';
+import sanitize from 'sanitize-filename';
/**
* Output options for the generated code.
@@ -16,17 +17,35 @@ export type OutputOptions =
| 'TypedJavaScript'
| 'Everything';
-/** Options for generating clients */
+/** Options for generating clients. */
export type GenerateContractClientsOptions = {
- /** Options for the output */
+ /** Options for the output. */
output?: OutputOptions;
+ /** Callback for getting notified on progress. */
+ onProgress?: NotifyProgress;
+};
+
+/** Callback for getting notified on progress. */
+export type NotifyProgress = (progress: Progress) => void;
+
+/**
+ * Progress notification
+ */
+export type Progress = {
+ type: 'Progress';
+ /** Total number of 'items' to be generated. */
+ totalItems: number;
+ /** Number of 'items' generated at the time of this notification. */
+ doneItems: number;
+ /** Number of milliseconds spent on the previous item. */
+ spentTime: number;
};
/**
* Generate smart contract client code for a given smart contract module file.
- * @param modulePath Path to the smart contract module.
- * @param outDirPath Path to the directory to use for the output.
- * @param options Options for generating the clients.
+ * @param {string} modulePath Path to the smart contract module.
+ * @param {string} outDirPath Path to the directory to use for the output.
+ * @param {GenerateContractClientsOptions} [options] Options for generating the clients.
* @throws If unable to: read provided file at `modulePath`, parse the provided smart contract module or write to provided directory `outDirPath`.
*/
export async function generateContractClientsFromFile(
@@ -52,10 +71,10 @@ export async function generateContractClientsFromFile(
/**
* Generate smart contract client code for a given smart contract module.
- * @param moduleSource Buffer with bytes for the smart contract module.
- * @param outName Name for the output file.
- * @param outDirPath Path to the directory to use for the output.
- * @param options Options for generating the clients.
+ * @param {SDK.VersionedModuleSource} moduleSource Buffer with bytes for the smart contract module.
+ * @param {string} outName Name for the output file.
+ * @param {string} outDirPath Path to the directory to use for the output.
+ * @param {GenerateContractClientsOptions} [options] Options for generating the clients.
* @throws If unable to write to provided directory `outDirPath`.
*/
export async function generateContractClients(
@@ -65,12 +84,6 @@ export async function generateContractClients(
options: GenerateContractClientsOptions = {}
): Promise {
const outputOption = options.output ?? 'Everything';
- const moduleInterface = await SDK.parseModuleInterface(moduleSource);
- const outputFilePath = path.format({
- dir: outDirPath,
- name: outName,
- ext: '.ts',
- });
const compilerOptions: tsm.CompilerOptions = {
outDir: outDirPath,
@@ -78,10 +91,15 @@ export async function generateContractClients(
outputOption === 'Everything' || outputOption === 'TypedJavaScript',
};
const project = new tsm.Project({ compilerOptions });
- const sourceFile = project.createSourceFile(outputFilePath, '', {
- overwrite: true,
- });
- addModuleClients(sourceFile, moduleInterface);
+
+ await generateCode(
+ project,
+ outName,
+ outDirPath,
+ moduleSource,
+ options.onProgress
+ );
+
if (outputOption === 'Everything' || outputOption === 'TypeScript') {
await project.save();
}
@@ -94,179 +112,997 @@ export async function generateContractClients(
}
}
-/** Iterates a module interface adding code to the provided source file. */
-function addModuleClients(
- sourceFile: tsm.SourceFile,
- moduleInterface: SDK.ModuleInterface
+/**
+ * Iterates a module interface building source files in the project.
+ * @param {tsm.Project} project The project to use for creating sourcefiles.
+ * @param {string} outModuleName The name for outputting the module client file.
+ * @param {string} outDirPath The directory to use for outputting files.
+ * @param {SDK.VersionedModuleSource} moduleSource The source of the smart contract module.
+ * @param {NotifyProgress} [notifyProgress] Callback to report progress.
+ */
+async function generateCode(
+ project: tsm.Project,
+ outModuleName: string,
+ outDirPath: string,
+ moduleSource: SDK.VersionedModuleSource,
+ notifyProgress?: NotifyProgress
) {
- sourceFile.addImportDeclaration({
- namespaceImport: 'SDK',
- moduleSpecifier: '@concordium/common-sdk',
+ const [moduleInterface, moduleRef, rawModuleSchema] = await Promise.all([
+ SDK.parseModuleInterface(moduleSource),
+ SDK.calculateModuleReference(moduleSource),
+ SDK.getEmbeddedModuleSchema(moduleSource),
+ ]);
+
+ let totalItems = 0;
+ for (const contracts of moduleInterface.values()) {
+ totalItems += contracts.entrypointNames.size;
+ }
+ let doneItems = 0;
+ notifyProgress?.({ type: 'Progress', totalItems, doneItems, spentTime: 0 });
+
+ const moduleSchema =
+ rawModuleSchema === null
+ ? null
+ : SDK.parseRawModuleSchema(rawModuleSchema);
+
+ const outputFilePath = path.format({
+ dir: outDirPath,
+ name: outModuleName,
+ ext: '.ts',
+ });
+ const moduleSourceFile = project.createSourceFile(outputFilePath, '', {
+ overwrite: true,
});
+ const moduleClientId = 'moduleClient';
+ const moduleClientType = `${toPascalCase(outModuleName)}Module`;
+ const internalModuleClientId = 'internalModuleClient';
+
+ generateModuleBaseCode(
+ moduleSourceFile,
+ moduleRef,
+ moduleClientId,
+ moduleClientType,
+ internalModuleClientId
+ );
for (const contract of moduleInterface.values()) {
- const contractNameId = 'contractName';
- const genericContractId = 'genericContract';
- const grpcClientId = 'grpcClient';
- const contractAddressId = 'contractAddress';
- const dryRunId = 'dryRun';
- const contractClassId = toPascalCase(contract.contractName);
- const contractDryRunClassId = `${contractClassId}DryRun`;
-
- const classDecl = sourceFile.addClass({
- docs: ['Smart contract client for a contract instance on chain.'],
+ const contractSchema: SDK.SchemaContractV3 | undefined =
+ moduleSchema?.module.contracts.get(contract.contractName);
+
+ generactionModuleContractCode(
+ moduleSourceFile,
+ contract.contractName,
+ moduleClientId,
+ moduleClientType,
+ internalModuleClientId,
+ moduleRef,
+ contractSchema
+ );
+
+ const contractOutputFilePath = path.format({
+ dir: outDirPath,
+ name: `${outModuleName}_${sanitize(contract.contractName, {
+ replacement: '-',
+ })}`,
+ ext: '.ts',
+ });
+ const contractSourceFile = project.createSourceFile(
+ contractOutputFilePath,
+ '',
+ {
+ overwrite: true,
+ }
+ );
+
+ const contractClientType = `${toPascalCase(
+ contract.contractName
+ )}Contract`;
+ const contractClientId = 'contractClient';
+
+ generateContractBaseCode(
+ contractSourceFile,
+ contract.contractName,
+ contractClientId,
+ contractClientType,
+ moduleRef,
+ contractSchema
+ );
+
+ for (const entrypointName of contract.entrypointNames) {
+ const startTime = Date.now();
+ const entrypointSchema =
+ contractSchema?.receive.get(entrypointName);
+ generateContractEntrypointCode(
+ contractSourceFile,
+ contract.contractName,
+ contractClientId,
+ contractClientType,
+ entrypointName,
+ entrypointSchema
+ );
+ const spentTime = Date.now() - startTime;
+ doneItems++;
+ notifyProgress?.({
+ type: 'Progress',
+ totalItems,
+ doneItems,
+ spentTime,
+ });
+ }
+ }
+}
+
+/**
+ * Generate code for a smart contract module client.
+ * @param moduleSourceFile The sourcefile of the module.
+ * @param moduleRef The module reference.
+ * @param moduleClientId The identifier to use for the module client.
+ * @param moduleClientType The identifier to use for the type of the module client.
+ * @param internalModuleClientId The identifier to use for referencing the internal module client.
+ */
+function generateModuleBaseCode(
+ moduleSourceFile: tsm.SourceFile,
+ moduleRef: SDK.ModuleReference.Type,
+ moduleClientId: string,
+ moduleClientType: string,
+ internalModuleClientId: string
+) {
+ const moduleRefId = 'moduleReference';
+
+ moduleSourceFile.addImportDeclaration({
+ namespaceImport: 'SDK',
+ moduleSpecifier: '@concordium/web-sdk',
+ });
+
+ moduleSourceFile.addVariableStatement({
+ isExported: true,
+ declarationKind: tsm.VariableDeclarationKind.Const,
+ docs: [
+ 'The reference of the smart contract module supported by the provided client.',
+ ],
+ declarations: [
+ {
+ name: moduleRefId,
+ type: 'SDK.ModuleReference.Type',
+ initializer: `/*#__PURE__*/ SDK.ModuleReference.fromHexString('${moduleRef.moduleRef}')`,
+ },
+ ],
+ });
+
+ const moduleClassDecl = moduleSourceFile.addClass({
+ docs: [
+ `Client for an on-chain smart contract module with module reference '${moduleRef.moduleRef}', can be used for instantiating new smart contract instances.`,
+ ],
+ name: moduleClientType,
+ properties: [
+ {
+ docs: [
+ 'Having a private field prevents similar structured objects to be considered the same type (similar to nominal typing).',
+ ],
+ scope: tsm.Scope.Private,
+ name: '__nominal',
+ initializer: 'true',
+ },
+ {
+ docs: ['Generic module client used internally.'],
+ scope: tsm.Scope.Public,
+ isReadonly: true,
+ name: internalModuleClientId,
+ type: 'SDK.ModuleClient.Type',
+ },
+ ],
+ });
+
+ moduleClassDecl
+ .addConstructor({
+ docs: [
+ 'Constructor is only ment to be used internally in this module. Use functions such as `create` or `createUnchecked` for construction.',
+ ],
+ parameters: [
+ {
+ name: internalModuleClientId,
+ type: 'SDK.ModuleClient.Type',
+ },
+ ],
+ })
+ .setBodyText(
+ `this.${internalModuleClientId} = ${internalModuleClientId};`
+ );
+
+ moduleSourceFile.addTypeAlias({
+ docs: [
+ `Client for an on-chain smart contract module with module reference '${moduleRef.moduleRef}', can be used for instantiating new smart contract instances.`,
+ ],
+ name: 'Type',
+ isExported: true,
+ type: moduleClientType,
+ });
+
+ const grpcClientId = 'grpcClient';
+ moduleSourceFile
+ .addFunction({
+ docs: [
+ [
+ `Construct a ${moduleClientType} client for interacting with a smart contract module on chain.`,
+ 'This function ensures the smart contract module is deployed on chain.',
+ `@param {SDK.ConcordiumGRPCClient} ${grpcClientId} - The concordium node client to use.`,
+ '@throws If failing to communicate with the concordium node or if the module reference is not present on chain.',
+ `@returns {${moduleClientType}} A module client ensured to be deployed on chain.`,
+ ].join('\n'),
+ ],
+ isExported: true,
+ isAsync: true,
+ name: 'create',
+ parameters: [
+ {
+ name: grpcClientId,
+ type: 'SDK.ConcordiumGRPCClient',
+ },
+ ],
+ returnType: `Promise<${moduleClientType}>`,
+ })
+ .setBodyText(
+ [
+ `const moduleClient = await SDK.ModuleClient.create(${grpcClientId}, ${moduleRefId});`,
+ `return new ${moduleClientType}(moduleClient);`,
+ ].join('\n')
+ );
+ moduleSourceFile
+ .addFunction({
+ docs: [
+ [
+ `Construct a ${moduleClientType} client for interacting with a smart contract module on chain.`,
+ 'It is up to the caller to ensure the module is deployed on chain.',
+ `@param {SDK.ConcordiumGRPCClient} ${grpcClientId} - The concordium node client to use.`,
+ `@returns {${moduleClientType}}`,
+ ].join('\n'),
+ ],
isExported: true,
- name: contractClassId,
- properties: [
+ name: 'createUnchecked',
+ parameters: [
{
- docs: [
- 'Name of the smart contract supported by this client.',
- ],
- scope: tsm.Scope.Public,
- isReadonly: true,
- name: contractNameId,
- type: 'string',
- initializer: `'${contract.contractName}'`,
+ name: grpcClientId,
+ type: 'SDK.ConcordiumGRPCClient',
},
+ ],
+ returnType: `${moduleClientType}`,
+ })
+ .setBodyText(
+ [
+ `const moduleClient = SDK.ModuleClient.createUnchecked(${grpcClientId}, ${moduleRefId});`,
+ `return new ${moduleClientType}(moduleClient);`,
+ ].join('\n')
+ );
+
+ moduleSourceFile
+ .addFunction({
+ docs: [
+ [
+ `Construct a ${moduleClientType} client for interacting with a smart contract module on chain.`,
+ 'This function ensures the smart contract module is deployed on chain.',
+ `@param {${moduleClientType}} ${moduleClientId} - The client of the on-chain smart contract module with referecence '${moduleRef.moduleRef}'.`,
+ '@throws If failing to communicate with the concordium node or if the module reference is not present on chain.',
+ `@returns {${moduleClientType}} A module client ensured to be deployed on chain.`,
+ ].join('\n'),
+ ],
+ isExported: true,
+ name: 'checkOnChain',
+ parameters: [
{
- docs: ['Generic contract client used internally.'],
- scope: tsm.Scope.Private,
- name: genericContractId,
- type: 'SDK.Contract',
+ name: moduleClientId,
+ type: moduleClientType,
},
+ ],
+ returnType: 'Promise',
+ })
+ .setBodyText(
+ `return SDK.ModuleClient.checkOnChain(${moduleClientId}.${internalModuleClientId});`
+ );
+
+ moduleSourceFile
+ .addFunction({
+ docs: [
+ [
+ 'Get the module source of the deployed smart contract module.',
+ `@param {${moduleClientType}} ${moduleClientId} - The client of the on-chain smart contract module with referecence '${moduleRef.moduleRef}'.`,
+ '@throws {SDK.RpcError} If failing to communicate with the concordium node or module not found.',
+ '@returns {SDK.VersionedModuleSource} Module source of the deployed smart contract module.',
+ ].join('\n'),
+ ],
+ isExported: true,
+ name: 'getModuleSource',
+ parameters: [
{
- docs: ['Dry run entrypoints of the smart contract.'],
- scope: tsm.Scope.Public,
- isReadonly: true,
- name: dryRunId,
- type: contractDryRunClassId,
+ name: moduleClientId,
+ type: moduleClientType,
},
],
+ returnType: 'Promise',
+ })
+ .setBodyText(
+ `return SDK.ModuleClient.getModuleSource(${moduleClientId}.${internalModuleClientId});`
+ );
+}
+
+/**
+ * Generate code in the module client specific to each contract in the module.
+ * @param {tsm.SourceFile} moduleSourceFile The sourcefile of the module client.
+ * @param {string} contractName The name of the contract.
+ * @param {string} moduleClientId The identifier for the module client.
+ * @param {string} moduleClientType The identifier for the type of the module client.
+ * @param {string} internalModuleClientId The identifier for the internal module client.
+ * @param {SDK.ModuleReference.Type} moduleRef The reference of the module.
+ * @param {SDK.SchemaContractV3} [contractSchema] The contract schema.
+ */
+function generactionModuleContractCode(
+ moduleSourceFile: tsm.SourceFile,
+ contractName: string,
+ moduleClientId: string,
+ moduleClientType: string,
+ internalModuleClientId: string,
+ moduleRef: SDK.ModuleReference.Type,
+ contractSchema?: SDK.SchemaContractV3
+) {
+ const transactionMetadataId = 'transactionMetadata';
+ const parameterId = 'parameter';
+ const signerId = 'signer';
+
+ const initParameter = createParameterCode(
+ parameterId,
+ contractSchema?.init?.parameter
+ );
+
+ const initParameterTypeId = `${toPascalCase(contractName)}Parameter`;
+
+ const createInitParameterFnId = `create${toPascalCase(
+ contractName
+ )}Parameter`;
+
+ if (initParameter !== undefined) {
+ moduleSourceFile.addTypeAlias({
+ docs: [
+ `Parameter type transaction for instantiating a new '${contractName}' smart contract instance`,
+ ],
+ isExported: true,
+ name: initParameterTypeId,
+ type: initParameter.type,
});
- const dryRunClassDecl = sourceFile.addClass({
+ moduleSourceFile
+ .addFunction({
+ docs: [
+ [
+ `Construct Parameter type transaction for instantiating a new '${contractName}' smart contract instance.`,
+ `@param {${initParameterTypeId}} ${parameterId} The structured parameter to construct from.`,
+ '@returns {SDK.Parameter.Type} The smart contract parameter.',
+ ].join('\n'),
+ ],
+ isExported: true,
+ name: createInitParameterFnId,
+ parameters: [
+ {
+ type: initParameterTypeId,
+ name: parameterId,
+ },
+ ],
+ returnType: 'SDK.Parameter.Type',
+ })
+ .setBodyText(
+ [...initParameter.code, `return ${initParameter.id}`].join('\n')
+ );
+ }
+
+ moduleSourceFile
+ .addFunction({
docs: [
- `Smart contract client for dry running messages to a contract instance of '${contract.contractName}' on chain.`,
+ [
+ `Send transaction for instantiating a new '${contractName}' smart contract instance.`,
+ `@param {${moduleClientType}} ${moduleClientId} - The client of the on-chain smart contract module with referecence '${moduleRef.moduleRef}'.`,
+ `@param {SDK.ContractTransactionMetadata} ${transactionMetadataId} - Metadata related to constructing a transaction for a smart contract module.`,
+ ...(initParameter === undefined
+ ? []
+ : [
+ `@param {${initParameterTypeId}} ${parameterId} - Parameter to provide as part of the transaction for the instantiation of a new smart contract contract.`,
+ ]),
+ `@param {SDK.AccountSigner} ${signerId} - The signer of the update contract transaction.`,
+ '@throws If failing to communicate with the concordium node.',
+ '@returns {SDK.TransactionHash.Type}',
+ ].join('\n'),
],
isExported: true,
- name: contractDryRunClassId,
+ name: `instantiate${toPascalCase(contractName)}`,
+ parameters: [
+ {
+ name: moduleClientId,
+ type: moduleClientType,
+ },
+ {
+ name: transactionMetadataId,
+ type: 'SDK.ContractTransactionMetadata',
+ },
+ ...(initParameter === undefined
+ ? []
+ : [
+ {
+ name: parameterId,
+ type: initParameterTypeId,
+ },
+ ]),
+ {
+ name: signerId,
+ type: 'SDK.AccountSigner',
+ },
+ ],
+ returnType: 'Promise',
+ })
+ .setBodyText(
+ [
+ 'return SDK.ModuleClient.createAndSendInitTransaction(',
+ ` ${moduleClientId}.${internalModuleClientId},`,
+ ` SDK.ContractName.fromStringUnchecked('${contractName}'),`,
+ ` ${transactionMetadataId},`,
+ ...(initParameter === undefined
+ ? []
+ : [` ${createInitParameterFnId}(${parameterId}),`]),
+ ` ${signerId}`,
+ ');',
+ ].join('\n')
+ );
+}
+
+/**
+ * Generate code for a smart contract instance client.
+ * @param {tsm.SourceFile} contractSourceFile The sourcefile of the contract client.
+ * @param {string} contractName The name of the smart contract.
+ * @param {string} contractClientId The identifier to use for the contract client.
+ * @param {string} contractClientType The identifier to use for the type of the contract client.
+ * @param {SDK.ModuleReference.Type} moduleRef The module reference.
+ * @param {SDK.SchemaContractV3} [contractSchema] The contract schema to use in the client.
+ */
+function generateContractBaseCode(
+ contractSourceFile: tsm.SourceFile,
+ contractName: string,
+ contractClientId: string,
+ contractClientType: string,
+ moduleRef: SDK.ModuleReference.Type,
+ contractSchema?: SDK.SchemaContractV3
+) {
+ const moduleRefId = 'moduleReference';
+ const grpcClientId = 'grpcClient';
+ const contractNameId = 'contractName';
+ const genericContractId = 'genericContract';
+ const contractAddressId = 'contractAddress';
+ const blockHashId = 'blockHash';
+
+ contractSourceFile.addImportDeclaration({
+ namespaceImport: 'SDK',
+ moduleSpecifier: '@concordium/web-sdk',
+ });
+
+ contractSourceFile.addVariableStatement({
+ docs: [
+ 'The reference of the smart contract module supported by the provided client.',
+ ],
+ isExported: true,
+ declarationKind: tsm.VariableDeclarationKind.Const,
+ declarations: [
+ {
+ name: moduleRefId,
+ type: 'SDK.ModuleReference.Type',
+ initializer: `/*#__PURE__*/ SDK.ModuleReference.fromHexString('${moduleRef.moduleRef}')`,
+ },
+ ],
+ });
+
+ contractSourceFile.addVariableStatement({
+ docs: ['Name of the smart contract supported by this client.'],
+ isExported: true,
+ declarationKind: tsm.VariableDeclarationKind.Const,
+ declarations: [
+ {
+ name: contractNameId,
+ type: 'SDK.ContractName.Type',
+ initializer: `/*#__PURE__*/ SDK.ContractName.fromStringUnchecked('${contractName}')`,
+ },
+ ],
+ });
+
+ const contractClassDecl = contractSourceFile.addClass({
+ docs: ['Smart contract client for a contract instance on chain.'],
+ name: contractClientType,
+ properties: [
+ {
+ docs: [
+ 'Having a private field prevents similar structured objects to be considered the same type (similar to nominal typing).',
+ ],
+ scope: tsm.Scope.Private,
+ name: '__nominal',
+ initializer: 'true',
+ },
+ {
+ docs: ['The gRPC connection used by this client.'],
+ scope: tsm.Scope.Public,
+ isReadonly: true,
+ name: grpcClientId,
+ type: 'SDK.ConcordiumGRPCClient',
+ },
+ {
+ docs: ['The contract address used by this client.'],
+ scope: tsm.Scope.Public,
+ isReadonly: true,
+ name: contractAddressId,
+ type: 'SDK.ContractAddress.Type',
+ },
+
+ {
+ docs: ['Generic contract client used internally.'],
+ scope: tsm.Scope.Public,
+ isReadonly: true,
+ name: genericContractId,
+ type: 'SDK.Contract',
+ },
+ ],
+ });
+
+ contractClassDecl
+ .addConstructor({
+ parameters: [
+ { name: grpcClientId, type: 'SDK.ConcordiumGRPCClient' },
+ {
+ name: contractAddressId,
+ type: 'SDK.ContractAddress.Type',
+ },
+ { name: genericContractId, type: 'SDK.Contract' },
+ ],
+ })
+ .setBodyText(
+ [grpcClientId, contractAddressId, genericContractId]
+ .map((name) => `this.${name} = ${name};`)
+ .join('\n')
+ );
+
+ contractSourceFile.addTypeAlias({
+ docs: ['Smart contract client for a contract instance on chain.'],
+ name: 'Type',
+ isExported: true,
+ type: contractClientType,
+ });
+
+ contractSourceFile
+ .addFunction({
+ docs: [
+ [
+ `Construct an instance of \`${contractClientType}\` for interacting with a '${contractName}' contract on chain.`,
+ 'Checking the information instance on chain.',
+ `@param {SDK.ConcordiumGRPCClient} ${grpcClientId} - The client used for contract invocations and updates.`,
+ `@param {SDK.ContractAddress.Type} ${contractAddressId} - Address of the contract instance.`,
+ `@param {SDK.BlockHash.Type} [${blockHashId}] - Hash of the block to check the information at. When not provided the last finalized block is used.`,
+ '@throws If failing to communicate with the concordium node or if any of the checks fails.',
+ `@returns {${contractClientType}}`,
+ ].join('\n'),
+ ],
+ isExported: true,
+ isAsync: true,
+ name: 'create',
+ parameters: [
+ {
+ name: grpcClientId,
+ type: 'SDK.ConcordiumGRPCClient',
+ },
+ {
+ name: contractAddressId,
+ type: 'SDK.ContractAddress.Type',
+ },
+ {
+ name: blockHashId,
+ hasQuestionToken: true,
+ type: 'SDK.BlockHash.Type',
+ },
+ ],
+ returnType: `Promise<${contractClientType}>`,
+ })
+ .setBodyText(
+ [
+ `const ${genericContractId} = new SDK.Contract(${grpcClientId}, ${contractAddressId}, ${contractNameId});`,
+ `await ${genericContractId}.checkOnChain({ moduleReference: ${moduleRefId}, blockHash: ${blockHashId} });`,
+ `return new ${contractClientType}(`,
+ ` ${grpcClientId},`,
+ ` ${contractAddressId},`,
+ ` ${genericContractId}`,
+ ');',
+ ].join('\n')
+ );
+
+ contractSourceFile
+ .addFunction({
+ docs: [
+ [
+ `Construct the \`${contractClientType}\` for interacting with a '${contractName}' contract on chain.`,
+ 'Without checking the instance information on chain.',
+ `@param {SDK.ConcordiumGRPCClient} ${grpcClientId} - The client used for contract invocations and updates.`,
+ `@param {SDK.ContractAddress.Type} ${contractAddressId} - Address of the contract instance.`,
+ `@returns {${contractClientType}}`,
+ ].join('\n'),
+ ],
+ isExported: true,
+ name: 'createUnchecked',
+ parameters: [
+ {
+ name: grpcClientId,
+ type: 'SDK.ConcordiumGRPCClient',
+ },
+ {
+ name: contractAddressId,
+ type: 'SDK.ContractAddress.Type',
+ },
+ ],
+ returnType: contractClientType,
+ })
+ .setBodyText(
+ [
+ `const ${genericContractId} = new SDK.Contract(${grpcClientId}, ${contractAddressId}, ${contractNameId});`,
+ `return new ${contractClientType}(`,
+ ` ${grpcClientId},`,
+ ` ${contractAddressId},`,
+ ` ${genericContractId},`,
+ ');',
+ ].join('\n')
+ );
+
+ contractSourceFile
+ .addFunction({
+ docs: [
+ [
+ 'Check if the smart contract instance exists on the blockchain and whether it uses a matching contract name and module reference.',
+ `@param {${contractClientType}} ${contractClientId} The client for a '${contractName}' smart contract instance on chain.`,
+ `@param {SDK.BlockHash.Type} [${blockHashId}] A optional block hash to use for checking information on chain, if not provided the last finalized will be used.`,
+ '@throws {SDK.RpcError} If failing to communicate with the concordium node or if any of the checks fails.',
+ ].join('\n'),
+ ],
+ isExported: true,
+ name: 'checkOnChain',
+ parameters: [
+ {
+ name: contractClientId,
+ type: contractClientType,
+ },
+ {
+ name: blockHashId,
+ hasQuestionToken: true,
+ type: 'SDK.BlockHash.Type',
+ },
+ ],
+ returnType: 'Promise',
+ })
+ .setBodyText(
+ `return ${contractClientId}.${genericContractId}.checkOnChain({moduleReference: ${moduleRefId}, blockHash: ${blockHashId} });`
+ );
+
+ const eventParameterId = 'event';
+ const eventParameterTypeId = 'Event';
+ const eventParser = parseEventCode(eventParameterId, contractSchema?.event);
+ if (eventParser !== undefined) {
+ contractSourceFile.addTypeAlias({
+ docs: [`Contract event type for the '${contractName}' contract.`],
+ isExported: true,
+ name: eventParameterTypeId,
+ type: eventParser.type,
});
- classDecl
- .addConstructor({
- docs: ['Contruct a client for a contract instance on chain'],
+ contractSourceFile
+ .addFunction({
+ docs: [
+ [
+ `Parse the contract events logged by the '${contractName}' contract.`,
+ `@param {SDK.ContractEvent.Type} ${eventParameterId} The unparsed contract event.`,
+ `@returns {${eventParameterTypeId}} The structured contract event.`,
+ ].join('\n'),
+ ],
+ isExported: true,
+ name: 'parseEvent',
parameters: [
{
- name: grpcClientId,
- type: 'SDK.ConcordiumGRPCClient',
- scope: tsm.Scope.Public,
+ name: eventParameterId,
+ type: 'SDK.ContractEvent.Type',
},
+ ],
+ returnType: eventParameterTypeId,
+ })
+ .setBodyText(
+ [...eventParser.code, `return ${eventParser.id};`].join('\n')
+ );
+ }
+}
+
+/**
+ * Generate contract client code for each entrypoint.
+ * @param {tsm.SourceFile} contractSourceFile The sourcefile of the contract.
+ * @param {string} contractName The name of the contract.
+ * @param {string} contractClientId The identifier to use for the contract client.
+ * @param {string} contractClientType The identifier to use for the type of the contract client.
+ * @param {string} entrypointName The name of the entrypoint.
+ * @param {SDK.SchemaFunctionV2} [entrypointSchema] The schema to use for the entrypoint.
+ */
+function generateContractEntrypointCode(
+ contractSourceFile: tsm.SourceFile,
+ contractName: string,
+ contractClientId: string,
+ contractClientType: string,
+ entrypointName: string,
+ entrypointSchema?: SDK.SchemaFunctionV2
+) {
+ const invokeMetadataId = 'invokeMetadata';
+ const parameterId = 'parameter';
+ const transactionMetadataId = 'transactionMetadata';
+ const signerId = 'signer';
+ const genericContractId = 'genericContract';
+ const blockHashId = 'blockHash';
+
+ const receiveParameter = createParameterCode(
+ parameterId,
+ entrypointSchema?.parameter
+ );
+
+ const receiveParameterTypeId = `${toPascalCase(entrypointName)}Parameter`;
+
+ const createReceiveParameterFnId = `create${toPascalCase(
+ entrypointName
+ )}Parameter`;
+
+ if (receiveParameter !== undefined) {
+ contractSourceFile.addTypeAlias({
+ docs: [
+ `Parameter type for update transaction for '${entrypointName}' entrypoint of the '${contractName}' contract.`,
+ ],
+ isExported: true,
+ name: receiveParameterTypeId,
+ type: receiveParameter.type,
+ });
+
+ contractSourceFile
+ .addFunction({
+ docs: [
+ [
+ `Construct Parameter for update transactions for '${entrypointName}' entrypoint of the '${contractName}' contract.`,
+ `@param {${receiveParameterTypeId}} ${parameterId} The structured parameter to construct from.`,
+ '@returns {SDK.Parameter.Type} The smart contract parameter.',
+ ].join('\n'),
+ ],
+ isExported: true,
+ name: createReceiveParameterFnId,
+ parameters: [
{
- name: contractAddressId,
- type: 'SDK.ContractAddress',
- isReadonly: true,
- scope: tsm.Scope.Public,
+ type: receiveParameterTypeId,
+ name: parameterId,
},
],
+ returnType: 'SDK.Parameter.Type',
})
.setBodyText(
- `this.${genericContractId} = new SDK.Contract(${grpcClientId}, ${contractAddressId}, '${contract.contractName}');
-this.${dryRunId} = new ${contractDryRunClassId}(this.${genericContractId});`
+ [
+ ...receiveParameter.code,
+ `return ${receiveParameter.id};`,
+ ].join('\n')
);
+ }
+
+ contractSourceFile
+ .addFunction({
+ docs: [
+ [
+ `Send an update-contract transaction to the '${entrypointName}' entrypoint of the '${contractName}' contract.`,
+ `@param {${contractClientType}} ${contractClientId} The client for a '${contractName}' smart contract instance on chain.`,
+ `@param {SDK.ContractTransactionMetadata} ${transactionMetadataId} - Metadata related to constructing a transaction for a smart contract.`,
+ ...(receiveParameter === undefined
+ ? []
+ : [
+ `@param {${receiveParameterTypeId}} ${parameterId} - Parameter to provide the smart contract entrypoint as part of the transaction.`,
+ ]),
+ `@param {SDK.AccountSigner} ${signerId} - The signer of the update contract transaction.`,
+ '@throws If the entrypoint is not successfully invoked.',
+ '@returns {SDK.TransactionHash.Type} Hash of the transaction.',
+ ].join('\n'),
+ ],
+ isExported: true,
+ name: `send${toPascalCase(entrypointName)}`,
+ parameters: [
+ {
+ name: contractClientId,
+ type: contractClientType,
+ },
+ {
+ name: transactionMetadataId,
+ type: 'SDK.ContractTransactionMetadata',
+ },
+ ...(receiveParameter === undefined
+ ? []
+ : [
+ {
+ name: parameterId,
+ type: receiveParameterTypeId,
+ },
+ ]),
+ {
+ name: signerId,
+ type: 'SDK.AccountSigner',
+ },
+ ],
+ returnType: 'Promise',
+ })
+ .setBodyText(
+ [
+ `return ${contractClientId}.${genericContractId}.createAndSendUpdateTransaction(`,
+ ` SDK.EntrypointName.fromStringUnchecked('${entrypointName}'),`,
+ ' SDK.Parameter.toBuffer,',
+ ` ${transactionMetadataId},`,
+ ...(receiveParameter === undefined
+ ? []
+ : [` ${createReceiveParameterFnId}(${parameterId}),`]),
+ ` ${signerId}`,
+ ');',
+ ].join('\n')
+ );
- dryRunClassDecl.addConstructor({
- docs: ['Contruct a client for a contract instance on chain'],
+ contractSourceFile
+ .addFunction({
+ docs: [
+ [
+ `Dry-run an update-contract transaction to the '${entrypointName}' entrypoint of the '${contractName}' contract.`,
+ `@param {${contractClientType}} ${contractClientId} The client for a '${contractName}' smart contract instance on chain.`,
+ `@param {SDK.ContractAddress.Type | SDK.AccountAddress.Type} ${invokeMetadataId} - The address of the account or contract which is invoking this transaction.`,
+ ...(receiveParameter === undefined
+ ? []
+ : [
+ `@param {${receiveParameterTypeId}} ${parameterId} - Parameter to provide the smart contract entrypoint as part of the transaction.`,
+ ]),
+ `@param {SDK.BlockHash.Type} [${blockHashId}] - Optional block hash allowing for dry-running the transaction at the end of a specific block.`,
+ '@throws {SDK.RpcError} If failing to communicate with the concordium node or if any of the checks fails.',
+ '@returns {SDK.InvokeContractResult} The result of invoking the smart contract instance.',
+ ].join('\n'),
+ ],
+ isExported: true,
+ name: `dryRun${toPascalCase(entrypointName)}`,
parameters: [
{
- name: genericContractId,
- type: 'SDK.Contract',
- scope: tsm.Scope.Private,
+ name: contractClientId,
+ type: contractClientType,
+ },
+ ...(receiveParameter === undefined
+ ? []
+ : [
+ {
+ name: parameterId,
+ type: receiveParameterTypeId,
+ },
+ ]),
+ {
+ name: invokeMetadataId,
+ type: 'SDK.ContractInvokeMetadata',
+ initializer: '{}',
+ },
+ {
+ name: blockHashId,
+ hasQuestionToken: true,
+ type: 'SDK.BlockHash.Type',
},
],
+ returnType: 'Promise',
+ })
+ .setBodyText(
+ [
+ `return ${contractClientId}.${genericContractId}.dryRun.invokeMethod(`,
+ ` SDK.EntrypointName.fromStringUnchecked('${entrypointName}'),`,
+ ` ${invokeMetadataId},`,
+ ' SDK.Parameter.toBuffer,',
+ ...(receiveParameter === undefined
+ ? []
+ : [` ${createReceiveParameterFnId}(${parameterId}),`]),
+ ` ${blockHashId}`,
+ ');',
+ ].join('\n')
+ );
+
+ const invokeResultId = 'invokeResult';
+ const returnValueTokens = parseReturnValueCode(
+ `${invokeResultId}.returnValue`,
+ entrypointSchema?.returnValue
+ );
+ if (returnValueTokens !== undefined) {
+ const returnValueTypeId = `ReturnValue${toPascalCase(entrypointName)}`;
+
+ contractSourceFile.addTypeAlias({
+ docs: [
+ `Return value for dry-running update transaction for '${entrypointName}' entrypoint of the '${contractName}' contract.`,
+ ],
+ isExported: true,
+ name: returnValueTypeId,
+ type: returnValueTokens.type,
});
- for (const entrypointName of contract.entrypointNames) {
- const transactionMetadataId = 'transactionMetadata';
- const parameterId = 'parameter';
- const signerId = 'signer';
- classDecl
- .addMethod({
- docs: [
- `Send an update-contract transaction to the '${entrypointName}' entrypoint of the '${contract.contractName}' contract.
-
-@param {SDK.ContractTransactionMetadata} ${transactionMetadataId} - Hex encoded parameter for entrypoint
-@param {SDK.HexString} ${parameterId} - Hex encoded parameter for entrypoint
-@param {SDK.AccountSigner} ${signerId} - The signer of the update contract transaction.
-
-@throws If the entrypoint is not successfully invoked.
-
-@returns {SDK.HexString} Transaction hash`,
- ],
- scope: tsm.Scope.Public,
- name: toCamelCase(entrypointName),
- parameters: [
- {
- name: transactionMetadataId,
- type: 'SDK.ContractTransactionMetadata',
- },
- {
- name: parameterId,
- type: 'SDK.HexString',
- },
- {
- name: signerId,
- type: 'SDK.AccountSigner',
- },
- ],
- returnType: 'Promise',
- })
- .setBodyText(
- `return this.${genericContractId}.createAndSendUpdateTransaction(
- '${entrypointName}',
- SDK.encodeHexString,
- ${transactionMetadataId},
- ${parameterId},
- ${signerId}
-);`
- );
- const blockHashId = 'blockHash';
- dryRunClassDecl
- .addMethod({
- docs: [
- `Dry run an update-contract transaction to the '${entrypointName}' entrypoint of the '${contract.contractName}' contract.
-
-@param {SDK.HexString} ${parameterId} - Hex encoded parameter for entrypoint
-@param {SDK.HexString} [${blockHashId}] - Block hash of the block to invoke entrypoint at
-
-@throws If the entrypoint is not successfully invoked.
-
-returns {SDK.HexString} Hex encoded response`,
- ],
- scope: tsm.Scope.Public,
- name: toCamelCase(entrypointName),
- parameters: [
- {
- name: parameterId,
- type: 'SDK.HexString',
- },
- {
- name: blockHashId,
- type: 'SDK.HexString',
- hasQuestionToken: true,
- },
- ],
- returnType: 'Promise',
- })
- .setBodyText(
- `return this.${genericContractId}.invokeView(
- '${entrypointName}',
- SDK.encodeHexString,
- (hex: SDK.HexString) => hex,
- ${parameterId},
- ${blockHashId}
-);`
- );
- }
+ contractSourceFile
+ .addFunction({
+ docs: [
+ [
+ `Get and parse the return value from dry-running update transaction for '${entrypointName}' entrypoint of the '${contractName}' contract.`,
+ 'Returns undefined if the result is not successful.',
+ '@param {SDK.InvokeContractResult} invokeResult The result from dry-running the transaction.',
+ `@returns {${returnValueTypeId} | undefined} The structured return value or undefined if result was not a success.`,
+ ].join('\n'),
+ ],
+ isExported: true,
+ name: `parseReturnValue${toPascalCase(entrypointName)}`,
+ parameters: [
+ {
+ name: invokeResultId,
+ type: 'SDK.InvokeContractResult',
+ },
+ ],
+ returnType: `${returnValueTypeId} | undefined`,
+ })
+ .setBodyText(
+ [
+ `if (${invokeResultId}.tag !== 'success') {`,
+ ' return undefined;',
+ '}',
+ `if (${invokeResultId}.returnValue === undefined) {`,
+ " throw new Error('Unexpected missing \\'returnValue\\' in result of invocation. Client expected a V1 smart contract.');",
+ '}',
+ ...returnValueTokens.code,
+ `return ${returnValueTokens.id};`,
+ ].join('\n')
+ );
+ }
+
+ const errorMessageTokens = parseReturnValueCode(
+ `${invokeResultId}.returnValue`,
+ entrypointSchema?.error
+ );
+ if (errorMessageTokens !== undefined) {
+ const errorMessageTypeId = `ErrorMessage${toPascalCase(
+ entrypointName
+ )}`;
+
+ contractSourceFile.addTypeAlias({
+ docs: [
+ `Error message for dry-running update transaction for '${entrypointName}' entrypoint of the '${contractName}' contract.`,
+ ],
+ isExported: true,
+ name: errorMessageTypeId,
+ type: errorMessageTokens.type,
+ });
+
+ contractSourceFile
+ .addFunction({
+ docs: [
+ [
+ `Get and parse the error message from dry-running update transaction for '${entrypointName}' entrypoint of the '${contractName}' contract.`,
+ 'Returns undefined if the result is not a failure.',
+ '@param {SDK.InvokeContractResult} invokeResult The result from dry-running the transaction.',
+ `@returns {${errorMessageTypeId} | undefined} The structured error message or undefined if result was not a failure or failed for other reason than contract rejectedReceive.`,
+ ].join('\n'),
+ ],
+ isExported: true,
+ name: `parseErrorMessage${toPascalCase(entrypointName)}`,
+ parameters: [
+ {
+ name: invokeResultId,
+ type: 'SDK.InvokeContractResult',
+ },
+ ],
+ returnType: `${errorMessageTypeId} | undefined`,
+ })
+ .setBodyText(
+ [
+ `if (${invokeResultId}.tag !== 'failure' || ${invokeResultId}.reason.tag !== 'RejectedReceive') {`,
+ ' return undefined;',
+ '}',
+ `if (${invokeResultId}.returnValue === undefined) {`,
+ " throw new Error('Unexpected missing \\'returnValue\\' in result of invocation. Client expected a V1 smart contract.');",
+ '}',
+ ...errorMessageTokens.code,
+ `return ${errorMessageTokens.id}`,
+ ].join('\n')
+ );
}
}
@@ -275,17 +1111,6 @@ function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.substring(1);
}
-/**
- * Convert a string in snake_case or kebab-case into camelCase.
- * This is used to transform entrypoint names in the smart contract to follow formatting javascript convention.
- */
-function toCamelCase(str: string): string {
- return str
- .split(/[-_]/g)
- .map((word, index) => (index === 0 ? word : capitalize(word)))
- .join('');
-}
-
/**
* Convert a string in snake_case or kebab-case into PascalCase.
* This is used to transform contract names in the smart contract to follow formatting javascript convention.
@@ -293,3 +1118,948 @@ function toCamelCase(str: string): string {
function toPascalCase(str: string): string {
return str.split(/[-_]/g).map(capitalize).join('');
}
+
+/** Type information from the schema. */
+type SchemaNativeType = {
+ /** The type to provide for a given schema type. */
+ nativeType: string;
+ /** The type in the Schema JSON format. */
+ jsonType: string;
+ /**
+ * Provided the identifier for the input (of the above type), this generates
+ * tokens for converting it into Schema JSON format.
+ */
+ nativeToJson: (nativeId: string) => { code: string[]; id: string };
+ /**
+ * Provided the identifier for the input (Schema JSON format), this generates
+ * tokens for converting it into a native type (the above type).
+ */
+ jsonToNative: (jsonId: string) => { code: string[]; id: string };
+};
+
+/**
+ * From a schema type construct a 'native' type, a type of the expected JSON format and converter functions
+ * between this native type and the JSON format expected when serializing using a schema.
+ *
+ * @param {SDK.SchemaType} schemaType The schema type
+ * @returns {SchemaNativeType} native type, JSON type and converters.
+ */
+function schemaAsNativeType(schemaType: SDK.SchemaType): SchemaNativeType {
+ switch (schemaType.type) {
+ case 'Unit':
+ return {
+ nativeType: '"Unit"',
+ jsonType: '[]',
+ jsonToNative() {
+ return { code: [], id: '[]' };
+ },
+ nativeToJson() {
+ return { code: [], id: '"Unit"' };
+ },
+ };
+ case 'Bool':
+ return {
+ nativeType: 'boolean',
+ jsonType: 'boolean',
+ nativeToJson(nativeId) {
+ return { code: [], id: nativeId };
+ },
+ jsonToNative(jsonId) {
+ return { code: [], id: jsonId };
+ },
+ };
+ case 'U8':
+ case 'U16':
+ case 'U32':
+ case 'I8':
+ case 'I16':
+ case 'I32':
+ return {
+ nativeType: 'number',
+ jsonType: 'number',
+ nativeToJson(id) {
+ return { code: [], id };
+ },
+ jsonToNative(id) {
+ return { code: [], id };
+ },
+ };
+ case 'U64':
+ case 'I64':
+ return {
+ nativeType: 'number | bigint',
+ jsonType: 'bigint',
+ nativeToJson(id) {
+ const resultId = idGenerator('number');
+ return {
+ code: [`const ${resultId} = BigInt(${id});`],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ return { code: [], id };
+ },
+ };
+ case 'U128':
+ case 'I128':
+ return {
+ nativeType: 'number | bigint',
+ jsonType: 'string',
+ nativeToJson(id) {
+ const resultId = idGenerator('number');
+ return {
+ code: [`const ${resultId} = BigInt(${id}).toString();`],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ return { code: [], id: `BigInt(${id})` };
+ },
+ };
+ case 'Amount':
+ return {
+ nativeType: 'SDK.CcdAmount.Type',
+ jsonType: 'SDK.CcdAmount.SchemaValue',
+ nativeToJson(id) {
+ const resultId = idGenerator('amount');
+ return {
+ code: [
+ `const ${resultId} = SDK.CcdAmount.toSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('amount');
+ return {
+ code: [
+ `const ${resultId} = SDK.CcdAmount.fromSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ };
+ case 'AccountAddress':
+ return {
+ nativeType: 'SDK.AccountAddress.Type',
+ jsonType: 'SDK.AccountAddress.SchemaValue',
+ nativeToJson(id) {
+ const resultId = idGenerator('accountAddress');
+ return {
+ code: [
+ `const ${resultId} = SDK.AccountAddress.toSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('accountAddress');
+ return {
+ code: [
+ `const ${resultId} = SDK.AccountAddress.fromSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ };
+ case 'ContractAddress':
+ return {
+ nativeType: 'SDK.ContractAddress.Type',
+ jsonType: 'SDK.ContractAddress.SchemaValue',
+ nativeToJson(id) {
+ const resultId = idGenerator('contractAddress');
+ return {
+ code: [
+ `const ${resultId} = SDK.ContractAddress.toSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('contractAddress');
+ return {
+ code: [
+ `const ${resultId} = SDK.ContractAddress.fromSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ };
+ case 'Timestamp':
+ return {
+ nativeType: 'SDK.Timestamp.Type',
+ jsonType: 'SDK.Timestamp.SchemaValue',
+ nativeToJson(id) {
+ const resultId = idGenerator('timestamp');
+ return {
+ code: [
+ `const ${resultId} = SDK.Timestamp.toSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('timestamp');
+ return {
+ code: [
+ `const ${resultId} = SDK.Timestamp.fromSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ };
+ case 'Duration':
+ return {
+ nativeType: 'SDK.Duration.Type',
+ jsonType: 'SDK.Duration.SchemaValue',
+ nativeToJson(id) {
+ const resultId = idGenerator('duration');
+ return {
+ code: [
+ `const ${resultId} = SDK.Duration.toSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('duration');
+ return {
+ code: [
+ `const ${resultId} = SDK.Duration.fromSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ };
+ case 'Pair':
+ const first = schemaAsNativeType(schemaType.first);
+ const second = schemaAsNativeType(schemaType.second);
+
+ return {
+ nativeType: `[${first.nativeType}, ${second.nativeType}]`,
+ jsonType: `[${first.jsonType}, ${second.jsonType}]`,
+ nativeToJson(id) {
+ const resultId = idGenerator('pair');
+ const firstTokens = first.nativeToJson(`${id}[0]`);
+ const secondTokens = second.nativeToJson(`${id}[1]`);
+ return {
+ code: [
+ ...firstTokens.code,
+ ...secondTokens.code,
+ `const ${resultId}: ${this.jsonType} = [${firstTokens.id}, ${secondTokens.id}];`,
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('pair');
+ const firstTokens = first.jsonToNative(`${id}[0]`);
+ const secondTokens = second.jsonToNative(`${id}[1]`);
+ return {
+ code: [
+ ...firstTokens.code,
+ ...secondTokens.code,
+ `const ${resultId}: ${this.nativeType} = [${firstTokens.id}, ${secondTokens.id}];`,
+ ],
+ id: resultId,
+ };
+ },
+ };
+ case 'List': {
+ const item = schemaAsNativeType(schemaType.item);
+ return {
+ nativeType: `Array<${item.nativeType}>`,
+ jsonType: `Array<${item.jsonType}>`,
+ nativeToJson(id) {
+ const resultId = idGenerator('list');
+ const itemId = idGenerator('item');
+ const tokens = item.nativeToJson(itemId);
+ // Check if any mapping is needed.
+ if (tokens.id === itemId && tokens.code.length === 0) {
+ return {
+ code: [],
+ id,
+ };
+ }
+ return {
+ code: [
+ `const ${resultId} = ${id}.map((${itemId}) => {`,
+ ...tokens.code,
+ `return ${tokens.id};`,
+ '});',
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('list');
+ const itemId = idGenerator('item');
+ const tokens = item.jsonToNative(itemId);
+ // Check if any mapping is needed.
+ if (tokens.id === itemId && tokens.code.length === 0) {
+ return {
+ code: [],
+ id,
+ };
+ }
+ return {
+ code: [
+ `const ${resultId} = ${id}.map((${itemId}) => {`,
+ ...tokens.code,
+ `return ${tokens.id};`,
+ '});',
+ ],
+ id: resultId,
+ };
+ },
+ };
+ }
+ case 'Set': {
+ const item = schemaAsNativeType(schemaType.item);
+ return {
+ nativeType: `Set<${item.nativeType}>`,
+ jsonType: `Array<${item.jsonType}>`,
+ nativeToJson(id) {
+ const resultId = idGenerator('set');
+ const valueId = idGenerator('value');
+ const valuesId = idGenerator('values');
+ const valueTokens = item.nativeToJson(valueId);
+ return {
+ code: [
+ `const ${valuesId} = [...${id}.values()]..map((${valueId}) => {`,
+ ...valueTokens.code,
+ `return ${valueTokens.id};`,
+ '});',
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('set');
+ const valueId = idGenerator('value');
+ const valuesId = idGenerator('values');
+ const valueTokens = item.jsonToNative(valueId);
+ return {
+ code: [
+ `const ${valuesId} = ${id}.map((${valueId}) => {`,
+ ...valueTokens.code,
+ `return ${valueTokens.id}; `,
+ '});',
+ `const ${resultId} = new Set(${valuesId});`,
+ ],
+ id: resultId,
+ };
+ },
+ };
+ }
+ case 'Map': {
+ const key = schemaAsNativeType(schemaType.key);
+ const value = schemaAsNativeType(schemaType.value);
+ return {
+ nativeType: `Map<${key.nativeType}, ${value.nativeType}>`,
+ jsonType: `[${key.jsonType}, ${value.jsonType}][]`,
+ nativeToJson(id) {
+ const resultId = idGenerator('map');
+ const keyId = idGenerator('key');
+ const valueId = idGenerator('value');
+ const keyTokens = key.nativeToJson(keyId);
+ const valueTokens = value.nativeToJson(valueId);
+
+ return {
+ code: [
+ `const ${resultId}: ${this.jsonType} = [...${id}.entries()].map(([${keyId}, ${valueId}]) => {`,
+ ...keyTokens.code,
+ ...valueTokens.code,
+ ` return [${keyTokens.id}, ${valueTokens.id}];`,
+ '});',
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('map');
+ const entriesId = idGenerator('entries');
+ const keyId = idGenerator('key');
+ const valueId = idGenerator('value');
+ const keyTokens = key.jsonToNative(keyId);
+ const valueTokens = value.jsonToNative(valueId);
+ return {
+ code: [
+ `const ${entriesId} = ${id}.map(([${keyId}, ${valueId}]) => {`,
+ ...keyTokens.code,
+ ...valueTokens.code,
+ `return [${keyTokens.id}, ${valueTokens.id}];`,
+ '});',
+ `const ${resultId}: ${this.nativeType} = Map.fromEntries(${entriesId});`,
+ ],
+ id: resultId,
+ };
+ },
+ };
+ }
+ case 'Array': {
+ const item = schemaAsNativeType(schemaType.item);
+ return {
+ nativeType: `[${new Array(schemaType.size)
+ .fill(item.nativeType)
+ .join(', ')}]`,
+ jsonType: `[${new Array(schemaType.size)
+ .fill(item.jsonType)
+ .join(', ')}]`,
+ nativeToJson(id) {
+ const resultId = idGenerator('array');
+ const itemId = idGenerator('item');
+ const tokens = item.nativeToJson(itemId);
+ // Check if any mapping is needed.
+ if (tokens.id === itemId && tokens.code.length === 0) {
+ return {
+ code: [],
+ id,
+ };
+ }
+
+ return {
+ code: [
+ `const ${resultId} = ${id}.map((${itemId}) => {`,
+ ...tokens.code,
+ ` return ${tokens.id};`,
+ '});',
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('array');
+ const itemId = idGenerator('item');
+ const tokens = item.jsonToNative(itemId);
+ // Check if any mapping is needed.
+ if (tokens.id === itemId && tokens.code.length === 0) {
+ return {
+ code: [],
+ id,
+ };
+ }
+ return {
+ code: [
+ `const ${resultId} = ${id}.map((${itemId}: any) => {`,
+ ...tokens.code,
+ ` return ${tokens.id};`,
+ '});',
+ ],
+ id: resultId,
+ };
+ },
+ };
+ }
+ case 'Struct':
+ return fieldToTypeAndMapper(schemaType.fields);
+
+ case 'Enum':
+ case 'TaggedEnum': {
+ const variants =
+ schemaType.type === 'Enum'
+ ? schemaType.variants
+ : [...schemaType.variants.values()];
+
+ const variantFieldSchemas = variants.map((variant) => ({
+ name: variant.name,
+ ...fieldToTypeAndMapper(variant.fields),
+ }));
+
+ const variantTypes = variantFieldSchemas.map((variantSchema) =>
+ variantSchema.nativeType === '"no-fields"'
+ ? `{ type: '${variantSchema.name}'}`
+ : `{ type: '${variantSchema.name}', content: ${variantSchema.nativeType} }`
+ );
+
+ const variantJsonTypes = variantFieldSchemas.map(
+ (variantSchema) =>
+ `{'${variantSchema.name}' : ${variantSchema.jsonType} }`
+ );
+
+ return {
+ nativeType: variantTypes.join(' | '),
+ jsonType: variantJsonTypes.join(' | '),
+ nativeToJson(id) {
+ const resultId = idGenerator('match');
+
+ const variantCases = variantFieldSchemas.flatMap(
+ (variantSchema) => {
+ const tokens = variantSchema.nativeToJson(
+ `${id}.content`
+ );
+ return [
+ ` case '${variantSchema.name}':`,
+ ...tokens.code,
+ ` ${resultId} = { ${defineProp(
+ variantSchema.name,
+ tokens.id
+ )} };`,
+ ' break;',
+ ];
+ }
+ );
+ return {
+ code: [
+ `let ${resultId}: ${this.jsonType};`,
+ `switch (${id}.type) {`,
+ ...variantCases,
+ '}',
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('match');
+ //const variantKeyId = idGenerator('variantKey');
+
+ const variantIfStatements = variantFieldSchemas.map(
+ (variantFieldSchema) => {
+ const variantId = idGenerator('variant');
+ const variantTokens =
+ variantFieldSchema.jsonToNative(variantId);
+ return [
+ `if ('${variantFieldSchema.name}' in ${id}) {`,
+ ...(variantTokens.id === '"no-fields"'
+ ? [
+ ` ${resultId} = {`,
+ ` type: '${variantFieldSchema.name}',`,
+ ' };',
+ ]
+ : [
+ ` const ${variantId} = ${accessProp(
+ id,
+ variantFieldSchema.name
+ )};`,
+ ...variantTokens.code,
+ ` ${resultId} = {`,
+ ` type: '${variantFieldSchema.name}',`,
+ ` content: ${variantTokens.id},`,
+ ' };',
+ ]),
+ '}',
+ ].join('\n');
+ }
+ );
+ return {
+ code: [
+ `let ${resultId}: ${this.nativeType};`,
+ variantIfStatements.join(' else '),
+ ' else {',
+ ' throw new Error("Unexpected enum variant");',
+ '}',
+ ],
+ id: resultId,
+ };
+ },
+ };
+ }
+ case 'String':
+ return {
+ nativeType: 'string',
+ jsonType: 'string',
+ nativeToJson(id) {
+ return { code: [], id };
+ },
+ jsonToNative(id) {
+ return {
+ code: [],
+ id,
+ };
+ },
+ };
+ case 'ContractName':
+ return {
+ nativeType: 'SDK.ContractName.Type',
+ jsonType: 'SDK.ContractName.SchemaType',
+ nativeToJson(id) {
+ const resultId = idGenerator('contractName');
+ return {
+ code: [
+ `const ${resultId} = SDK.ContractName.toSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('contractName');
+ return {
+ code: [
+ `const ${resultId} = SDK.ContractName.fromSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ };
+ case 'ReceiveName':
+ return {
+ nativeType: 'SDK.ReceiveName.Type',
+ jsonType: 'SDK.ReceiveName.SchemaType',
+ nativeToJson(id) {
+ const resultId = idGenerator('receiveName');
+ return {
+ code: [
+ `const ${resultId} = SDK.ReceiveName.toSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('receiveName');
+ return {
+ code: [
+ `const ${resultId} = SDK.ReceiveName.fromSchemaValue(${id});`,
+ ],
+ id: resultId,
+ };
+ },
+ };
+ case 'ULeb128':
+ case 'ILeb128':
+ return {
+ nativeType: 'number | bigint',
+ jsonType: 'bigint',
+ nativeToJson(id) {
+ const resultId = idGenerator('number');
+ return {
+ code: [`const ${resultId} = BigInt(${id}).toString();`],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ return {
+ code: [],
+ id: `BigInt(${id})`,
+ };
+ },
+ };
+ case 'ByteList':
+ case 'ByteArray':
+ return {
+ nativeType: 'SDK.HexString',
+ jsonType: 'string',
+ nativeToJson(id) {
+ return { code: [], id };
+ },
+ jsonToNative(id) {
+ return {
+ code: [],
+ id,
+ };
+ },
+ };
+ }
+}
+
+function fieldToTypeAndMapper(fields: SDK.SchemaFields): SchemaNativeType {
+ switch (fields.type) {
+ case 'Named': {
+ const schemas = fields.fields.map((named) => ({
+ name: named.name,
+ ...schemaAsNativeType(named.field),
+ }));
+
+ const objectFieldTypes = schemas.map((s) =>
+ defineProp(s.name, s.nativeType)
+ );
+ const objectFieldJsonTypes = schemas.map((s) =>
+ defineProp(s.name, s.jsonType)
+ );
+
+ return {
+ nativeType: `{\n${objectFieldTypes.join('\n')}\n}`,
+ jsonType: `{\n${objectFieldJsonTypes.join('\n')}\n}`,
+ nativeToJson(id) {
+ const resultId = idGenerator('named');
+ const fields = schemas.map((s) => {
+ const fieldId = idGenerator('field');
+ const field = s.nativeToJson(fieldId);
+ return {
+ name: s.name,
+ constructTokens: [
+ `const ${fieldId} = ${accessProp(id, s.name)};`,
+ ...field.code,
+ ],
+ id: field.id,
+ };
+ });
+ const constructTokens = fields.flatMap(
+ (tokens) => tokens.constructTokens
+ );
+
+ return {
+ code: [
+ ...constructTokens,
+ `const ${resultId} = {`,
+ ...fields.map((tokens) =>
+ defineProp(tokens.name, tokens.id)
+ ),
+ '};',
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const fields = schemas.map((s) => {
+ const fieldId = idGenerator('field');
+ const field = s.jsonToNative(fieldId);
+ return {
+ name: s.name,
+ constructTokens: [
+ `const ${fieldId} = ${accessProp(id, s.name)};`,
+ ...field.code,
+ ],
+ id: field.id,
+ };
+ });
+ const constructTokens = fields.flatMap(
+ (tokens) => tokens.constructTokens
+ );
+ const resultId = idGenerator('named');
+ return {
+ code: [
+ ...constructTokens,
+ `const ${resultId} = {`,
+ ...fields.map((tokens) =>
+ defineProp(tokens.name, tokens.id)
+ ),
+ '};',
+ ],
+ id: resultId,
+ };
+ },
+ };
+ }
+ case 'Unnamed': {
+ const schemas = fields.fields.flatMap((f) => {
+ const schema = schemaAsNativeType(f);
+ return schema === undefined ? [] : [schema];
+ });
+ if (schemas.length === 1) {
+ const schema = schemas[0];
+ return {
+ nativeType: schema.nativeType,
+ jsonType: `[${schema.jsonType}]`,
+ nativeToJson(id) {
+ const tokens = schema.nativeToJson(id);
+ return { code: tokens.code, id: `[${tokens.id}]` };
+ },
+ jsonToNative(id) {
+ return schema.jsonToNative(`${id}[0]`);
+ },
+ };
+ } else {
+ return {
+ nativeType: `[${schemas
+ .map((s) => s.nativeType)
+ .join(', ')}]`,
+ jsonType: `[${schemas.map((s) => s.jsonType).join(', ')}]`,
+ nativeToJson(id) {
+ const resultId = idGenerator('unnamed');
+ const mapped = schemas.map((schema, index) =>
+ schema.nativeToJson(`${id}[${index}]`)
+ );
+ const constructFields = mapped.flatMap(
+ (tokens) => tokens.code
+ );
+ const fieldIds = mapped.map((s) => s.id);
+ return {
+ code: [
+ ...constructFields,
+ `const ${resultId}: ${
+ this.jsonType
+ } = [${fieldIds.join(', ')}];`,
+ ],
+ id: resultId,
+ };
+ },
+ jsonToNative(id) {
+ const resultId = idGenerator('unnamed');
+ const mapped = schemas.map((schema, index) =>
+ schema.jsonToNative(`${id}[${index}]`)
+ );
+ const constructFields = mapped.flatMap(
+ (tokens) => tokens.code
+ );
+ const fieldIds = mapped.map((s) => s.id);
+ return {
+ code: [
+ ...constructFields,
+ `const ${resultId} = [${fieldIds.join(', ')}];`,
+ ],
+ id: resultId,
+ };
+ },
+ };
+ }
+ }
+ case 'None':
+ return {
+ nativeType: '"no-fields"',
+ jsonType: '[]',
+ nativeToJson() {
+ return { code: [], id: '[]' };
+ },
+ jsonToNative() {
+ return { code: [], id: '"no-fields"' };
+ },
+ };
+ }
+}
+
+/**
+ * Information related to conversion between JSON and native type.
+ */
+type TypeConversionCode = {
+ /** The native type. */
+ type: string;
+ /** Code to convert JSON either to or from native type. */
+ code: string[];
+ /** Identifier for the result of the code. */
+ id: string;
+};
+
+/**
+ * Generate tokens for creating the parameter from input.
+ * @param {string} parameterId Identifier of the input.
+ * @param {SDK.SchemaType} [schemaType] The schema type to use for the parameter.
+ * @returns Undefined if no parameter is expected.
+ */
+function createParameterCode(
+ parameterId: string,
+ schemaType?: SDK.SchemaType
+): TypeConversionCode | undefined {
+ // No schema type is present so fallback to plain parameter.
+ if (schemaType === undefined) {
+ return {
+ type: 'SDK.Parameter.Type',
+ code: [],
+ id: parameterId,
+ };
+ }
+
+ if (schemaType.type === 'Unit') {
+ // No parameter is needed according to the schema.
+ return undefined;
+ }
+ const typeAndMapper = schemaAsNativeType(schemaType);
+ const buffer = SDK.serializeSchemaType(schemaType);
+ const base64Schema = Buffer.from(buffer).toString('base64');
+
+ const mappedParameter = typeAndMapper.nativeToJson(parameterId);
+ const resultId = 'out';
+ return {
+ type: typeAndMapper.nativeType,
+ code: [
+ ...mappedParameter.code,
+ `const ${resultId} = SDK.Parameter.fromBase64SchemaType('${base64Schema}', ${mappedParameter.id});`,
+ ],
+ id: resultId,
+ };
+}
+
+/**
+ * Generate tokens for parsing a contract event.
+ * @param {string} eventId Identifier of the event to parse.
+ * @param {SDK.SchemaType} [schemaType] The schema to take into account when parsing.
+ * @returns Undefined if no code should be produced.
+ */
+function parseEventCode(
+ eventId: string,
+ schemaType?: SDK.SchemaType
+): TypeConversionCode | undefined {
+ // No schema type is present so generate any code.
+ if (schemaType === undefined) {
+ return undefined;
+ }
+ const typeAndMapper = schemaAsNativeType(schemaType);
+ const base64Schema = Buffer.from(
+ SDK.serializeSchemaType(schemaType)
+ ).toString('base64');
+
+ const schemaJsonId = 'schemaJson';
+ const tokens = typeAndMapper.jsonToNative(schemaJsonId);
+ return {
+ type: typeAndMapper.nativeType,
+ code: [
+ `const ${schemaJsonId} = <${typeAndMapper.jsonType}>SDK.ContractEvent.parseWithSchemaTypeBase64(${eventId}, '${base64Schema}');`,
+ ...tokens.code,
+ ],
+ id: tokens.id,
+ };
+}
+
+/**
+ * Generate tokens for parsing a return type.
+ * @param {string} returnTypeId Identifier of the return type to parse.
+ * @param {SDK.SchemaType} [schemaType] The schema to take into account when parsing return type.
+ * @returns Undefined if no code should be produced.
+ */
+function parseReturnValueCode(
+ returnTypeId: string,
+ schemaType?: SDK.SchemaType
+): TypeConversionCode | undefined {
+ // No schema type is present so don't generate any code.
+ if (schemaType === undefined) {
+ return undefined;
+ }
+ const typeAndMapper = schemaAsNativeType(schemaType);
+ const base64Schema = Buffer.from(
+ SDK.serializeSchemaType(schemaType)
+ ).toString('base64');
+
+ const schemaJsonId = 'schemaJson';
+ const tokens = typeAndMapper.jsonToNative(schemaJsonId);
+ return {
+ type: typeAndMapper.nativeType,
+
+ code: [
+ `const ${schemaJsonId} = <${typeAndMapper.jsonType}>SDK.ReturnValue.parseWithSchemaTypeBase64(${returnTypeId}, '${base64Schema}');`,
+ ...tokens.code,
+ ],
+ id: tokens.id,
+ };
+}
+
+/**
+ * Stateful function which suffixes a provided string with a number, which increments everytime this is called.
+ * Used to ensure identifiers are unique.
+ * @param {string} name Name of the identifier.
+ * @returns {string} The name of the identifier suffixed with a number.
+ */
+const idGenerator = (() => {
+ let counter = 0;
+ return (name: string) => `${name}${counter++}`;
+})();
+
+/**
+ * Create tokens for accessing a property on an object.
+ * @param {string} objectId Identifier for the object.
+ * @param {string} propId Identifier for the property.
+ * @returns {string} Tokens for accessing the prop.
+ */
+function accessProp(objectId: string, propId: string): string {
+ return identifierRegex.test(propId)
+ ? `${objectId}.${propId}`
+ : `${objectId}['${propId}']`;
+}
+
+/**
+ * Create tokens for defining a property in an object
+ * @param {string} propId Identifier for the property.
+ * @param {string} valueId Identifier for the value.
+ * @returns {string} Tokens for defining a property initialized to the value.
+ */
+function defineProp(propId: string, valueId: string): string {
+ return identifierRegex.test(propId)
+ ? `${propId}: ${valueId},`
+ : `'${propId}': ${valueId},`;
+}
+
+/**
+ * Regular expression matching the format of valid identifiers in javascript.
+ *
+ * > Note: this does not check for collision with keywords, which is not a problem
+ * when accessing props or defining fields in an object.
+ */
+const identifierRegex = /^[$A-Z_][0-9A-Z_$]*$/i;
diff --git a/packages/ccd-js-gen/test/generate-test-bench.test.ts b/packages/ccd-js-gen/test/generate-test-bench.test.ts
new file mode 100644
index 000000000..faa4fc3b1
--- /dev/null
+++ b/packages/ccd-js-gen/test/generate-test-bench.test.ts
@@ -0,0 +1,93 @@
+/*
+ * This file contains tests for generating clients for the smart contract module 'test-bench'
+ * located at https://github.com/Concordium/concordium-misc-tools/tree/main/wallet-connect-test-bench/smart-contract
+ *
+ * The tests will run the client generator, typecheck the generated files and ensure the files
+ * exposes relevant functions.
+ *
+ * These tests depends on the smart contract module being a file with path:
+ *
+ * test/resources/test-bench.wasm.v1
+ *
+ * Which can be built from the above linked project using `cargo-concordium`:
+ *
+ * ```
+ * cargo concordium build --schema-embed --out ./path/to/test/resources/test-bench.wasm.v1
+ * ```
+ */
+import * as Gen from '../src/lib.js';
+import { assertTypeChecks } from './testHelpers.js';
+
+const outDir = __dirname + '/lib';
+const outModuleFile = `${outDir}/test-bench`;
+const outContractFile = `${outDir}/test-bench_smart_contract_test_bench`;
+
+beforeAll(() => {
+ return Gen.generateContractClientsFromFile(
+ __dirname + '/resources/test-bench.wasm.v1',
+ outDir,
+ { output: 'Everything' }
+ );
+}, 60_000);
+
+describe('Generated module client file', () => {
+ test('Type checks', () => {
+ assertTypeChecks([`${outModuleFile}.ts`]);
+ });
+
+ test('Exports basic functions based on wasm', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const module = require(`${outModuleFile}.js`);
+
+ expect(module.create).toBeDefined();
+ expect(module.createUnchecked).toBeDefined();
+ expect(module.checkOnChain).toBeDefined();
+ expect(module.getModuleSource).toBeDefined();
+ });
+
+ test('Exports module specific functions based on wasm', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const module = require(`${outModuleFile}.js`);
+ expect(module.instantiateSmartContractTestBench).toBeDefined();
+ });
+
+ test('Exports functions based on schema', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const module = require(`${outModuleFile}.js`);
+ expect(module.createSmartContractTestBenchParameter).toBeDefined();
+ });
+});
+
+describe('Generated contract client file', () => {
+ test('Type checks', () => {
+ assertTypeChecks([`${outContractFile}.ts`]);
+ });
+
+ test('Exports basic functions based on wasm module', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const module = require(`${outContractFile}.js`);
+
+ expect(module.create).toBeDefined();
+ expect(module.createUnchecked).toBeDefined();
+ expect(module.checkOnChain).toBeDefined();
+ });
+
+ test('Exports contract specific functions based on wasm module', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const module = require(`${outContractFile}.js`);
+
+ expect(module.sendSetU8).toBeDefined();
+ expect(module.dryRunSetU8).toBeDefined();
+ expect(module.sendSetU8Payable).toBeDefined();
+ expect(module.dryRunSetU8Payable).toBeDefined();
+ });
+
+ test('Exports functions based on schema', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const module = require(`${outContractFile}.js`);
+ expect(module.parseEvent).not.toBeDefined();
+ expect(module.createSetU8Parameter).toBeDefined();
+ expect(module.createSetU8PayableParameter).toBeDefined();
+ expect(module.parseErrorMessageSetU8).toBeDefined();
+ });
+});
diff --git a/packages/ccd-js-gen/test/generate-wCCD.test.ts b/packages/ccd-js-gen/test/generate-wCCD.test.ts
new file mode 100644
index 000000000..6c8f27baa
--- /dev/null
+++ b/packages/ccd-js-gen/test/generate-wCCD.test.ts
@@ -0,0 +1,98 @@
+/*
+ * This file contains tests for generating clients for the smart contract module of wCCD
+ * (module reference "cc285180b45d7695db75c29dee004d2e81a1383880c9b122399bea809196c98f").
+ *
+ * The tests will run the client generator, typecheck the generated files and ensure the files
+ * exposes relevant functions.
+ *
+ * These tests depends on the smart contract module being a file with path:
+ *
+ * test/resources/wCCD.wasm.v1
+ *
+ * Which can be generated using the SDK:
+ *
+ * ```
+ * import * as SDK from "@concordium/web-sdk";
+ * import * as fs from "node:fs/promises";
+ * const client = ...// Grpc client for Testnet.
+ * const source = await client.getModuleSource("cc285180b45d7695db75c29dee004d2e81a1383880c9b122399bea809196c98f");
+ * await fs.writeFile("test/resources/wCCD.wasm.v1", versionedModuleSourceToBuffer(source));
+ * ```
+ */
+import * as Gen from '../src/lib.js';
+import { assertTypeChecks } from './testHelpers.js';
+
+const moduleFileName = 'wCCD';
+const moduleFilePath = `${__dirname}/resources/${moduleFileName}.wasm.v1`;
+const outDir = `${__dirname}/lib`;
+const outModuleFile = `${outDir}/${moduleFileName}`;
+const outContractFile = `${outDir}/${moduleFileName}_cis2_wCCD`;
+
+beforeAll(() => {
+ return Gen.generateContractClientsFromFile(moduleFilePath, outDir, {
+ output: 'Everything',
+ });
+}, 60_000);
+
+describe('Generated module client file', () => {
+ test('Type checks', () => {
+ assertTypeChecks([`${outModuleFile}.ts`]);
+ });
+
+ test('Exports basic functions based on wasm', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const module = require(`${outModuleFile}.js`);
+
+ expect(module.create).toBeDefined();
+ expect(module.createUnchecked).toBeDefined();
+ expect(module.checkOnChain).toBeDefined();
+ expect(module.getModuleSource).toBeDefined();
+ });
+
+ test('Exports module specific functions based on wasm', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const module = require(`${outModuleFile}.js`);
+ expect(module.instantiateCis2WCCD).toBeDefined();
+ });
+
+ test('Exports functions based on schema', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const module = require(`${outModuleFile}.js`);
+ expect(module.createCis2WCCDParameter).toBeDefined();
+ });
+});
+
+describe('Generated contract client file', () => {
+ test('Type checks', () => {
+ assertTypeChecks([`${outContractFile}.ts`]);
+ });
+
+ test('Exports basic functions based on wasm module', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const module = require(`${outContractFile}.js`);
+
+ expect(module.create).toBeDefined();
+ expect(module.createUnchecked).toBeDefined();
+ expect(module.checkOnChain).toBeDefined();
+ });
+
+ test('Exports contract specific functions based on wasm module', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const module = require(`${outContractFile}.js`);
+
+ expect(module.sendWrap).toBeDefined();
+ expect(module.dryRunWrap).toBeDefined();
+ expect(module.sendTransfer).toBeDefined();
+ expect(module.dryRunTransfer).toBeDefined();
+ });
+
+ test('Exports functions based on schema', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ const module = require(`${outContractFile}.js`);
+ expect(module.parseEvent).toBeDefined();
+ expect(module.createUnwrapParameter).toBeDefined();
+ expect(module.parseErrorMessageUnwrap).toBeDefined();
+ expect(module.createTransferParameter).toBeDefined();
+ expect(module.parseErrorMessageTransfer).toBeDefined();
+ });
+});
diff --git a/packages/ccd-js-gen/test/resources/test-bench.wasm.v1 b/packages/ccd-js-gen/test/resources/test-bench.wasm.v1
new file mode 100644
index 000000000..4e6fcbca8
Binary files /dev/null and b/packages/ccd-js-gen/test/resources/test-bench.wasm.v1 differ
diff --git a/packages/ccd-js-gen/test/resources/wCCD.wasm.v1 b/packages/ccd-js-gen/test/resources/wCCD.wasm.v1
new file mode 100644
index 000000000..a0097861d
Binary files /dev/null and b/packages/ccd-js-gen/test/resources/wCCD.wasm.v1 differ
diff --git a/packages/ccd-js-gen/test/testHelpers.ts b/packages/ccd-js-gen/test/testHelpers.ts
new file mode 100644
index 000000000..7711214ce
--- /dev/null
+++ b/packages/ccd-js-gen/test/testHelpers.ts
@@ -0,0 +1,42 @@
+import * as ts from 'typescript';
+
+/**
+ * Use typescript compiler to typecheck the provided files, fails the test otherwise.
+ * @param {string[]} files Typescript files to type check.
+ */
+export function assertTypeChecks(files: string[]) {
+ const program = ts.createProgram(files, {
+ noEmit: true,
+ target: ts.ScriptTarget.ES2022,
+ moduleResolution: ts.ModuleResolutionKind.NodeNext,
+ module: ts.ModuleKind.NodeNext,
+ });
+ const emitResult = program.emit();
+
+ const allDiagnostics = ts
+ .getPreEmitDiagnostics(program)
+ .concat(emitResult.diagnostics);
+
+ const errors = allDiagnostics.map((diagnostic) => {
+ if (diagnostic.file) {
+ const { line, character } = ts.getLineAndCharacterOfPosition(
+ diagnostic.file,
+ diagnostic.start!
+ );
+ const message = ts.flattenDiagnosticMessageText(
+ diagnostic.messageText,
+ '\n'
+ );
+ return `${diagnostic.file.fileName} (${line + 1},${
+ character + 1
+ }): ${message}`;
+ } else {
+ return ts.flattenDiagnosticMessageText(
+ diagnostic.messageText,
+ '\n'
+ );
+ }
+ });
+ expect(errors).toEqual([]);
+ expect(emitResult.emitSkipped).toBeFalsy();
+}
diff --git a/packages/ccd-js-gen/tsconfig.build.json b/packages/ccd-js-gen/tsconfig.build.json
new file mode 100644
index 000000000..edc2723b8
--- /dev/null
+++ b/packages/ccd-js-gen/tsconfig.build.json
@@ -0,0 +1,4 @@
+{
+ "extends": "./tsconfig.json",
+ "include": ["src/**/*", "package.json"]
+}
diff --git a/packages/ccd-js-gen/tsconfig.json b/packages/ccd-js-gen/tsconfig.json
index 93480aa50..4f493d24a 100644
--- a/packages/ccd-js-gen/tsconfig.json
+++ b/packages/ccd-js-gen/tsconfig.json
@@ -1,10 +1,11 @@
{
"extends": "../../tsconfig-base.json",
- "include": ["src/**/*", "package.json"],
+ "include": ["src/**/*", "test/**/*", "package.json", "jest.config.ts"],
"compilerOptions": {
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
"outDir": "./lib",
"lib": ["ES2020", "dom"], // "dom" is only added to get the typings for the global variable `WebAssembly`.
- "target": "ES2020",
"resolveJsonModule": true
}
}
diff --git a/packages/common/README.md b/packages/common/README.md
deleted file mode 100644
index f6f699409..000000000
--- a/packages/common/README.md
+++ /dev/null
@@ -1,7 +0,0 @@
-# Concordium JS SDKs Common Functionality
-
-This package is the shared library for the NodeJS and Web SDK's.
-
-Please see the
-[documentation](https://developer.concordium.software/concordium-node-sdk-js/index.html)
-for more information
diff --git a/packages/common/jest.config.js b/packages/common/jest.config.js
deleted file mode 100644
index 40810b105..000000000
--- a/packages/common/jest.config.js
+++ /dev/null
@@ -1,11 +0,0 @@
-module.exports = {
- preset: 'ts-jest',
- testEnvironment: 'node',
- moduleFileExtensions: ['js', 'ts', 'json'],
- moduleDirectories: ['node_modules'],
- globals: {
- 'ts-jest': {
- tsconfig: 'tsconfig.json',
- },
- },
-};
diff --git a/packages/common/package.json b/packages/common/package.json
deleted file mode 100644
index 8a820a38b..000000000
--- a/packages/common/package.json
+++ /dev/null
@@ -1,69 +0,0 @@
-{
- "name": "@concordium/common-sdk",
- "version": "9.5.1",
- "license": "Apache-2.0",
- "engines": {
- "node": ">=14.16.0"
- },
- "repository": {
- "type": "git",
- "url": "https://github.com/Concordium/concordium-node-sdk-js",
- "directory": "packages/common"
- },
- "main": "lib/index.js",
- "types": "lib/index.d.ts",
- "files": [
- "/grpc/**/*",
- "/lib/**/*"
- ],
- "devDependencies": {
- "@protobuf-ts/plugin": "2.8.1",
- "@types/big.js": "^6.2.0",
- "@types/bs58check": "^2.1.0",
- "@types/jest": "^26.0.23",
- "@types/json-bigint": "^1.0.1",
- "@types/uuid": "^8.3.4",
- "@typescript-eslint/eslint-plugin": "^4.28.1",
- "@typescript-eslint/parser": "^4.28.1",
- "babel-jest": "^27.0.6",
- "eslint": "^7.29.0",
- "eslint-config-prettier": "^8.3.0",
- "eslint-plugin-prettier": "^3.4.0",
- "grpc-tools": "^1.11.2",
- "grpc_tools_node_protoc_ts": "5.3.0",
- "husky": "^4.2.5",
- "jest": "^27.0.6",
- "lint-staged": "^12.0.2",
- "prettier": "^2.3.2",
- "ts-jest": "^27.0.3",
- "typescript": "^4.3.5"
- },
- "prettier": {
- "singleQuote": true,
- "tabWidth": 4
- },
- "scripts": {
- "generate-ts-v2": "yarn run grpc_tools_node_protoc --plugin=protoc-gen-ts=../../node_modules/@protobuf-ts/plugin/bin/protoc-gen-ts --ts_opt 'optimize_code_size,output_legacy_commonjs,output_javascript' --ts_out=grpc -I ../../deps/concordium-base/concordium-grpc-api ../../deps/concordium-base/concordium-grpc-api/v2/concordium/*.proto",
- "generate": "([ -e \"../../deps/concordium-base/concordium-grpc-api\" ] && yarn generate-ts-v2) || echo 'Please checkout submodules before building'",
- "lint": "eslint . --cache --ext .ts,.tsx --max-warnings 0",
- "lint-fix": "yarn --silent lint --fix; exit 0",
- "test": "jest",
- "build": "rm -rf grpc; mkdir -p grpc; yarn generate && tsc",
- "build-dev": "tsc"
- },
- "dependencies": {
- "@concordium/rust-bindings": "1.2.0",
- "@grpc/grpc-js": "^1.3.4",
- "@noble/ed25519": "^1.7.1",
- "@protobuf-ts/runtime-rpc": "^2.8.2",
- "@scure/bip39": "^1.1.0",
- "big.js": "^6.2.0",
- "bs58check": "^2.1.2",
- "buffer": "^6.0.3",
- "cross-fetch": "3.1.5",
- "hash.js": "^1.1.7",
- "iso-3166-1": "^2.1.1",
- "json-bigint": "^1.0.0",
- "uuid": "^8.3.2"
- }
-}
diff --git a/packages/common/src/JsonRpcClient.ts b/packages/common/src/JsonRpcClient.ts
deleted file mode 100644
index 692f43d2f..000000000
--- a/packages/common/src/JsonRpcClient.ts
+++ /dev/null
@@ -1,406 +0,0 @@
-import { Buffer } from 'buffer/';
-import {
- AccountInfo,
- AccountTransaction,
- AccountTransactionSignature,
- buildInvoker,
- ConcordiumBftStatus,
- ConsensusStatus,
- ConsensusStatusV0,
- ConsensusStatusV1,
- ContractAddress,
- ContractContext,
- CryptographicParameters,
- InstanceInfo,
- InvokeContractResultV1,
- NextAccountNonce,
- SignedCredentialDeploymentDetails,
- TransactionStatus,
- TransactionSummary,
- Versioned,
-} from './types';
-import { AccountAddress } from './types/accountAddress';
-import Provider, { JsonRpcResponse } from './providers/provider';
-import {
- serializeAccountTransactionForSubmission,
- serializeSignedCredentialDeploymentDetailsForSubmission,
-} from './serialization';
-import { CcdAmount } from './types/ccdAmount';
-import { ModuleReference } from './types/moduleReference';
-import {
- buildJsonResponseReviver,
- intToStringTransformer,
- isValidHash,
-} from './util';
-import { CredentialRegistrationId } from './types/CredentialRegistrationId';
-
-function transformJsonResponse(
- jsonString: string,
- reviver?: (this: unknown, key: string, value: unknown) => unknown,
- transformer?: (json: string) => string
-): JsonRpcResponse {
- if (transformer) {
- const transformedJson = transformer(jsonString);
- return JSON.parse(transformedJson, reviver);
- }
-
- return JSON.parse(jsonString, reviver);
-}
-
-/**
- * @deprecated This has been deprecated in favor of the {@link ConcordiumGRPCClient} that uses version 2 of the concordium gRPC API
- */
-export class JsonRpcClient {
- provider: Provider;
-
- constructor(provider: Provider) {
- this.provider = provider;
- }
-
- async getNextAccountNonce(
- accountAddress: AccountAddress
- ): Promise {
- const response = await this.provider.request('getNextAccountNonce', {
- address: accountAddress.address,
- });
-
- const bigIntPropertyKeys: (keyof NextAccountNonce)[] = ['nonce'];
-
- const res = transformJsonResponse(
- response,
- buildJsonResponseReviver([], bigIntPropertyKeys),
- intToStringTransformer(bigIntPropertyKeys)
- );
- return res.result;
- }
-
- async getTransactionStatus(
- transactionHash: string
- ): Promise {
- const response = await this.provider.request('getTransactionStatus', {
- transactionHash: transactionHash,
- });
-
- // TODO avoid code duplication with nodejs client
- const bigIntPropertyKeys: (keyof TransactionSummary)[] = [
- 'cost',
- 'energyCost',
- 'index',
- ];
-
- const res = transformJsonResponse(
- response,
- buildJsonResponseReviver([], bigIntPropertyKeys),
- intToStringTransformer(bigIntPropertyKeys)
- );
- return res.result;
- }
-
- /**
- * @param serializedTransaction the transaction serialized as a base64-encoded string.
- */
- private async sendRawTransaction(
- serializedTransaction: string
- ): Promise {
- const res = await this.provider.request('sendTransaction', {
- transaction: serializedTransaction,
- });
- return JSON.parse(res).result || false;
- }
-
- async sendAccountTransaction(
- accountTransaction: AccountTransaction,
- signatures: AccountTransactionSignature
- ): Promise {
- const serializedAccountTransaction: Buffer = Buffer.from(
- serializeAccountTransactionForSubmission(
- accountTransaction,
- signatures
- )
- );
- return this.sendRawTransaction(
- serializedAccountTransaction.toString('base64')
- );
- }
-
- async sendCredentialDeployment(
- credentialDetails: SignedCredentialDeploymentDetails
- ): Promise {
- const serializedDetails =
- serializeSignedCredentialDeploymentDetailsForSubmission(
- credentialDetails
- );
- return this.sendRawTransaction(serializedDetails.toString('base64'));
- }
-
- async getConsensusStatus(): Promise {
- const response = await this.provider.request('getConsensusStatus');
- type CS = ConsensusStatusV0 & ConsensusStatusV1;
-
- // TODO Avoid code duplication with nodejs client
- const datePropertyKeys: (keyof CS | keyof ConcordiumBftStatus)[] = [
- 'blockLastReceivedTime',
- 'blockLastArrivedTime',
- 'genesisTime',
- 'currentEraGenesisTime',
- 'lastFinalizedTime',
-
- // v1
- 'triggerBlockTime',
- ];
- const bigIntPropertyKeys: (keyof CS | keyof ConcordiumBftStatus)[] = [
- 'epochDuration',
- 'slotDuration',
- 'bestBlockHeight',
- 'lastFinalizedBlockHeight',
- 'finalizationCount',
- 'blocksVerifiedCount',
- 'blocksReceivedCount',
- 'protocolVersion',
-
- // v1
- 'currentTimeoutDuration',
- 'currentRound',
- 'currentEpoch',
- ];
-
- const res = transformJsonResponse(
- response,
- buildJsonResponseReviver(datePropertyKeys, bigIntPropertyKeys),
- intToStringTransformer(bigIntPropertyKeys)
- );
-
- if (!res.result) {
- throw new Error(
- 'Nothing was returned when trying to get the consensus status.'
- );
- }
-
- return res.result;
- }
-
- /**
- * Retrieve information about a given smart contract instance.
- * @param blockHash the block hash to get the smart contact instances at
- * @param address the address of the smart contract
- * @returns A JSON object with information about the contract instance
- */
- async getInstanceInfo(
- address: ContractAddress,
- blockHash?: string
- ): Promise {
- if (!blockHash) {
- const consensusStatus = await this.getConsensusStatus();
- blockHash = consensusStatus.lastFinalizedBlock;
- } else if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
-
- const response = await this.provider.request('getInstanceInfo', {
- index: address.index,
- subindex: address.subindex,
- blockHash,
- });
-
- const result = JSON.parse(response).result;
-
- if (!result) {
- return undefined;
- }
-
- // TODO: Avoid code duplication with nodejs client
- const common = {
- amount: new CcdAmount(BigInt(result.amount)),
- sourceModule: new ModuleReference(result.sourceModule),
- owner: new AccountAddress(result.owner),
- methods: result.methods,
- name: result.name,
- };
-
- switch (result.version) {
- case 1:
- return {
- version: 1,
- ...common,
- };
- case undefined:
- case 0:
- return {
- version: 0,
- ...common,
- model: Buffer.from(result.model, 'hex'),
- };
- default:
- throw new Error(
- 'InstanceInfo had unsupported version: ' +
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (result as any).version
- );
- }
- }
-
- /**
- * Retrieves the account info for the given account. If the provided block
- * hash is in a block prior to the finalization of the account, then the account
- * information will not be available.
- * A credential registration id can also be provided, instead of an address. In this case
- * the node will return the account info of the account, which the corresponding credential
- * is (or was) deployed to.
- * @param accountAddress base58 account address (or a credential registration id) to get the account info for
- * @param blockHash the block hash to get the account info at
- * @returns the account info for the provided account address, undefined is the account does not exist
- */
- async getAccountInfo(
- accountAddress: string | AccountAddress | CredentialRegistrationId,
- blockHash?: string
- ): Promise {
- if (!blockHash) {
- const consensusStatus = await this.getConsensusStatus();
- blockHash = consensusStatus.lastFinalizedBlock;
- } else if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
-
- let address: string;
- if (typeof accountAddress === 'string') {
- address = accountAddress;
- } else if ('address' in accountAddress) {
- address = accountAddress.address;
- } else if ('credId' in accountAddress) {
- address = accountAddress.credId;
- } else {
- throw new Error('Invalid accountAddress input');
- }
-
- const response = await this.provider.request('getAccountInfo', {
- blockHash,
- address,
- });
-
- const datePropertyKeys = ['timestamp', 'effectiveTime'];
- const bigIntPropertyKeys = [
- 'accountAmount',
- 'accountNonce',
- 'accountIndex',
- 'startIndex',
- 'total',
- 'amount',
- 'stakedAmount',
- 'bakerId',
- 'newStake',
- 'epoch',
- ];
- const res = transformJsonResponse(
- response,
- buildJsonResponseReviver(datePropertyKeys, bigIntPropertyKeys),
- intToStringTransformer(bigIntPropertyKeys)
- );
-
- return res.result;
- }
-
- /**
- * Retrieves the global cryptographic parameters on the blockchain at
- * the provided block.
- * @param blockHash the block to get the cryptographic parameters at
- * @returns the global cryptographic parameters at the given block, or undefined it the block does not exist.
- */
- async getCryptographicParameters(
- blockHash?: string
- ): Promise | undefined> {
- if (!blockHash) {
- const consensusStatus = await this.getConsensusStatus();
- blockHash = consensusStatus.lastFinalizedBlock;
- } else if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
-
- const response = await this.provider.request(
- 'getCryptographicParameters',
- {
- blockHash,
- }
- );
-
- const res =
- transformJsonResponse>(response);
-
- return res.result;
- }
-
- /**
- * Retrieves the source of the given module at
- * the provided block.
- * @param moduleReference the module's reference, which is the hex encoded hash of the source.
- * @param blockHash the block to get the cryptographic parameters at
- * @returns the source of the module as raw bytes.
- */
- async getModuleSource(
- moduleReference: ModuleReference,
- blockHash?: string
- ): Promise {
- if (!blockHash) {
- const consensusStatus = await this.getConsensusStatus();
- blockHash = consensusStatus.lastFinalizedBlock;
- } else if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
-
- const response = await this.provider.request('getModuleSource', {
- moduleReference: moduleReference.moduleRef,
- blockHash,
- });
-
- return Buffer.from(JSON.parse(response).result, 'base64');
- }
-
- /**
- * Invokes a smart contract.
- * @param context the collection of details used to invoke the contract. Must include the address of the contract and the method invoked.
- * @param blockHash the block hash at which the contract should be invoked at. The contract is invoked in the state at the end of this block.
- * @returns If the node was able to invoke, then a object describing the outcome is returned.
- * The outcome is determined by the `tag` field, which is either `success` or `failure`.
- * The `usedEnergy` field will always be present, and is the amount of NRG was used during the execution.
- * If the tag is `success`, then an `events` field is present, and it contains the events that would have been generated.
- * If invoking a V1 contract and it produces a return value, it will be present in the `returnValue` field.
- * If the tag is `failure`, then a `reason` field is present, and it contains the reason the update would have been rejected.
- * If either the block does not exist, or then node fails to parse of any of the inputs, then undefined is returned.
- */
- async invokeContract(
- contractContext: ContractContext,
- blockHash?: string
- ): Promise {
- if (!blockHash) {
- const consensusStatus = await this.getConsensusStatus();
- blockHash = consensusStatus.lastFinalizedBlock;
- } else if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
-
- const invoker = buildInvoker(contractContext.invoker);
-
- const context = {
- ...contractContext,
- invoker,
- amount:
- contractContext.amount && contractContext.amount.microCcdAmount,
- parameter:
- contractContext.parameter &&
- contractContext.parameter.toString('hex'),
- };
-
- const response = await this.provider.request('invokeContract', {
- blockHash,
- context,
- });
-
- const bigIntPropertyKeys = ['usedEnergy', 'index', 'subindex'];
- const res = transformJsonResponse(
- response,
- buildJsonResponseReviver([], bigIntPropertyKeys),
- intToStringTransformer(bigIntPropertyKeys)
- );
-
- return res.result;
- }
-}
diff --git a/packages/common/src/accountHelpers.ts b/packages/common/src/accountHelpers.ts
deleted file mode 100644
index 6ca4f3461..000000000
--- a/packages/common/src/accountHelpers.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import * as wasm from '@concordium/rust-bindings';
-import { AccountAddress } from './types/accountAddress';
-import {
- ReduceStakePendingChange,
- RemovalPendingChange,
- AccountInfo,
- AccountInfoBaker,
- AccountInfoDelegator,
- GenerateBakerKeysOutput,
-} from './types';
-
-/** Whether {@link AccountInfo} parameter given is of type {@link AccountInfoDelegator}, i.e. the account is a delegator */
-export const isDelegatorAccount = (
- ai: AccountInfo
-): ai is AccountInfoDelegator =>
- (ai as AccountInfoDelegator).accountDelegation !== undefined;
-
-/** Whether {@link AccountInfo} parameter given is of type {@link AccountInfoBaker}, i.e. the account is a baker. */
-export const isBakerAccount = (ai: AccountInfo): ai is AccountInfoBaker =>
- (ai as AccountInfoBaker).accountBaker !== undefined;
-
-/** Whether the pending change given is of type {@link ReduceStakePendingChange} */
-export const isReduceStakePendingChange = (
- spc: ReduceStakePendingChange | RemovalPendingChange
-): spc is ReduceStakePendingChange =>
- (spc as ReduceStakePendingChange).newStake !== undefined;
-
-/** Whether the pending change given is of type {@link RemovalPendingChange} */
-export const isRemovalPendingChange = (
- spc: ReduceStakePendingChange | RemovalPendingChange
-): spc is RemovalPendingChange => !isReduceStakePendingChange(spc);
-
-/**
- * Generates random baker keys for the specified account, that can be used with the configureBaker transaction
- * @param account the address of the account that the keys should be added to.
- * @returns an object containing the public baker keys, their associated proofs and their associated private keys.
- */
-export function generateBakerKeys(
- account: AccountAddress
-): GenerateBakerKeysOutput {
- const rawKeys = wasm.generateBakerKeys(account.address);
- try {
- return JSON.parse(rawKeys);
- } catch (e) {
- throw new Error(rawKeys);
- }
-}
diff --git a/packages/common/src/alias.ts b/packages/common/src/alias.ts
deleted file mode 100644
index d504d90d0..000000000
--- a/packages/common/src/alias.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import * as bs58check from 'bs58check';
-import { Buffer } from 'buffer/';
-import { AccountAddress } from './types/accountAddress';
-
-const addressByteLength = 32;
-const aliasBytesLength = 3;
-const commonBytesLength = addressByteLength - aliasBytesLength;
-const maxCount = 16777215; // 2^(8 * 3) - 1
-
-/**
- * Given two accountAddresses, return whether they are aliases.
- * @param address an AccountAddress
- * @param alias another AccountAddress
- * @returns boolean that indicates whether address and alias are aliases
- */
-export function isAlias(
- address: AccountAddress,
- alias: AccountAddress
-): boolean {
- return (
- 0 ===
- address.decodedAddress.compare(
- alias.decodedAddress,
- 0,
- commonBytesLength,
- 0,
- commonBytesLength
- )
- );
-}
-
-/**
- * Given an AccountAddress and a counter, returns an alias for the address.
- * @param address the account address for which the function should get an alias for
- * @param counter number s.t. 0 <= counter < 2^24, decides which alias is returned.
- * If a counter outside this scope is given, then the function will throw an exception
- * @returns an AccountAddress, which is an alias to the given address
- */
-export function getAlias(
- address: AccountAddress,
- counter: number
-): AccountAddress {
- if (counter < 0 || counter > maxCount) {
- throw new Error(
- `An invalid counter value was given: ${counter}. The value has to satisfy that 0 <= counter < 2^24`
- );
- }
- const commonBytes = address.decodedAddress.slice(0, commonBytesLength);
- const aliasBytes = Buffer.alloc(aliasBytesLength);
- aliasBytes.writeUIntBE(counter, 0, aliasBytesLength);
- const prefixedWithVersion = Buffer.concat([
- Buffer.of(1),
- commonBytes,
- aliasBytes,
- ]);
- return new AccountAddress(bs58check.encode(prefixedWithVersion));
-}
diff --git a/packages/common/src/blockSummaryHelpers.ts b/packages/common/src/blockSummaryHelpers.ts
deleted file mode 100644
index ebebe3e3c..000000000
--- a/packages/common/src/blockSummaryHelpers.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import {
- BlockSummary,
- BlockSummaryV0,
- BlockSummaryV1,
- BlockSummaryV2,
- UpdateQueues,
- UpdateQueuesV0,
- UpdateQueuesV1,
- UpdateQueuesV2,
- Updates,
- UpdatesV0,
- UpdatesV1,
- UpdatesV2,
-} from './types';
-
-/** Whether {@link UpdateQueues} parameter given is of type {@link UpdateQueuesV0} */
-export const isUpdateQueuesV0 = (uq: UpdateQueues): uq is UpdateQueuesV0 =>
- (uq as UpdateQueuesV0).bakerStakeThreshold !== undefined;
-
-/** Whether {@link UpdateQueues} parameter given is of type {@link UpdateQueuesV1} */
-export const isUpdateQueuesV1 = (uq: UpdateQueues): uq is UpdateQueuesV1 =>
- (uq as UpdateQueuesV1).timeParameters !== undefined;
-
-/** Whether {@link UpdateQueues} parameter given is of type {@link UpdateQueuesV2} */
-export const isUpdateQueuesV2 = (uq: UpdateQueues): uq is UpdateQueuesV2 =>
- (uq as UpdateQueuesV2).consensus2TimingParameters !== undefined;
-
-export const isUpdatesV0 = (u: Updates): u is UpdatesV0 =>
- isUpdateQueuesV0(u.updateQueues);
-
-export const isUpdatesV1 = (u: Updates): u is UpdatesV1 =>
- isUpdateQueuesV1(u.updateQueues);
-
-export const isUpdatesV2 = (u: Updates): u is UpdatesV2 =>
- isUpdateQueuesV2(u.updateQueues);
-
-export const isBlockSummaryV0 = (bs: BlockSummary): bs is BlockSummaryV0 =>
- bs.protocolVersion === undefined || bs.protocolVersion <= 3n;
-
-export const isBlockSummaryV1 = (bs: BlockSummary): bs is BlockSummaryV1 =>
- bs.protocolVersion !== undefined &&
- bs.protocolVersion > 3n &&
- bs.protocolVersion <= 5n;
-
-export const isBlockSummaryV2 = (bs: BlockSummary): bs is BlockSummaryV2 =>
- bs.protocolVersion !== undefined && bs.protocolVersion > 5n;
diff --git a/packages/common/src/cis2/index.ts b/packages/common/src/cis2/index.ts
deleted file mode 100644
index d9d69d176..000000000
--- a/packages/common/src/cis2/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export type { CIS2 } from './util';
-export { tokenAddressFromBase58, tokenAddressToBase58 } from './util';
-export * from './CIS2Contract';
diff --git a/packages/common/src/cis4/index.ts b/packages/common/src/cis4/index.ts
deleted file mode 100644
index 9a37bc789..000000000
--- a/packages/common/src/cis4/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { CIS4, Web3IdSigner } from './util';
-export * from './CIS4Contract';
diff --git a/packages/common/src/constants.ts b/packages/common/src/constants.ts
deleted file mode 100644
index a57ac1bca..000000000
--- a/packages/common/src/constants.ts
+++ /dev/null
@@ -1 +0,0 @@
-export const DEFAULT_INVOKE_ENERGY = 1000000n;
diff --git a/packages/common/src/deserialization.ts b/packages/common/src/deserialization.ts
deleted file mode 100644
index 369fe8e4b..000000000
--- a/packages/common/src/deserialization.ts
+++ /dev/null
@@ -1,335 +0,0 @@
-import * as wasm from '@concordium/rust-bindings';
-import { Buffer } from 'buffer/';
-import { getAccountTransactionHandler } from './accountTransactions';
-import {
- AccountTransaction,
- AccountTransactionHeader,
- AccountTransactionSignature,
- BlockItemKind,
- isAccountTransactionType,
- SmartContractTypeValues,
- TypedCredentialDeployment,
-} from './types';
-import { AccountAddress } from './types/accountAddress';
-import { TransactionExpiry } from './types/transactionExpiry';
-import { PassThrough, Readable } from 'stream';
-
-/**
- * Reads an unsigned 8-bit integer from the given {@link Readable}.
- *
- * @param source input stream
- * @returns number from 0 to 255
- */
-export function deserializeUint8(source: Readable): number {
- return source.read(1).readUInt8(0);
-}
-
-/**
- * Given a contract's raw state, its name and its schema, return the state as a JSON object.
- * The return type is any, and the actual type should be determined by using the schema.
- */
-export function deserializeContractState(
- contractName: string,
- schema: Buffer,
- state: Buffer,
- verboseErrorMessage = false
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
-): any {
- const serializedState = wasm.deserializeState(
- contractName,
- state.toString('hex'),
- schema.toString('hex'),
- verboseErrorMessage
- );
- try {
- return JSON.parse(serializedState);
- } catch (e) {
- throw new Error(
- 'unable to deserialize state, due to: ' + serializedState
- ); // In this case serializedState is the error message from the rust module
- }
-}
-
-function deserializeMap(
- serialized: Readable,
- decodeSize: (size: Readable) => number,
- decodeKey: (k: Readable) => K,
- decodeValue: (t: Readable) => T
-): Record {
- const size = decodeSize(serialized);
- const result = {} as Record;
- for (let i = 0; i < size; i += 1) {
- const key = decodeKey(serialized);
- const value = decodeValue(serialized);
- result[key] = value;
- }
- return result;
-}
-
-function deserializeAccountTransactionSignature(
- signatures: Readable
-): AccountTransactionSignature {
- const decodeSignature = (serialized: Readable) => {
- const length = serialized.read(2).readUInt16BE(0);
- return serialized.read(length).toString('hex');
- };
- const decodeCredentialSignatures = (serialized: Readable) =>
- deserializeMap(
- serialized,
- deserializeUint8,
- deserializeUint8,
- decodeSignature
- );
- return deserializeMap(
- signatures,
- deserializeUint8,
- deserializeUint8,
- decodeCredentialSignatures
- );
-}
-
-function deserializeTransactionHeader(
- serializedHeader: Readable
-): AccountTransactionHeader {
- const sender = AccountAddress.fromBytes(
- Buffer.from(serializedHeader.read(32))
- );
- const nonce = serializedHeader.read(8).readBigUInt64BE(0);
- // TODO: extract payloadSize and energyAmount?
- // energyAmount
- serializedHeader.read(8).readBigUInt64BE(0);
- // payloadSize
- serializedHeader.read(4).readUInt32BE(0);
- const expiry = TransactionExpiry.fromEpochSeconds(
- serializedHeader.read(8).readBigUInt64BE(0),
- true
- );
- return {
- sender,
- nonce,
- expiry,
- };
-}
-
-function deserializeAccountTransaction(serializedTransaction: Readable): {
- accountTransaction: AccountTransaction;
- signatures: AccountTransactionSignature;
-} {
- const signatures = deserializeAccountTransactionSignature(
- serializedTransaction
- );
-
- const header = deserializeTransactionHeader(serializedTransaction);
-
- const transactionType = deserializeUint8(serializedTransaction);
- if (!isAccountTransactionType(transactionType)) {
- throw new Error(
- 'TransactionType is not a valid value: ' + transactionType
- );
- }
- const accountTransactionHandler =
- getAccountTransactionHandler(transactionType);
- const payload = accountTransactionHandler.deserialize(
- serializedTransaction
- );
-
- return {
- accountTransaction: {
- type: transactionType,
- payload,
- header,
- },
- signatures,
- };
-}
-
-function deserializeCredentialDeployment(serializedDeployment: Readable) {
- const raw = wasm.deserializeCredentialDeployment(
- serializedDeployment.read().toString('hex')
- );
- try {
- const parsed = JSON.parse(raw);
- return {
- credential: parsed.credential,
- expiry: parsed.messageExpiry,
- };
- } catch {
- // If the return value is not a proper JSON, it should be an error message.
- throw new Error(raw);
- }
-}
-
-export type BlockItem =
- | {
- kind: BlockItemKind.AccountTransactionKind;
- transaction: {
- accountTransaction: AccountTransaction;
- signatures: AccountTransactionSignature;
- };
- }
- | {
- kind: BlockItemKind.CredentialDeploymentKind;
- transaction: {
- credential: TypedCredentialDeployment;
- expiry: number;
- };
- };
-
-/**
- * Deserializes a transaction, from the binary format used to send it to the node, back into an js object.
- * @param serializedTransaction A buffer containing the binary transaction. It is expected to start with the version and blockItemKind.
- * @returns An object specifiying the blockItemKind that the transaction has. The object also contains the actual transaction under the transaction field.
- **/
-export function deserializeTransaction(
- serializedTransaction: Buffer
-): BlockItem {
- const bufferStream = new PassThrough();
- bufferStream.end(serializedTransaction);
-
- const version = deserializeUint8(bufferStream);
- if (version !== 0) {
- throw new Error(
- 'Supplied version ' +
- version +
- ' is not valid. Only transactions with version 0 format are supported'
- );
- }
- const blockItemKind = deserializeUint8(bufferStream);
- switch (blockItemKind) {
- case BlockItemKind.AccountTransactionKind:
- return {
- kind: BlockItemKind.AccountTransactionKind,
- transaction: deserializeAccountTransaction(bufferStream),
- };
- case BlockItemKind.CredentialDeploymentKind:
- return {
- kind: BlockItemKind.CredentialDeploymentKind,
- transaction: deserializeCredentialDeployment(bufferStream),
- };
- case BlockItemKind.UpdateInstructionKind:
- throw new Error(
- 'deserialization of UpdateInstructions is not supported'
- );
- default:
- throw new Error('Invalid blockItemKind');
- }
-}
-
-/**
- * Deserializes a receive functions's return value from a sequence of bytes into a json object.
- * @param returnValueBytes A buffer containing the return value as raw bytes.
- * @param moduleSchema The raw module schema as a buffer.
- * @param contractName The name of the contract where the receive function is located.
- * @param functionName The name of the receive function which return value you want to deserialize.
- * @param schemaVersion The schema version as a number. This parameter is optional, if you provide a serialized versioned schema this argument won't be needed.
- * @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`.
- */
-export function deserializeReceiveReturnValue(
- returnValueBytes: Buffer,
- moduleSchema: Buffer,
- contractName: string,
- functionName: string,
- schemaVersion?: number,
- verboseErrorMessage = false
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
-): any {
- const deserializedReturnValue = wasm.deserializeReceiveReturnValue(
- returnValueBytes.toString('hex'),
- moduleSchema.toString('hex'),
- contractName,
- functionName,
- schemaVersion,
- verboseErrorMessage
- );
- try {
- return JSON.parse(deserializedReturnValue);
- } catch (e) {
- throw new Error(
- 'unable to deserialize the return value, due to: ' +
- deserializedReturnValue
- ); // In this case deserializedReturnValue is the error message from the rust module
- }
-}
-
-/**
- * Deserializes a receive function's error from a sequence of bytes into a json object.
- * @param errorBytes A buffer containing the error as raw bytes.
- * @param moduleSchema The raw module schema as a buffer.
- * @param contractName The name of the contract where the receive function is located.
- * @param functionName The name of the receive function which error you want to deserialize.
- * @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`.
- */
-export function deserializeReceiveError(
- errorBytes: Buffer,
- moduleSchema: Buffer,
- contractName: string,
- functionName: string,
- verboseErrorMessage = false
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
-): any {
- const deserializedError = wasm.deserializeReceiveError(
- errorBytes.toString('hex'),
- moduleSchema.toString('hex'),
- contractName,
- functionName,
- verboseErrorMessage
- );
- try {
- return JSON.parse(deserializedError);
- } catch (e) {
- throw new Error(
- 'unable to deserialize the error value, due to: ' +
- deserializedError
- ); // In this case deserializedError is the error message from the rust module
- }
-}
-
-/**
- * Deserializes an init function's error from a sequence of bytes into a json object.
- * @param errorBytes A buffer containing the error as raw bytes.
- * @param moduleSchema The raw module schema as a buffer.
- * @param contractName The name of the init function which error you want to deserialize.
- * @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`.
- */
-export function deserializeInitError(
- errorBytes: Buffer,
- moduleSchema: Buffer,
- contractName: string,
- verboseErrorMessage = false
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
-): any {
- const deserializedError = wasm.deserializeInitError(
- errorBytes.toString('hex'),
- moduleSchema.toString('hex'),
- contractName,
- verboseErrorMessage
- );
- try {
- return JSON.parse(deserializedError);
- } catch (e) {
- throw new Error(
- 'unable to deserialize the error value, due to: ' +
- deserializedError
- ); // In this case deserializedError is the error message from the rust module
- }
-}
-
-/**
- * Given a binary value for a smart contract type, and the raw schema for that type, deserialize the value into the JSON representation.
- * @param value the value that should be deserialized.
- * @param rawSchema the schema for the type that the given value should be deserialized as
- * @param verboseErrorMessage Whether errors are in a verbose format or not. Defaults to `false`.
- * @returns the deserialized value
- */
-export function deserializeTypeValue(
- value: Buffer,
- rawSchema: Buffer,
- verboseErrorMessage = false
-): SmartContractTypeValues {
- const deserializedValue = wasm.deserializeTypeValue(
- value.toString('hex'),
- rawSchema.toString('hex'),
- verboseErrorMessage
- );
- return JSON.parse(deserializedValue);
-}
diff --git a/packages/common/src/index.ts b/packages/common/src/index.ts
deleted file mode 100644
index 502901489..000000000
--- a/packages/common/src/index.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { sha256 } from './hash';
-export * from './types';
-export {
- getAccountTransactionHash,
- getAccountTransactionSignDigest,
- getCredentialDeploymentSignDigest,
- getCredentialDeploymentTransactionHash,
- getCredentialForExistingAccountSignDigest,
- serializeInitContractParameters,
- serializeUpdateContractParameters,
- serializeAccountTransactionForSubmission,
- serializeCredentialDeploymentTransactionForSubmission,
- getSignedCredentialDeploymentTransactionHash,
- serializeTypeValue,
- serializeAccountTransactionPayload,
- serializeCredentialDeploymentPayload,
-} from './serialization';
-export { encodeHexString } from './serializationHelpers';
-export { sha256 };
-export { CredentialRegistrationId } from './types/CredentialRegistrationId';
-export { AccountAddress } from './types/accountAddress';
-export { CcdAmount } from './types/ccdAmount';
-export { TransactionExpiry } from './types/transactionExpiry';
-export { DataBlob } from './types/DataBlob';
-export { ModuleReference } from './types/moduleReference';
-export * from './types/VersionedModuleSource';
-export {
- VerifiablePresentation,
- reviveDateFromTimeStampAttribute,
- replaceDateWithTimeStampAttribute,
-} from './types/VerifiablePresentation';
-export * from './credentialDeploymentTransactions';
-export { isAlias, getAlias } from './alias';
-export {
- deserializeContractState,
- deserializeTransaction,
- deserializeReceiveReturnValue,
- deserializeReceiveError,
- deserializeInitError,
- deserializeTypeValue,
-} from './deserialization';
-
-export {
- StatementTypes,
- StatementBuilder,
- MIN_DATE,
- MAX_DATE,
- EU_MEMBERS,
-} from './commonProofTypes';
-export * from './idProofTypes';
-export * from './idProofs';
-export * from './web3ProofTypes';
-export * from './web3Proofs';
-
-export * from './signHelpers';
-export * from './versionedTypeHelpers';
-export * from './accountHelpers';
-export * from './blockSummaryHelpers';
-export * from './rewardStatusHelpers';
-export * from './HdWallet';
-export * from './schemaHelpers';
-export * from './web3IdHelpers';
-
-export { getContractName } from './contractHelpers';
-export { isHex, streamToList, wasmToSchema, unwrap } from './util';
-
-export { HttpProvider } from './providers/httpProvider';
-export { JsonRpcClient } from './JsonRpcClient';
-export * from './identity';
-export { ConcordiumGRPCClient } from './GRPCClient';
-
-export { getAccountTransactionHandler } from './accountTransactions';
-export * from './energyCost';
-
-export * from './uleb128';
-export * from './cis2';
-export * from './cis0';
-export * from './cis4';
-export * from './GenericContract';
diff --git a/packages/common/src/providers/httpProvider.ts b/packages/common/src/providers/httpProvider.ts
deleted file mode 100644
index 7abb88b5c..000000000
--- a/packages/common/src/providers/httpProvider.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import Provider, { JsonRpcRequest } from './provider';
-import fetch from 'cross-fetch';
-import JSONBig from 'json-bigint';
-import { v4 as uuidv4 } from 'uuid';
-
-/**
- * @deprecated This is only used by the JSON-RPC client, which has been deprecated
- */
-export class HttpProvider implements Provider {
- request: JsonRpcRequest;
- cookie?: string;
-
- /**
- * @param internalFetch Fetch function that performs the request. Defaults to using the cross-fetch package.
- */
- constructor(
- url: string,
- internalFetch: typeof fetch = fetch,
- onSetCookie?: (cookie: string) => void,
- initialCookie?: string,
- autoUpdateCookie = true
- ) {
- this.cookie = initialCookie;
- this.request = async function (method, params?) {
- const request = {
- method: method,
- params: params,
- id: uuidv4(),
- jsonrpc: '2.0',
- };
-
- const options = {
- method: 'POST',
- // Use JSONBig in order ensure bigints are automatically parsed (as numbers)
- body: JSONBig.stringify(request),
- headers: {
- 'Content-Type': 'application/json',
- ...(this.cookie && { cookie: this.cookie }),
- },
- };
-
- const res = await internalFetch(url, options);
- if (res.status >= 400) {
- const json = await res.json();
- if (json.error) {
- throw new Error(
- `${json.error.code}: ${json.error.message} (id: ${json.id})`
- );
- } else {
- throw new Error(
- `${res.status}: ${res.statusText} (id: ${json.id})`
- );
- }
- }
-
- const setCookieValue = res.headers.get('set-cookie');
- if (setCookieValue) {
- onSetCookie?.(setCookieValue);
- if (autoUpdateCookie) {
- this.updateCookie(setCookieValue);
- }
- }
-
- return res.text();
- };
- }
-
- updateCookie(newCookie: string): void {
- this.cookie = newCookie;
- }
-}
diff --git a/packages/common/src/providers/provider.ts b/packages/common/src/providers/provider.ts
deleted file mode 100644
index 67cb1e2b4..000000000
--- a/packages/common/src/providers/provider.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import { Invoker } from '../types';
-
-/* eslint-disable @typescript-eslint/no-explicit-any */
-interface JsonRpcResponseBase {
- jsonrpc: '2.0';
- id: string | null;
-}
-
-/**
- * @deprecated This is only used by the JSON-RPC client, which has been deprecated
- */
-export interface JsonRpcResponseError extends JsonRpcResponseBase {
- error: {
- code: number;
- message: string;
- data?: any;
- };
- result?: never;
-}
-
-/**
- * @deprecated This is only used by the JSON-RPC client, which has been deprecated
- */
-export interface JsonRpcResponseSuccess extends JsonRpcResponseBase {
- error?: never;
- result: Result;
-}
-
-/**
- * @deprecated This is only used by the JSON-RPC client, which has been deprecated
- */
-export type JsonRpcResponse =
- | JsonRpcResponseError
- | JsonRpcResponseSuccess;
-
-/**
- * @deprecated This is only used by the JSON-RPC client, which has been deprecated
- */
-export type JsonRpcRequest = (
- ...args:
- | ['getNextAccountNonce', { address: string }]
- | ['getTransactionStatus', { transactionHash: string }]
- | ['getConsensusStatus']
- | [
- 'getInstanceInfo',
- { blockHash: string; index: bigint; subindex: bigint }
- ]
- | ['sendTransaction', { transaction: string }]
- | ['getAccountInfo', { address: string; blockHash: string }]
- | ['getCryptographicParameters', { blockHash: string }]
- | ['getModuleSource', { blockHash: string; moduleReference: string }]
- | [
- 'invokeContract',
- {
- blockHash: string;
- context: {
- contract: { index: bigint; subindex: bigint };
- method: string;
- amount?: bigint;
- invoker: Invoker;
- energy?: bigint;
- parameter?: string;
- };
- }
- ]
-) => Promise;
-
-/**
- * @deprecated This is only used by the JSON-RPC client, which has been deprecated
- */
-export default interface Provider {
- request: JsonRpcRequest;
-}
diff --git a/packages/common/src/rewardStatusHelpers.ts b/packages/common/src/rewardStatusHelpers.ts
deleted file mode 100644
index 30697c623..000000000
--- a/packages/common/src/rewardStatusHelpers.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { RewardStatus, RewardStatusV1 } from './types';
-
-export function isRewardStatusV1(rs: RewardStatus): rs is RewardStatusV1 {
- return rs.protocolVersion !== undefined && rs.protocolVersion > 3n;
-}
diff --git a/packages/common/src/schemaHelpers.ts b/packages/common/src/schemaHelpers.ts
deleted file mode 100644
index 27394aaa8..000000000
--- a/packages/common/src/schemaHelpers.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { Buffer } from 'buffer/';
-import { SchemaVersion } from './types';
-import * as wasm from '@concordium/rust-bindings';
-
-/**
- * @param moduleSchema buffer for the schema of a module that contains the contract
- * @param contractName name of the contract that the init contract transaction will initialize
- * @param schemaVersion the version of the schema provided
- * @returns buffer containing the schema for of init contract parameters
- */
-export function getInitContractParameterSchema(
- moduleSchema: Buffer,
- contractName: string,
- schemaVersion?: SchemaVersion
-): Buffer {
- const parameterSchema = wasm.getInitContractParameterSchema(
- moduleSchema.toString('hex'),
- contractName,
- schemaVersion
- );
- return Buffer.from(parameterSchema, 'hex');
-}
-
-/**
- * @param moduleSchema buffer for the schema of a module that contains the contract
- * @param contractName name of the contract that the update contract transaction will update
- * @param receiveFunctionName name of function that the update contract transaction will invoke
- * @param schemaVersion the version of the schema provided
- * @returns buffer containing the schema for of update contract parameters
- */
-export function getUpdateContractParameterSchema(
- moduleSchema: Buffer,
- contractName: string,
- receiveFunctionName: string,
- schemaVersion?: SchemaVersion
-): Buffer {
- const parameterSchema = wasm.getReceiveContractParameterSchema(
- moduleSchema.toString('hex'),
- contractName,
- receiveFunctionName,
- schemaVersion
- );
- return Buffer.from(parameterSchema, 'hex');
-}
-
-/**
- * @param rawSchema the schema for the type
- * @returns JSON template of the schema
- */
-export function displayTypeSchemaTemplate(rawSchema: Buffer): string {
- return wasm.displayTypeSchemaTemplate(rawSchema.toString('hex'));
-}
diff --git a/packages/common/src/schemaTypes.ts b/packages/common/src/schemaTypes.ts
deleted file mode 100644
index a936258f5..000000000
--- a/packages/common/src/schemaTypes.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- * The JSON schema representation of a rust Option
- *
- * @template T - The type to represent as optional
- */
-export type OptionJson = { None: [] } | { Some: [T] };
-
-/**
- * Takes a value and wraps it in a {@link OptionJson}.
- *
- * @template T - The type to represent as optional
- *
- * @param {T} value - The value to wrap.
- *
- * @returns {OptionJson} the wrapped value
- */
-export function toOptionJson(value: T | undefined): OptionJson {
- if (value === undefined) {
- return { None: [] };
- }
-
- return { Some: [value] };
-}
diff --git a/packages/common/src/types/CredentialRegistrationId.ts b/packages/common/src/types/CredentialRegistrationId.ts
deleted file mode 100644
index 8daf30d1e..000000000
--- a/packages/common/src/types/CredentialRegistrationId.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { isHex } from '../util';
-
-/**
- * Representation of a credential registration id, which enforces that it:
- * - Is a valid Hex string
- * - Has length exactly 96, because a credId is 48 bytes.
- * - Checks the first bit is 1, which indicates that the value represents a compressed BLS12-381 curve point.
- */
-export class CredentialRegistrationId {
- credId: string;
-
- constructor(credId: string) {
- if (credId.length !== 96) {
- throw new Error(
- 'The provided credId ' +
- credId +
- ' is invalid as its length was not 96'
- );
- }
- if (!isHex(credId)) {
- throw new Error(
- 'The provided credId ' +
- credId +
- ' does not represent a hexidecimal value'
- );
- }
- // Check that the first bit is 1
- if ((parseInt(credId.substring(0, 2), 16) & 0b10000000) === 0) {
- throw new Error(
- 'The provided credId ' +
- credId +
- 'does not represent a compressed BLS12-381 point'
- );
- }
-
- this.credId = credId;
- }
-
- toJSON(): string {
- return this.credId;
- }
-}
diff --git a/packages/common/src/types/DataBlob.ts b/packages/common/src/types/DataBlob.ts
deleted file mode 100644
index 888db2070..000000000
--- a/packages/common/src/types/DataBlob.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { Buffer } from 'buffer/';
-import { packBufferWithWord16Length } from '../serializationHelpers';
-
-/**
- * Representation of a transfer's memo or a registerData transaction's data, which enforces that:
- * - the byte length is <= 256
- */
-export class DataBlob {
- data: Buffer;
-
- constructor(data: Buffer) {
- if (data.length > 256) {
- throw new Error("A data blob's size cannot exceed 256 bytes");
- }
- this.data = data;
- }
-
- toJSON(): string {
- return packBufferWithWord16Length(this.data).toString('hex');
- }
-}
diff --git a/packages/common/src/types/accountAddress.ts b/packages/common/src/types/accountAddress.ts
deleted file mode 100644
index e03bffcae..000000000
--- a/packages/common/src/types/accountAddress.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import bs58check from 'bs58check';
-import { Buffer } from 'buffer/';
-
-/**
- * Representation of an account address, which enforces that it:
- * - Hash length exactly 50
- * - Is a valid base58 string
- */
-export class AccountAddress {
- address: string;
-
- decodedAddress: Buffer;
-
- constructor(address: string) {
- if (address.length !== 50) {
- throw new Error(
- 'The provided address ' +
- address +
- ' is invalid as its length was not 50'
- );
- }
- try {
- this.decodedAddress = Buffer.from(
- bs58check.decode(address).subarray(1)
- );
- this.address = address;
- } catch (error) {
- throw error;
- }
- }
-
- static fromBytes(bytes: Buffer): AccountAddress {
- return new AccountAddress(
- bs58check.encode(Buffer.concat([Buffer.of(1), bytes]))
- );
- }
-
- toJSON(): string {
- return this.address;
- }
-}
diff --git a/packages/common/src/types/ccdAmount.ts b/packages/common/src/types/ccdAmount.ts
deleted file mode 100644
index e92772e74..000000000
--- a/packages/common/src/types/ccdAmount.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import { Big, BigSource } from 'big.js';
-
-const MICRO_CCD_PER_CCD = 1000000;
-
-/**
- * Representation of a CCD amount.
- * The base unit of CCD is micro CCD, which is the representation
- * used on chain.
- */
-export class CcdAmount {
- microCcdAmount: bigint;
-
- /**
- * Constructs a CcdAmount and checks that it is valid. It accepts a number, string, big, or bigint as parameter.
- * It can accept a string as parameter with either a comma or a dot as the decimal separator.
- *
- * @param microCcdAmount The amount of micro CCD as a number, string, big, or bigint.
- * @throws If an invalid micro CCD amount is passed, i.e. any value which is not an unsigned 64-bit integer
- */
- constructor(microCcdAmount: bigint | BigSource) {
- // If the input is a "BigSource" assert that the number is whole
- if (typeof microCcdAmount !== 'bigint') {
- microCcdAmount = newBig(microCcdAmount);
-
- if (!microCcdAmount.mod(Big(1)).eq(Big(0))) {
- throw Error(
- 'Can not create CcdAmount from a non-whole number!'
- );
- }
-
- microCcdAmount = BigInt(microCcdAmount.toFixed());
- }
-
- if (microCcdAmount < 0n) {
- throw new Error(
- 'A micro CCD amount must be a non-negative integer but was: ' +
- microCcdAmount
- );
- } else if (microCcdAmount > 18446744073709551615n) {
- throw new Error(
- 'A micro CCD amount must be representable as an unsigned 64 bit integer but was: ' +
- microCcdAmount
- );
- }
-
- this.microCcdAmount = microCcdAmount;
- }
-
- /**
- * Returns the amount of micro CCD as a Big.
- *
- * @returns The amount of micro CCD as a Big
- */
- toMicroCcd(): Big {
- return Big(this.microCcdAmount.toString());
- }
-
- /**
- * Returns the amount of CCD as a Big.
- *
- * @returns The amount of CCD as a Big
- */
- toCcd(): Big {
- return this.toMicroCcd().div(Big(MICRO_CCD_PER_CCD));
- }
-
- /**
- * Creates a CcdAmount from a number, string, big, or bigint.
- *
- * @param ccd The amount of micro CCD as a number, string, big or bigint.
- * @returns The CcdAmount object derived from the ccd input parameter
- * @throws If a number is passed with several decimal seperators
- * @throws If a negative amount of micro CCD is passed
- * @throws If the micro CCD passed is greater than what can be contained in a 64-bit integer
- */
- static fromCcd(ccd: BigSource | bigint): CcdAmount {
- if (typeof ccd === 'bigint') {
- ccd = ccd.toString();
- }
-
- const microCcd = newBig(ccd).mul(Big(MICRO_CCD_PER_CCD));
- return new CcdAmount(microCcd);
- }
-
- /**
- * Converts an amount of CCD to micro CCD and asserts that the amount is a valid amount of CCD.
- *
- * @param ccd The amount of CCD as a number, string, big or bigint.
- * @returns The amount of micro CCD as a Big
- * @throws If a number is passed with several decimal seperators
- * @throws If a negative amount of micro CCD is passed
- * @throws If the micro CCD passed is greater than what can be contained in a 64-bit integer
- */
- static ccdToMicroCcd(ccd: BigSource | bigint): Big {
- return CcdAmount.fromCcd(ccd).toMicroCcd();
- }
-
- /**
- * Converts an amount of micro CCD to CCD and asserts that the amount is a valid amount of CCD.
- *
- * @param microCcd The amount of micro CCD as a number, string, big or bigint.
- * @returns The amount of CCD as a Big
- * @throws If a number is passed with several decimal seperators
- * @throws If a negative amount of micro CCD is passed
- * @throws If the micro CCD passed is greater than what can be contained in a 64-bit integer
- */
- static microCcdToCcd(microCcd: BigSource | bigint): Big {
- return new CcdAmount(microCcd).toCcd();
- }
-
- toJSON(): string {
- return this.microCcdAmount.toString();
- }
-}
-
-function newBig(bigSource: BigSource): Big {
- if (typeof bigSource === 'string') {
- return Big(bigSource.replace(',', '.'));
- }
- return Big(bigSource);
-}
diff --git a/packages/common/src/types/moduleReference.ts b/packages/common/src/types/moduleReference.ts
deleted file mode 100644
index 35137bd15..000000000
--- a/packages/common/src/types/moduleReference.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { Buffer } from 'buffer/';
-import { packBufferWithWord32Length } from '../serializationHelpers';
-
-/**
- * Representation of a module reference, which enforces that it:
- * - Hash length exactly 64
- * - Is a valid 64 length hex string
- */
-export class ModuleReference {
- moduleRef: string;
-
- decodedModuleRef: Uint8Array;
-
- constructor(moduleRef: string) {
- if (moduleRef.length !== 64) {
- throw new Error(
- 'The provided moduleRef ' +
- moduleRef +
- ' is invalid as its length was not 64'
- );
- }
- try {
- this.decodedModuleRef = Buffer.from(moduleRef, 'hex');
- this.moduleRef = moduleRef;
- } catch (error) {
- throw error;
- }
- }
-
- static fromBytes(bytes: Buffer): ModuleReference {
- return new ModuleReference(bytes.toString('hex'));
- }
-
- toJSON(): string {
- return packBufferWithWord32Length(
- Buffer.from(this.decodedModuleRef)
- ).toString('hex');
- }
-}
diff --git a/packages/common/src/types/transactionExpiry.ts b/packages/common/src/types/transactionExpiry.ts
deleted file mode 100644
index ebcb164fd..000000000
--- a/packages/common/src/types/transactionExpiry.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { secondsSinceEpoch } from '../util';
-
-/**
- * Representation of a transaction expiry date.
- *
- * A transaction expiry has to be in the future. Note that the concordium-node
- * will reject transactions that are too far into the future, currently the default
- * value for this rejection is 2 hours.
- */
-export class TransactionExpiry {
- /** expiry is measured as seconds since epoch */
- expiryEpochSeconds: bigint;
-
- constructor(expiry: Date, allowExpired = false) {
- if (!allowExpired && expiry < new Date()) {
- throw new Error(
- 'A transaction expiry is not allowed to be in the past: ' +
- expiry
- );
- }
- this.expiryEpochSeconds = secondsSinceEpoch(expiry);
- }
-
- static fromEpochSeconds(
- seconds: bigint,
- allowExpired = false
- ): TransactionExpiry {
- return new TransactionExpiry(
- new Date(Number(seconds) * 1000),
- allowExpired
- );
- }
-
- toJSON(): number {
- return Number(this.expiryEpochSeconds);
- }
-}
diff --git a/packages/common/src/versionedTypeHelpers.ts b/packages/common/src/versionedTypeHelpers.ts
deleted file mode 100644
index e05a3b868..000000000
--- a/packages/common/src/versionedTypeHelpers.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import {
- AccountInfo,
- AccountInfoBakerV0,
- AccountInfoBakerV1,
- Authorizations,
- AuthorizationsV1,
- BlockInfo,
- BlockInfoV0,
- BlockInfoV1,
- ChainParameters,
- ChainParametersV0,
- ChainParametersV1,
- ChainParametersV2,
- ConsensusStatus,
- ConsensusStatusV0,
- ConsensusStatusV1,
- ElectionInfo,
- ElectionInfoV0,
- ElectionInfoV1,
- Keys,
- KeysV0,
- KeysV1,
- StakePendingChange,
- StakePendingChangeV0,
- StakePendingChangeV1,
-} from './types';
-
-/** Whether {@link AccountInfo} parameter given is of type {@link AccountInfoBakerV0} */
-export const isBakerAccountV0 = (ai: AccountInfo): ai is AccountInfoBakerV0 =>
- (ai as AccountInfoBakerV1).accountBaker?.bakerPoolInfo === undefined;
-
-/** Whether {@link AccountInfo} parameter given is of type {@link AccountInfoBakerV1} */
-export const isBakerAccountV1 = (ai: AccountInfo): ai is AccountInfoBakerV1 =>
- (ai as AccountInfoBakerV1).accountBaker?.bakerPoolInfo !== undefined;
-
-/** Whether {@link StakePendingChange} parameter given is of type {@link StakePendingChangeV0} */
-export const isStakePendingChangeV0 = (
- spc: StakePendingChange
-): spc is StakePendingChangeV0 =>
- (spc as StakePendingChangeV0).epoch !== undefined;
-
-/** Whether {@link StakePendingChange} parameter given is of type {@link StakePendingChangeV1} */
-export const isStakePendingChangeV1 = (
- spc: StakePendingChange
-): spc is StakePendingChangeV1 =>
- (spc as StakePendingChangeV1).effectiveTime !== undefined;
-
-/** Whether {@link Authorizations} parameter given is of type {@link AuthorizationsV1} */
-export const isAuthorizationsV1 = (
- as: Authorizations
-): as is AuthorizationsV1 =>
- (as as AuthorizationsV1).timeParameters !== undefined;
-
-/** Whether {@link ChainParameters} parameter given is of type {@link ChainParametersV0} */
-export const isChainParametersV0 = (
- cp: ChainParameters
-): cp is ChainParametersV0 =>
- (cp as ChainParametersV0).minimumThresholdForBaking !== undefined;
-
-/** Whether {@link ChainParameters} parameter given is of type {@link ChainParametersV1} */
-export const isChainParametersV1 = (
- cp: ChainParameters
-): cp is ChainParametersV1 =>
- (cp as ChainParametersV1).mintPerPayday !== undefined &&
- !isChainParametersV2(cp);
-
-/** Whether {@link ChainParameters} parameter given is of type {@link ChainParametersV2} */
-export const isChainParametersV2 = (
- cp: ChainParameters
-): cp is ChainParametersV2 =>
- (cp as ChainParametersV2).maximumFinalizers !== undefined;
-
-/** Whether {@link Keys} parameter given is of type {@link KeysV0} */
-export const isKeysV0 = (ks: Keys): ks is KeysV0 =>
- !isAuthorizationsV1(ks.level2Keys);
-
-/** Whether {@link Keys} parameter given is of type {@link KeysV1} */
-export const isKeysV1 = (ks: Keys): ks is KeysV1 =>
- isAuthorizationsV1(ks.level2Keys);
-
-/** Whether {@link BlockInfo} parameter given is of type {@link BlockInfoV0} */
-export const isBlockInfoV0 = (bi: BlockInfo): bi is BlockInfoV0 =>
- (bi as BlockInfoV0).blockSlot !== undefined;
-
-/** Whether {@link BlockInfo} parameter given is of type {@link BlockInfoV1} */
-export const isBlockInfoV1 = (bi: BlockInfo): bi is BlockInfoV1 =>
- (bi as BlockInfoV1).round !== undefined;
-
-/** Whether {@link ConensusStatus} parameter given is of type {@link ConsensusStatusV0} */
-export const isConsensusStatusV0 = (
- cs: ConsensusStatus
-): cs is ConsensusStatusV0 => (cs as ConsensusStatusV0).slotDuration != null;
-
-/** Whether {@link ConensusStatus} parameter given is of type {@link ConsensusStatusV1} */
-export const isConsensusStatusV1 = (
- cs: ConsensusStatus
-): cs is ConsensusStatusV1 =>
- (cs as ConsensusStatusV1).concordiumBFTStatus !== undefined;
-
-/** Whether {@link ElectionInfo} parameter given is of type {@link ElectionInfoV0} */
-export const isElectionInfoV0 = (ei: ElectionInfo): ei is ElectionInfoV0 =>
- (ei as ElectionInfoV0).electionDifficulty !== undefined;
-
-/** Whether {@link ElectionInfo} parameter given is of type {@link ElectionInfoV1} */
-export const isElectionInfoV1 = (ei: ElectionInfo): ei is ElectionInfoV1 =>
- !isElectionInfoV0(ei);
diff --git a/packages/common/test/alias.test.ts b/packages/common/test/alias.test.ts
deleted file mode 100644
index c87d9ed1b..000000000
--- a/packages/common/test/alias.test.ts
+++ /dev/null
@@ -1,146 +0,0 @@
-import { AccountAddress } from '../src/types/accountAddress';
-import * as bs58check from 'bs58check';
-import { getAlias, isAlias } from '../src/alias';
-import { Buffer } from 'buffer/';
-
-test('isAlias is reflexive', () => {
- const address = new AccountAddress(
- bs58check.encode(
- Buffer.from(
- '01e718721402249e81f8fedcba6027f1c9bcb4445e9433b7905d579d83ec000002',
- 'hex'
- )
- )
- );
- expect(isAlias(address, address)).toBeTruthy();
-});
-
-test('isAlias: Addresses with first 29 bytes in common are aliases', () => {
- const address = new AccountAddress(
- bs58check.encode(
- Buffer.from(
- '01e718721402249e81f8fedcba6027f1c9bcb4445e9433b7905d579d83ec000002',
- 'hex'
- )
- )
- );
- const alias = new AccountAddress(
- bs58check.encode(
- Buffer.from(
- '01e718721402249e81f8fedcba6027f1c9bcb4445e9433b7905d579d83ececb467',
- 'hex'
- )
- )
- );
- expect(isAlias(address, alias)).toBeTruthy();
-});
-
-test('isAlias: Addresses with differences in the 5th byte are not aliases', () => {
- const address = new AccountAddress(
- bs58check.encode(
- Buffer.from(
- '01e718721412249e81f8fedcba6027f1c9bcb4445e9433b7905d579d83ec000002',
- 'hex'
- )
- )
- );
- const alias = new AccountAddress(
- bs58check.encode(
- Buffer.from(
- '01e718721402249e81f8fedcba6027f1c9bcb4445e9433b7905d579d83ec000002',
- 'hex'
- )
- )
- );
- expect(isAlias(address, alias)).toBeFalsy();
-});
-
-test('isAlias: Addresses with differences in the 29th byte are not aliases', () => {
- const address = new AccountAddress(
- bs58check.encode(
- Buffer.from(
- '01e718721402249e81f8fedcba6027f1c9bcb4445e9433b7905d579d83ececb467',
- 'hex'
- )
- )
- );
- const alias = new AccountAddress(
- bs58check.encode(
- Buffer.from(
- '01e718721402249e81f8fedcba6027f1c9bcb4445e9433b7905d579d83e1ecb467',
- 'hex'
- )
- )
- );
- expect(isAlias(address, alias)).toBeFalsy();
-});
-
-test('getAlias: getAlias returns an alias', () => {
- const address = new AccountAddress(
- '4hXCdgNTxgM7LNm8nFJEfjDhEcyjjqQnPSRyBS9QgmHKQVxKRf'
- );
- const alias = getAlias(address, 1);
- expect(isAlias(address, alias)).toBeTruthy();
-});
-
-test('getAlias: changing counter makes getAlias return different aliases', () => {
- const address = new AccountAddress(
- '4hXCdgNTxgM7LNm8nFJEfjDhEcyjjqQnPSRyBS9QgmHKQVxKRf'
- );
- const alias = getAlias(address, 1);
- const otherAlias = getAlias(address, 100);
- expect(otherAlias.address).not.toBe(alias.address);
- expect(isAlias(otherAlias, alias)).toBeTruthy();
-});
-
-test('getAlias: last 3 bytes of alias matches counter', () => {
- const address = new AccountAddress(
- '4hXCdgNTxgM7LNm8nFJEfjDhEcyjjqQnPSRyBS9QgmHKQVxKRf'
- );
- let alias = getAlias(address, 0xaaaaaa);
- expect(alias.decodedAddress.slice(29, 32).toString('hex')).toBe('aaaaaa');
- alias = getAlias(address, 0x152637);
- expect(alias.decodedAddress.slice(29, 32).toString('hex')).toBe('152637');
- alias = getAlias(address, 0x000000);
- expect(alias.decodedAddress.slice(29, 32).toString('hex')).toBe('000000');
- alias = getAlias(address, 0xffffff);
- expect(alias.decodedAddress.slice(29, 32).toString('hex')).toBe('ffffff');
-});
-
-test('getAlias: using counter = "last 3 bytes of address" returns the address', () => {
- const address = new AccountAddress(
- '4hXCdgNTxgM7LNm8nFJEfjDhEcyjjqQnPSRyBS9QgmHKQVxKRf'
- );
- const alsoAddress = getAlias(address, 0xecb198);
- expect(alsoAddress.address).toBe(address.address);
-});
-
-test('getAlias: accepts counter = 0', () => {
- const address = new AccountAddress(
- '4hXCdgNTxgM7LNm8nFJEfjDhEcyjjqQnPSRyBS9QgmHKQVxKRf'
- );
- const alias = getAlias(address, 0);
- expect(isAlias(address, alias)).toBeTruthy();
-});
-
-test('getAlias: does not accept counter = -1', () => {
- const address = new AccountAddress(
- '4hXCdgNTxgM7LNm8nFJEfjDhEcyjjqQnPSRyBS9QgmHKQVxKRf'
- );
- expect(() => getAlias(address, -1)).toThrowError();
-});
-
-test('getAlias: accepts counter === 2^24 - 1', () => {
- const address = new AccountAddress(
- '4hXCdgNTxgM7LNm8nFJEfjDhEcyjjqQnPSRyBS9QgmHKQVxKRf'
- );
- const alias = getAlias(address, 0xffffff);
- expect(isAlias(address, alias)).toBeTruthy();
-});
-
-test('getAlias: does not accept counter === 2^24', () => {
- const address = new AccountAddress(
- '4hXCdgNTxgM7LNm8nFJEfjDhEcyjjqQnPSRyBS9QgmHKQVxKRf'
- );
- expect(() => getAlias(address, 0x01000000)).toThrowError();
-});
diff --git a/packages/common/test/deserialization.test.ts b/packages/common/test/deserialization.test.ts
deleted file mode 100644
index cf42fd25a..000000000
--- a/packages/common/test/deserialization.test.ts
+++ /dev/null
@@ -1,307 +0,0 @@
-import {
- deserializeContractState,
- deserializeTransaction,
- deserializeReceiveReturnValue,
- deserializeReceiveError,
- deserializeInitError,
-} from '../src/deserialization';
-import { Buffer } from 'buffer/';
-import { serializeAccountTransactionForSubmission } from '../src/serialization';
-import {
- AccountAddress,
- AccountTransaction,
- AccountTransactionHeader,
- AccountTransactionPayload,
- AccountTransactionSignature,
- AccountTransactionType,
- BlockItemKind,
- DataBlob,
- CcdAmount,
- RegisterDataPayload,
- SimpleTransferPayload,
- SimpleTransferWithMemoPayload,
- TransactionExpiry,
- deserializeTypeValue,
- tokenAddressFromBase58,
- tokenAddressToBase58,
-} from '../src';
-import * as fs from 'fs';
-import {
- CIS2_WCCD_STATE_SCHEMA,
- V0_PIGGYBANK_SCHEMA,
- CIS2_WCCD_STATE_GET_BALANCE_RETURN_VALUE_SCHEMA,
- TEST_CONTRACT_INIT_ERROR_SCHEMA,
- TEST_CONTRACT_SCHEMA,
- TEST_CONTRACT_RECEIVE_ERROR_SCHEMA,
- AUCTION_WITH_ERRORS_VIEW_RETURN_VALUE_SCHEMA,
-} from './resources/schema';
-
-test('test that deserializeContractState works', () => {
- const state = deserializeContractState(
- 'PiggyBank',
- Buffer.from(V0_PIGGYBANK_SCHEMA, 'base64'),
- Buffer.from('00', 'hex')
- );
-
- expect(state.Intact).toBeDefined();
-});
-
-function deserializeAccountTransactionBase(
- type: AccountTransactionType,
- payload: AccountTransactionPayload,
- expiry = new TransactionExpiry(new Date(Date.now() + 1200000))
-) {
- const header: AccountTransactionHeader = {
- expiry,
- nonce: 0n,
- sender: new AccountAddress(
- '3VwCfvVskERFAJ3GeJy2mNFrzfChqUymSJJCvoLAP9rtAwMGYt'
- ),
- };
-
- const transaction: AccountTransaction = {
- header,
- payload,
- type,
- };
-
- const signatures: AccountTransactionSignature = {
- 0: {
- 0: '780e4f5e00554fb4e235c67795fbd6d4ad638f3778199713f03634c846e4dbec496f0b13c4454e1a760c3efffec7cc8c11c6053a632dd32c9714cd26952cda08',
- },
- };
-
- const deserialized = deserializeTransaction(
- serializeAccountTransactionForSubmission(transaction, signatures)
- );
-
- if (deserialized.kind !== BlockItemKind.AccountTransactionKind) {
- throw new Error('Incorrect BlockItemKind');
- }
-
- expect(deserialized.transaction).toEqual({
- accountTransaction: transaction,
- signatures,
- });
-}
-
-test('test deserialize simpleTransfer ', () => {
- const payload: SimpleTransferPayload = {
- amount: new CcdAmount(5100000n),
- toAddress: new AccountAddress(
- '3VwCfvVskERFAJ3GeJy2mNFrzfChqUymSJJCvoLAP9rtAwMGYt'
- ),
- };
- deserializeAccountTransactionBase(AccountTransactionType.Transfer, payload);
-});
-
-test('test deserialize simpleTransfer with memo ', () => {
- const payload: SimpleTransferWithMemoPayload = {
- amount: new CcdAmount(5100000n),
- toAddress: new AccountAddress(
- '3VwCfvVskERFAJ3GeJy2mNFrzfChqUymSJJCvoLAP9rtAwMGYt'
- ),
- memo: new DataBlob(Buffer.from('00', 'hex')),
- };
- deserializeAccountTransactionBase(
- AccountTransactionType.TransferWithMemo,
- payload
- );
-});
-
-test('test deserialize registerData ', () => {
- const payload: RegisterDataPayload = {
- data: new DataBlob(Buffer.from('00AB5303926810EE', 'hex')),
- };
- deserializeAccountTransactionBase(
- AccountTransactionType.RegisterData,
- payload
- );
-});
-
-test('Expired transactions can be deserialized', () => {
- const payload: SimpleTransferPayload = {
- amount: new CcdAmount(5100000n),
- toAddress: new AccountAddress(
- '3VwCfvVskERFAJ3GeJy2mNFrzfChqUymSJJCvoLAP9rtAwMGYt'
- ),
- };
- deserializeAccountTransactionBase(
- AccountTransactionType.Transfer,
- payload,
- new TransactionExpiry(new Date(2000, 1), true)
- );
-});
-
-test('Receive return value can be deserialized', () => {
- const returnValue = deserializeReceiveReturnValue(
- Buffer.from('80f18c27', 'hex'),
- Buffer.from(CIS2_WCCD_STATE_SCHEMA, 'base64'),
- 'CIS2-wCCD-State',
- 'getBalance'
- );
-
- expect(returnValue).toEqual('82000000');
-});
-
-/**
- * Repeats the "Receive return value can be deserialized" test, using deserializeTypeValue and a type specific schema instead.
- */
-test('Receive return value can be deserialized using deserializeTypeValue', () => {
- const returnValue = deserializeTypeValue(
- Buffer.from('80f18c27', 'hex'),
- Buffer.from(CIS2_WCCD_STATE_GET_BALANCE_RETURN_VALUE_SCHEMA, 'base64')
- );
- expect(returnValue).toEqual('82000000');
-});
-
-const auctionRawReturnValue = Buffer.from(
- '00000b0000004120676f6f64206974656d00a4fbca84010000',
- 'hex'
-);
-
-/**
- * Small helper for expected deserialized value of rawAuctionReturnValue
- */
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-const expectAuctionReturnValue = (returnValue: any) => {
- expect(returnValue.item).toEqual('A good item');
- expect(returnValue.end).toEqual('2022-12-01T00:00:00+00:00');
- expect(returnValue.auction_state).toHaveProperty('NotSoldYet');
- expect(returnValue.highest_bidder).toHaveProperty('None');
-};
-
-test('Return value can be deserialized - auction', () => {
- const returnValue = deserializeReceiveReturnValue(
- auctionRawReturnValue,
- Buffer.from(
- fs.readFileSync('./test/resources/auction-with-errors-schema.bin')
- ),
- 'auction',
- 'view'
- );
-
- expectAuctionReturnValue(returnValue);
-});
-
-/**
- * Repeats the "Return value can be deserialized - auction" test, using deserializeTypeValue and a type specific schema instead.
- */
-test('Return value can be deserialized - auction using deserializeTypeValue', () => {
- const returnValue = deserializeTypeValue(
- auctionRawReturnValue,
- Buffer.from(AUCTION_WITH_ERRORS_VIEW_RETURN_VALUE_SCHEMA, 'base64')
- );
-
- expectAuctionReturnValue(returnValue);
-});
-
-test('Receive error can be deserialized', () => {
- const error = deserializeReceiveError(
- Buffer.from('ffff', 'hex'),
- Buffer.from(TEST_CONTRACT_SCHEMA, 'base64'),
- 'TestContract',
- 'receive_function'
- );
-
- expect(error).toEqual(-1);
-});
-
-/**
- * Repeats the "Receive error can be deserialized" test, using deserializeTypeValue and a type specific schema instead.
- */
-test('Receive error can be deserialized using deserializeTypeValue', () => {
- const error = deserializeTypeValue(
- Buffer.from('ffff', 'hex'),
- Buffer.from(TEST_CONTRACT_RECEIVE_ERROR_SCHEMA, 'base64')
- );
- expect(error).toEqual(-1);
-});
-
-test('Init error can be deserialized', () => {
- const error = deserializeInitError(
- Buffer.from('0100', 'hex'),
- Buffer.from(TEST_CONTRACT_SCHEMA, 'base64'),
- 'TestContract'
- );
-
- expect(error).toEqual(1);
-});
-
-/**
- * Repeats the "Init error can be deserialized" test, using deserializeTypeValue and a type specific schema instead.
- */
-test('Init error can be deserialized using deserializeTypeValue', () => {
- const error = deserializeTypeValue(
- Buffer.from('0100', 'hex'),
- Buffer.from(TEST_CONTRACT_INIT_ERROR_SCHEMA, 'base64')
- );
- expect(error).toEqual(1);
-});
-
-test('Test parsing of Token Addresses', () => {
- let base58 = '5Pxr5EUtU';
- let address = tokenAddressFromBase58(base58);
- let rebase58 = tokenAddressToBase58(address);
- let expectedAddress = {
- contract: {
- index: 0n,
- subindex: 0n,
- },
- id: '',
- };
- expect(address).toEqual(expectedAddress);
- expect(rebase58).toEqual(base58);
-
- base58 = 'LQMMu3bAg7';
- address = tokenAddressFromBase58(base58);
- rebase58 = tokenAddressToBase58(address);
- expectedAddress = {
- contract: {
- index: 0n,
- subindex: 0n,
- },
- id: 'aa',
- };
- expect(address).toEqual(expectedAddress);
- expect(rebase58).toEqual(base58);
-
- base58 = '5QTdu98KF';
- address = tokenAddressFromBase58(base58);
- rebase58 = tokenAddressToBase58(address);
- const expectedAddress2 = {
- contract: {
- index: 1n,
- subindex: 0n,
- },
- id: '',
- };
- expect(address).toEqual(expectedAddress2);
- expect(rebase58).toEqual(base58);
-
- base58 = 'LSYqgoQcb6';
- address = tokenAddressFromBase58(base58);
- rebase58 = tokenAddressToBase58(address);
- expectedAddress = {
- contract: {
- index: 1n,
- subindex: 0n,
- },
- id: 'aa',
- };
- expect(address).toEqual(expectedAddress);
- expect(rebase58).toEqual(base58);
-
- base58 = 'LSYXivPSWP';
- address = tokenAddressFromBase58(base58);
- rebase58 = tokenAddressToBase58(address);
- expectedAddress = {
- contract: {
- index: 1n,
- subindex: 0n,
- },
- id: '0a',
- };
- expect(address).toEqual(expectedAddress);
- expect(rebase58).toEqual(base58);
-});
diff --git a/packages/common/test/schemaHelpers.test.ts b/packages/common/test/schemaHelpers.test.ts
deleted file mode 100644
index 52aaf3a88..000000000
--- a/packages/common/test/schemaHelpers.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import fs from 'fs';
-import { Buffer } from 'buffer/';
-import {
- displayTypeSchemaTemplate,
- getUpdateContractParameterSchema,
-} from '../src/schemaHelpers';
-
-test('schema template display', () => {
- const fullSchema = Buffer.from(
- fs.readFileSync('./test/resources/cis2-nft-schema.bin')
- );
- const schemaVersion = 1;
- const contractName = 'CIS2-NFT';
- const functionName = 'transfer';
- const template = displayTypeSchemaTemplate(
- getUpdateContractParameterSchema(
- fullSchema,
- contractName,
- functionName,
- schemaVersion
- )
- );
- expect(template).toBe(
- '[{"amount":["",""],"data":[""],"from":{"Enum":[{"Account":[""]},{"Contract":[{"index":"","subindex":""}]}]},"to":{"Enum":[{"Account":[""]},{"Contract":[{"index":"","subindex":""},{"contract":"","func":""}]}]},"token_id":[""]}]'
- );
-});
diff --git a/packages/common/test/serialization.test.ts b/packages/common/test/serialization.test.ts
deleted file mode 100644
index 5d4813448..000000000
--- a/packages/common/test/serialization.test.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-import fs from 'fs';
-import { Buffer } from 'buffer/';
-import { AccountAddress } from '../src/types/accountAddress';
-import { CcdAmount } from '../src/types/ccdAmount';
-import {
- serializeAccountTransactionForSubmission,
- serializeAccountTransactionSignature,
- serializeUpdateContractParameters,
- serializeTypeValue,
-} from '../src/serialization';
-import {
- AccountTransaction,
- AccountTransactionHeader,
- AccountTransactionSignature,
- AccountTransactionType,
- SimpleTransferPayload,
-} from '../src/types';
-import { TransactionExpiry } from '../src/types/transactionExpiry';
-import { getUpdateContractParameterSchema } from '../src';
-
-test('fail account transaction serialization if no signatures', () => {
- const simpleTransferPayload: SimpleTransferPayload = {
- amount: new CcdAmount(5100000n),
- toAddress: new AccountAddress(
- '3VwCfvVskERFAJ3GeJy2mNFrzfChqUymSJJCvoLAP9rtAwMGYt'
- ),
- };
-
- const header: AccountTransactionHeader = {
- expiry: new TransactionExpiry(new Date(Date.now() + 1200000)),
- nonce: 0n,
- sender: new AccountAddress(
- '3VwCfvVskERFAJ3GeJy2mNFrzfChqUymSJJCvoLAP9rtAwMGYt'
- ),
- };
-
- const simpleTransferAccountTransaction: AccountTransaction = {
- header: header,
- payload: simpleTransferPayload,
- type: AccountTransactionType.Transfer,
- };
-
- expect(() =>
- serializeAccountTransactionForSubmission(
- simpleTransferAccountTransaction,
- {}
- )
- ).toThrow();
-});
-
-test('serialization of an account signature with two credentials', () => {
- const signature: AccountTransactionSignature = {
- 0: {
- 0: '893f2e4a230bcbeee24675454c4ca95a2f55fd33f328958b626c6fa368341e07902c9ffe7864c3bee23b2b2300ed0922eb814ea41fdee25035be8cddc5c3980f',
- },
- 1: {
- 0: '620d859224c40160c2bb03dbe84e9f57b8ed17f1a5df28b4e21f10658992531ef27655e6b74b8e47923e1ccb0413d563205e8b6c0cd22b3adce5dc7dc1daf603',
- },
- };
-
- const serializedSignature = serializeAccountTransactionSignature(signature);
- expect(serializedSignature.toString('hex')).toBe(
- '020001000040893f2e4a230bcbeee24675454c4ca95a2f55fd33f328958b626c6fa368341e07902c9ffe7864c3bee23b2b2300ed0922eb814ea41fdee25035be8cddc5c3980f0101000040620d859224c40160c2bb03dbe84e9f57b8ed17f1a5df28b4e21f10658992531ef27655e6b74b8e47923e1ccb0413d563205e8b6c0cd22b3adce5dc7dc1daf603'
- );
-});
-
-test('serialize UpdateContractParameters using CIS2 contract', () => {
- const parameter = serializeUpdateContractParameters(
- 'CIS2-NFT',
- 'transfer',
- [
- {
- token_id: [],
- amount: [200, 0],
- from: {
- Account: [
- '4RgTGQhg1Y8DAUkC2TpZsKmXdicArDqY9gcgJmBDECg4kkYNg4',
- ],
- },
- to: {
- Account: [
- '3UiNwnmZ64YR423uamgZyY8RnRkD88tfn6SYtKzvWZCkyFdN94',
- ],
- },
- data: [],
- },
- ],
- Buffer.from(fs.readFileSync('./test/resources/cis2-nft-schema.bin')),
- 1
- );
-
- expect(parameter.toString('hex')).toBe(
- '010000c80000c320b41f1997accd5d21c6bf4992370948ed711435e0e2c9302def62afd1295f004651a37c65c8461540decd511e7440d1ff6d4191b7e2133b7239b2485be1a4860000'
- );
-});
-
-test('serialize UpdateContractParameters using CIS2 contract and incorrect name', () => {
- const parameter = function () {
- serializeUpdateContractParameters(
- 'CIS2-NFT',
- 'non-existent',
- [
- {
- token_id: [],
- amount: [200, 0],
- from: {
- Account: [
- '4RgTGQhg1Y8DAUkC2TpZsKmXdicArDqY9gcgJmBDECg4kkYNg4',
- ],
- },
- to: {
- Account: [
- '3UiNwnmZ64YR423uamgZyY8RnRkD88tfn6SYtKzvWZCkyFdN94',
- ],
- },
- data: [],
- },
- ],
- Buffer.from(
- fs.readFileSync('./test/resources/cis2-nft-schema.bin')
- ),
- 1
- );
- };
-
- expect(parameter).toThrow();
-});
-
-test('serialize type value and serializeUpdateContractParameters give same result', () => {
- const parameters = [
- {
- token_id: [],
- amount: [200, 0],
- from: {
- Account: ['4RgTGQhg1Y8DAUkC2TpZsKmXdicArDqY9gcgJmBDECg4kkYNg4'],
- },
- to: {
- Account: ['3UiNwnmZ64YR423uamgZyY8RnRkD88tfn6SYtKzvWZCkyFdN94'],
- },
- data: [],
- },
- ];
- const fullSchema = Buffer.from(
- fs.readFileSync('./test/resources/cis2-nft-schema.bin')
- );
- const schemaVersion = 1;
- const contractName = 'CIS2-NFT';
- const functionName = 'transfer';
-
- const serializedParameter = serializeUpdateContractParameters(
- contractName,
- functionName,
- parameters,
- fullSchema,
- schemaVersion
- );
-
- const serializedType = serializeTypeValue(
- parameters,
- getUpdateContractParameterSchema(
- fullSchema,
- contractName,
- functionName,
- schemaVersion
- )
- );
-
- expect(serializedParameter.toString('hex')).toEqual(
- serializedType.toString('hex')
- );
-});
-
-test('serializeTypeValue throws an error if unable to serialize', () => {
- expect(() => serializeTypeValue('test', Buffer.alloc(0))).toThrowError(
- Error
- );
-});
diff --git a/packages/common/test/types/blockSpecialEvents.test.ts b/packages/common/test/types/blockSpecialEvents.test.ts
deleted file mode 100644
index 3b08be905..000000000
--- a/packages/common/test/types/blockSpecialEvents.test.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-import {
- BlockSpecialEventBakingRewards,
- BlockSpecialEventPaydayPoolReward,
- BlockSpecialEventBlockAccrueReward,
- BlockSpecialEventPaydayFoundationReward,
- BlockSpecialEventFinalizationRewards,
- BlockSpecialEventMint,
- BlockSpecialEventPaydayAccountReward,
- BlockSpecialEventBlockReward,
- specialEventAffectedAccounts,
-} from '../../src';
-
-const bakingRewards: BlockSpecialEventBakingRewards = {
- tag: 'bakingRewards',
- remainder: 0n,
- bakingRewards: [
- {
- account: '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe',
- amount: 400000n,
- },
- {
- account: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV',
- amount: 400000n,
- },
- ],
-};
-
-const finalizationRewards: BlockSpecialEventFinalizationRewards = {
- tag: 'finalizationRewards',
- remainder: 0n,
- finalizationRewards: [
- {
- account: '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe',
- amount: 400000n,
- },
- {
- account: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV',
- amount: 400000n,
- },
- ],
-};
-
-const foundationReward: BlockSpecialEventPaydayFoundationReward = {
- tag: 'paydayFoundationReward',
- developmentCharge: 123n,
- foundationAccount: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV',
-};
-
-const mint: BlockSpecialEventMint = {
- tag: 'mint',
- mintBakingReward: 0n,
- mintFinalizationReward: 0n,
- mintPlatformDevelopmentCharge: 0n,
- foundationAccount: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV',
-};
-
-const paydayAccountReward: BlockSpecialEventPaydayAccountReward = {
- tag: 'paydayAccountReward',
- account: '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe',
- transactionFees: 123n,
- bakerReward: 123n,
- finalizationReward: 123n,
-};
-
-const foundationBlockReward: BlockSpecialEventBlockReward = {
- tag: 'blockReward',
- transactionFees: 1231241n,
- bakerReward: 12314n,
- foundationCharge: 12n,
- newGasAccount: 1n,
- oldGasAccount: 0n,
- baker: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV',
- foundationAccount: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV',
-};
-
-const blockReward: BlockSpecialEventBlockReward = {
- tag: 'blockReward',
- transactionFees: 1231241n,
- bakerReward: 12314n,
- foundationCharge: 12n,
- newGasAccount: 1n,
- oldGasAccount: 0n,
- baker: '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe',
- foundationAccount: '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV',
-};
-
-const paydayPoolReward: BlockSpecialEventPaydayPoolReward = {
- tag: 'paydayPoolReward',
- poolOwner: 123n,
- finalizationReward: 123n,
- bakerReward: 12314n,
- transactionFees: 1231241n,
-};
-
-const accrueReward: BlockSpecialEventBlockAccrueReward = {
- tag: 'blockAccrueReward',
- transactionFees: 1231241n,
- bakerReward: 12314n,
- baker: 0n,
- foundationCharge: 12n,
- newGasAccount: 1n,
- oldGasAccount: 0n,
- passiveReward: 123n,
-};
-
-describe('specialEventAffectedAccounts', () => {
- test('Returns empty list of accounts for events with no account payouts', () => {
- let accounts = specialEventAffectedAccounts(paydayPoolReward);
- expect(accounts).toEqual([]);
-
- accounts = specialEventAffectedAccounts(accrueReward);
- expect(accounts).toEqual([]);
- });
-
- test('Returns correct list of accounts for events with account payouts', () => {
- let accounts = specialEventAffectedAccounts(bakingRewards);
- expect(accounts).toEqual([
- '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe',
- '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV',
- ]);
-
- accounts = specialEventAffectedAccounts(finalizationRewards);
- expect(accounts).toEqual([
- '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe',
- '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV',
- ]);
-
- accounts = specialEventAffectedAccounts(foundationReward);
- expect(accounts).toEqual([
- '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV',
- ]);
-
- accounts = specialEventAffectedAccounts(mint);
- expect(accounts).toEqual([
- '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV',
- ]);
-
- accounts = specialEventAffectedAccounts(paydayAccountReward);
- expect(accounts).toEqual([
- '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe',
- ]);
-
- accounts = specialEventAffectedAccounts(foundationBlockReward);
- expect(accounts).toEqual([
- '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV',
- ]);
-
- accounts = specialEventAffectedAccounts(blockReward);
- expect(accounts).toEqual([
- '4owvMHZSKsPW8QGYUEWSdgqxfoPBh3ZwPameBV46pSvmeHDkEe',
- '3v1JUB1R1JLFtcKvHqD9QFqe2NXeBF53tp69FLPHYipTjNgLrV',
- ]);
- });
-});
diff --git a/packages/common/test/util.test.ts b/packages/common/test/util.test.ts
deleted file mode 100644
index a87ed2286..000000000
--- a/packages/common/test/util.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { intToStringTransformer, stringToInt, wasmToSchema } from '../src/util';
-import { readFileSync } from 'fs';
-import { Buffer } from 'buffer/';
-
-test('intToStringTransformer transform chosen field, but not others', () => {
- const keysToTransform = ['a'];
- const input =
- '{ "a":90071992547409910, "b":90071992547409911, "aa":90071992547409912}';
- const transformed = intToStringTransformer(keysToTransform)(input);
- expect(transformed).toEqual(
- '{ "a":"90071992547409910", "b":90071992547409911, "aa":90071992547409912}'
- );
-});
-
-test('intToStringTransformer transforms multiple fields', () => {
- const keysToTransform = ['a', 'b'];
- const input =
- '{ "a":90071992547409910, "b":90071992547409911, "aa":{"a":12071992547409910,"c":1}}';
- const transformed = intToStringTransformer(keysToTransform)(input);
- expect(transformed).toEqual(
- '{ "a":"90071992547409910", "b":"90071992547409911", "aa":{"a":"12071992547409910","c":1}}'
- );
-});
-
-test('intToStringTransformer will not change the string if no keys match', () => {
- const keysToTransform = ['d', 'aaa'];
- const input =
- '{ "a":90071992547409910, "b":90071992547409911, "aa":{"a":12071992547409910,"c":1}}';
- const transformed = intToStringTransformer(keysToTransform)(input);
- expect(transformed).toEqual(input);
-});
-
-test('stringToInt transforms chosen field, but not others', () => {
- const keysToTransform = ['a'];
- const input =
- '{ "a":"90071992547409910", "b":"90071992547409911", "aa":"90071992547409912"}';
- const transformed = stringToInt(input, keysToTransform);
- expect(transformed).toEqual(
- '{ "a":90071992547409910, "b":"90071992547409911", "aa":"90071992547409912"}'
- );
-});
-
-test('stringToInt transforms multiple fields', () => {
- const keysToTransform = ['a', 'b'];
- const input =
- '{ "a":"90071992547409910", "b":"90071992547409911", "aa":{"a":"12071992547409910","c":"1"}}';
- const transformed = stringToInt(input, keysToTransform);
- expect(transformed).toEqual(
- '{ "a":90071992547409910, "b":90071992547409911, "aa":{"a":12071992547409910,"c":"1"}}'
- );
-});
-
-test('stringToInt will not change the string if no keys match', () => {
- const keysToTransform = ['d', 'aaa'];
- const input =
- '{ "a":"90071992547409910", "b":"90071992547409911", "aa":{"a":"12071992547409910","c":"1"}}';
- const transformed = stringToInt(input, keysToTransform);
- expect(transformed).toEqual(input);
-});
-
-test('stringToInt can inverse intToStringTransformer (with same chosen keys, and no matching number fields)', () => {
- const keysToTransform = ['a', 'b'];
- const input =
- '{ "a":90071992547409910, "b":90071992547409911, "aa":{"a":12071992547409910,"c":"1"}, "d": true}';
- const transformed = stringToInt(
- intToStringTransformer(keysToTransform)(input),
- keysToTransform
- );
- expect(transformed).toEqual(input);
-});
-
-test('intToStringTransformer is inverse of stringToInt (with same chosen keys, and no matching string fields)', () => {
- const keysToTransform = ['a', 'b'];
- const input =
- '{ "a":"90071992547409910", "b":"90071992547409911", "aa":{"a":"12071992547409910","c":"1"}, "d": true}';
- const transformed = intToStringTransformer(keysToTransform)(
- stringToInt(input, keysToTransform)
- );
- expect(transformed).toEqual(input);
-});
-
-test('Embedded schema is the same as a seperate schema file', () => {
- const versionedWasmModule = new Buffer(
- readFileSync('test/resources/icecream-with-schema.wasm')
- );
- // Strip module version information
- const wasmModule = versionedWasmModule.slice(8);
-
- const seperateSchema = new Buffer(
- readFileSync('test/resources/icecream-schema.bin')
- );
- const embeddedSchema = wasmToSchema(wasmModule);
-
- expect(seperateSchema).toEqual(embeddedSchema);
-});
diff --git a/packages/common/tsconfig.eslint.json b/packages/common/tsconfig.eslint.json
deleted file mode 100644
index d4da0a919..000000000
--- a/packages/common/tsconfig.eslint.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "include": ["src/**/*", "test/**/*", "types/**/*"]
-}
diff --git a/packages/common/tsconfig.json b/packages/common/tsconfig.json
deleted file mode 100644
index d560719fc..000000000
--- a/packages/common/tsconfig.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "extends": "../../tsconfig-base.json",
- "include": [
- "src/**/*",
- "types/**/*"
- ],
- "compilerOptions": {
- "rootDir": "./src",
- "outDir": "./lib"
- }
-}
diff --git a/packages/nodejs/CHANGELOG.md b/packages/nodejs/CHANGELOG.md
deleted file mode 100644
index c5b146845..000000000
--- a/packages/nodejs/CHANGELOG.md
+++ /dev/null
@@ -1,258 +0,0 @@
-# Changelog
-
-## 9.5.1
-
-- Bumped @concordium/common-sdk to 9.5.1.
-
-## 9.5.0
-
-- Bumped @concordium/common-sdk to 9.5.0.
-
-## 9.4.0
-
-- Bumped @concordium/common-sdk to 9.4.0.
-
-## 9.3.0
-
-- Bumped @concordium/common-sdk to 9.3.0.
-
-## 9.2.0
-
-- Bumped @concordium/common-sdk to 9.2.0.
-
-## 9.1.1
-
-### Changed
-
-- Bumped @concordium/common-sdk to 9.1.1. (includes fixes for `verifyWeb3IdCredentialSignature` and `canProveAtomicStatement`)
-
-## 9.1.0
-
-### Changed
-
-- Bumped @concordium/common-sdk to 9.1.0. (adds methods for creating verifiable presentation (proving statements about Web3Id Credentials))
-
-## 9.0.0
-
-### Breaking changes
-
-- Bumped @concordium/common-sdk to 9.0.0. (adds `displayTypeSchemaTemplate/getTransactionKindString` and renames `AccountTransactionType.TransferWithScheduleWithMemo`)
-
-## 8.0.0
-
-### Breaking changes
-
-- Bumped @concordium/common-sdk to 8.0.0:
- - Properly formed errors thrown by functions wrapping WASM execution (from @concordium/rust-bindings) with more helpful error messages.
- - Types adapted to changes in protocol version 6.
- - and [more](../common/CHANGELOG.md)
-
-## 7.0.0 2023-05-15
-
-### Breaking Changes
-
-- Bumped @concordium/common-sdk to 7.0.0:
- - Updated `blockInfo` so that the `bakerId` field is optional, since it will be undefined for genesis blocks.
- - `waitForTransactionFinalization` now returns a `BlockItemSummaryInBlock`
- - Added missing version return type in `getModuleSchema`. It now returns an object containing the schema source and version.
-
-## 6.4.0 2023-5-03
-
-### Changed
-
-- Bumped @concordium/common-sdk to 6.5.0. (Adds `CIS2Contract`)
-
-## 6.3.0 2023-3-22
-
-### Changed
-
-- Bumped @concordium/common-sdk to 6.4.0. (Adds `deserializeTypeValue`)
-
-## 6.2.0 2023-2-27
-
-### Added
-
-- Added a `createConcordiumClient` function to create the gRPC v2 client.
-
-### Changed
-
-- Bumped @concordium/common-sdk to 6.3.0. (Adds the gRPC v2 client)
-
-### Fixed
-
-- The value of amount fields in the GRPCv1 client's invokeContract's events has been changed to bigint (instead of string) as the type specifies.
-
-### Deprecated
-
-- The old gRPC client has been deprecated in favor of the new gRPC v2 client.
-
-## 6.1.0 2022-11-30
-
-### Changed
-
-- Bumped @concordium/common-sdk to 6.1.0. (adds support for id statements and proofs)
-
-## 6.0.0 2022-11-15
-
-### Breaking Changes
-
-- Bumped @concordium/common-sdk to 6.0.0. (Which changes transaction type names and field names to be aligned with other implementations)
-
-## 5.0.0 2022-11-8
-
-Breaking Changes
-
-- Bumped @concordium/common-sdk to 5.2.0. (Which changes the function signature of ConcordiumHdWallet and sign helpers functions)
-
-## 4.0.0 2022-8-26
-
-### Breaking Changes
-
-- Bumped @concordium/common-sdk to 3.0.0. (Which includes breaking changes to schema versioning)
-
-## 3.0.2 2022-7-26
-
-### Fixed
-
-- `deserializeTransaction` no longer throws an error on expired transactions.
-
-## 3.0.1 2022-7-26
-
-### Fixed
-
-- `deserializeTransaction` is now exported from index.
-
-## 3.0.0 - 2022-7-25
-
-### Added
-
-- `deserializeTransaction` function to deserialize transaction created by `serializeAccountTransactionForSubmission` and `serializeCredentialDeploymentTransactionForSubmission`. (Currently SimpleTransfer, SimpleTransferWithMemo and RegisterData are the only supported account transactions kinds)
-
-### Breaking changes
-
-- getInstanceInfo, getModuleSource and invokeContract's parameters have changed order. Now the blockHash is the 2nd parameter instead of the 1st.
-
-## 2.1.1 2022-7-8
-
-### Fixed
-
-- Fixed contract schema serialization for ByteList.
-
-## 2.1.0 2022-7-5
-
-### Added
-
-- Support deserializing new schema types: ULeb128, ILeb128, ByteArray and ByteList.
-- Support deserializing schemas with versioning information.
-
-### Changed
-
-- The function for deserializing a module schema `deserialModuleFromBuffer` now have the schema version as an optional argument. The function will try to extract the version from the buffer. When a version is provided it falls back to this, otherwise it throws an error.
-
-## 2.0.2 2022-6-27
-
-### Fixed
-
-- `getModuleBuffer` returns correct type of `Buffer`.
-
-## 2.0.1 2022-6-27
-
-### Added
-
-- `getModuleBuffer`, which is `getModuleFromBuffer` renamed (which was removed in 2.0.0).
-
-### Fixed
-
-- Error in build, which caused imports to fail.
-- Added missing dependency google-protobuf.
-- @noble/ed25519 and cross-fetch moved from devDependencies to dependencies. (In common-sdk)
-
-## 2.0.0 2022-6-24
-
-### Added
-
-- Using `@concordium/common-sdk` as a dependency, and most features have been removed from this package. (But are re-exported instead)
-- Support deserializing version 2 schemas.
-- Support serializing parameters for contracts using version 2 schemas.
-- Support for deploying versioned smart contract modules, which is the format used in cargo-concordium v2+. (This is done by not supplying the version field in the payload)
-
-### Breaking changes
-
-- `serializeInitContractParameters` and `serializeUpdateContractParameters` each have an additional parameter, which denotes the version of the schema provided. For existing users that are using V0 contracts, that parameter should be `SchemaVersion.V1`.
-- Deserialization of schemas have been changed: types and functions have been renamed and `deserialModuleFromBuffer` have an additional parameter, and now returns a versioned module schema.
-
-## 1.1.0 2022-06-14
-
-### Added
-
-- Support for the Invoke contract node entrypoint.
-
-### Fixed
-
-- Lossy parsing of uint64's from the node, if their value was above MAX_SAFE_INTEGER.
-
-## 1.0.0 2022-05-11
-
-### Added
-
-- Support for getting baker list from node.
-- Support for getting status of a Baker Pool/Passive delegation (required node to have protocol version 4 or later).
-- Support for getting reward status of chain at specific block.
-- Helper functions for determining the version of `BlockSummary` and nested types.
-- Helper functions for determining the version of `AccountInfo` variants.
-- Support for the new "configure delegation" transaction type.
-
-### Changed
-
-- Updated `BlockSummary` type to include new version, effective from protocol version 4.
-- Updated `AccountInfo` type to include new fields related to delegation introduced with protocol version 4.
-
-## 0.7.3 2022-05-05
-
-### Added
-
-- Export of serializeCredentialDeploymentTransactionForSubmission.
-
-### Fixed
-
-- Added missing dependency "google-protobuf"
-
-## 0.7.2 2022-05-05
-
-### Added
-
-- Export of serializeAccountTransactionForSubmission.
-
-## 0.7.1 2022-03-09
-
-### Added
-
-- Support for initiating and updating contracts with parameters.
-
-## 0.6.0 2022-02-02
-
-### Added
-
-- Function to deserialize contract state.
-- Support for register data transaction.
-
-## 0.5.1 2021-11-19
-
-### Added
-
-- Functions to generate account aliases, and check if addresses are aliases.
-
-## 0.4.0 2021-11-17
-
-### Added
-
-- Support for getting account info for a credential registration id.
-- Support for the update credentials account transaction.
-- Support for deploy module, initiate contract and update contract (without parameters).
-
-## 0.3.0 2021-10-28
-
-### Added
-
-- Support for the credential deployment transaction.
-- Helpers to decrypt mobile wallet exports, in particular to extract identity information from the export.
diff --git a/packages/nodejs/README.md b/packages/nodejs/README.md
deleted file mode 100644
index 903c9b681..000000000
--- a/packages/nodejs/README.md
+++ /dev/null
@@ -1,50 +0,0 @@
-# Concordium NodeJS SDK
-
-[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.0-4baaaa.svg)](https://github.com/Concordium/.github/blob/main/.github/CODE_OF_CONDUCT.md)
-
-Wrappers for interacting with the Concordium node, using nodejs.
-
-Please see the
-[documentation](https://developer.concordium.software/concordium-node-sdk-js/index.html)
-for more information
-
-## ConcordiumGRPCClient
-
-The SDK provides a gRPC client, which can interact with the [Concordium
-Node](https://github.com/Concordium/concordium-node)
-
-For an overview of the endpoints, [click
-here](https://developer.concordium.software/concordium-node-sdk-js/modules/Common_GRPC_Client.html).
-
-To create a client, the function `createConcordiumClient` can be used. It
-requires the address and port of the node. It also requires credentials to
-be specified. These can be used for create either an insecure connection or
-a TLS connection. In the following example the credentials are created for
-a TLS connection:
-
-```ts
-import { credentials } from '@grpc/grpc-js/';
-import { createConcordiumClient } from '@concordium/node-sdk';
-...
-return createConcordiumClient(
- address,
- port,
- credentials.createSsl(),
- { timeout: 15000 }
-);
-```
-
-The fourth argument is additional options. In the example
-above we sat the timeout for a call to the node to 15
-seconds. The options allowed here are those allowed by the
-[grpc-transport](https://www.npmjs.com/package/@protobuf-ts/grpc-transport).
-
-The connection to a node can be either an insecure connection or a TLS
-connection. Note that the node that you are trying to connect to must support
-TLS, for a TLS connection to work. Otherwise an insecure connection can be
-created by using `credentials.createInsecure()` instead.
-
-To see the documentation for the deprecated v1 client, [click
-here](https://developer.concordium.software/concordium-node-sdk-js/pages/misc-pages/grpc-v1.html).
-For an overview of how to migrate from the v1 client to the v2 client, [click
-here](https://developer.concordium.software/concordium-node-sdk-js/pages/misc-pages/grpc-migration.html).
diff --git a/packages/nodejs/jest.config.js b/packages/nodejs/jest.config.js
deleted file mode 100644
index efc8bc73b..000000000
--- a/packages/nodejs/jest.config.js
+++ /dev/null
@@ -1,11 +0,0 @@
-module.exports = {
- preset: 'ts-jest',
- testEnvironment: 'node',
- moduleFileExtensions: ['js', 'ts', 'json'],
- moduleDirectories: ['node_modules'],
- globals: {
- 'ts-jest': {
- tsconfig: 'tsconfig.jest.json',
- },
- },
-};
diff --git a/packages/nodejs/package.json b/packages/nodejs/package.json
deleted file mode 100644
index 9fc9972b0..000000000
--- a/packages/nodejs/package.json
+++ /dev/null
@@ -1,69 +0,0 @@
-{
- "name": "@concordium/node-sdk",
- "version": "9.5.1",
- "description": "Helpers for interacting with the Concordium node",
- "repository": {
- "type": "git",
- "url": "https://github.com/Concordium/concordium-node-sdk-js",
- "directory": "packages/nodejs"
- },
- "author": {
- "name": "Concordium Software",
- "email": "support@concordium.software",
- "url": "https://concordium.com"
- },
- "license": "Apache-2.0",
- "engines": {
- "node": ">=14.16.0"
- },
- "main": "lib/index.js",
- "types": "lib/index.d.ts",
- "files": [
- "/grpc/*",
- "/lib/**/*"
- ],
- "devDependencies": {
- "@noble/ed25519": "^1.7.1",
- "@protobuf-ts/grpcweb-transport": "^2.8.2",
- "@types/bs58check": "^2.1.0",
- "@types/google-protobuf": "^3.15.3",
- "@types/jest": "^26.0.23",
- "@typescript-eslint/eslint-plugin": "^4.28.1",
- "@typescript-eslint/parser": "^4.28.1",
- "babel-jest": "^27.0.6",
- "cross-env": "5.0.5",
- "eslint": "^7.29.0",
- "eslint-config-prettier": "^8.3.0",
- "eslint-plugin-import": "^2.23.4",
- "eslint-plugin-prettier": "^3.4.0",
- "grpc-tools": "^1.11.2",
- "grpc_tools_node_protoc_ts": "5.3.0",
- "isomorphic-fetch": "^3.0.0",
- "jest": "^27.0.6",
- "lint-staged": "^12.0.2",
- "prettier": "^2.3.2",
- "ts-jest": "^27.0.3",
- "typescript": "^4.3.5"
- },
- "prettier": {
- "singleQuote": true,
- "tabWidth": 4
- },
- "scripts": {
- "generate-js": "yarn run grpc_tools_node_protoc --js_out=import_style=commonjs,binary:grpc --grpc_out=grpc_js:grpc --plugin=protoc-gen-grpc=../../node_modules/.bin/grpc_tools_node_protoc_plugin -I ../../deps/concordium-base/concordium-grpc-api ../../deps/concordium-base/concordium-grpc-api/**/*.proto",
- "generate-ts": "yarn run grpc_tools_node_protoc --plugin=protoc-gen-ts=../../node_modules/grpc_tools_node_protoc_ts/bin/protoc-gen-ts --ts_out=grpc_js:grpc -I ../../deps/concordium-base/concordium-grpc-api ../../deps/concordium-base/concordium-grpc-api/concordium_p2p_rpc.proto",
- "generate": "([ -e \"../../deps/concordium-base/concordium-grpc-api\" ] && yarn generate-js && yarn generate-ts) || echo 'Please checkout submodules before building'",
- "lint": "eslint . --cache --ext .ts,.tsx --max-warnings 0",
- "lint-fix": "yarn --silent lint --fix; exit 0",
- "test": "jest",
- "build": "rm -rf grpc; mkdir -p grpc; yarn generate && tsc",
- "build-dev": "tsc"
- },
- "dependencies": {
- "@concordium/common-sdk": "9.5.1",
- "@grpc/grpc-js": "^1.3.4",
- "@protobuf-ts/grpc-transport": "^2.8.2",
- "buffer": "^6.0.3",
- "google-protobuf": "^3.20.1"
- }
-}
diff --git a/packages/nodejs/src/client.ts b/packages/nodejs/src/client.ts
deleted file mode 100644
index a814c5c5c..000000000
--- a/packages/nodejs/src/client.ts
+++ /dev/null
@@ -1,951 +0,0 @@
-import { ChannelCredentials, Metadata, ServiceError } from '@grpc/grpc-js';
-import { Buffer as BufferFormater } from 'buffer/';
-import { P2PClient } from '../grpc/concordium_p2p_rpc_grpc_pb';
-import {
- AccountAddress,
- BlockHash,
- BlockHeight,
- Empty,
- GetAddressInfoRequest,
- GetPoolStatusRequest,
- GetModuleSourceRequest,
- PeerListResponse,
- PeersRequest,
- SendTransactionRequest,
- TransactionHash,
- InvokeContractRequest,
-} from '../grpc/concordium_p2p_rpc_pb';
-import {
- serializeAccountTransactionForSubmission,
- serializeCredentialDeploymentTransactionForSubmission,
- AccountAddress as Address,
- CredentialRegistrationId,
- AccountBakerDetails,
- AccountEncryptedAmount,
- AccountInfo,
- AccountReleaseSchedule,
- AccountTransaction,
- AccountTransactionSignature,
- ArInfo,
- BlockInfo,
- BlockSummary,
- ConsensusStatus,
- ContractAddress,
- CredentialDeploymentTransaction,
- CryptographicParameters,
- ExchangeRate,
- FinalizationData,
- IpInfo,
- KeysWithThreshold,
- NextAccountNonce,
- PartyInfo,
- ReleaseSchedule,
- TransactionStatus,
- TransactionSummary,
- TransferredEvent,
- UpdateQueue,
- Versioned,
- InstanceInfo,
- InstanceInfoSerialized,
- BakerId,
- ChainParametersV0,
- ChainParametersV1,
- PoolStatus,
- BakerPoolStatusDetails,
- CurrentPaydayBakerPoolStatus,
- KeysMatching,
- BakerPoolPendingChangeReduceBakerCapitalDetails,
- BakerPoolStatus,
- RewardStatusV0,
- RewardStatus,
- RewardStatusV1,
- ReduceStakePendingChangeV0,
- PassiveDelegationStatus,
- PassiveDelegationStatusDetails,
- ContractContext,
- InvokeContractResultV1,
- CcdAmount,
- ModuleReference,
- ReduceStakePendingChangeV1,
- buildInvoker,
- DelegationStakeChangedEvent,
- CooldownParametersV1,
- TimeParametersV1,
- PoolParametersV1,
- BlockInfoV0,
- BlockInfoV1,
- ConsensusStatusV0,
- ConsensusStatusV1,
- ChainParametersV2,
- ConsensusParameters,
- TimeoutParameters,
- Ratio,
- ConcordiumBftStatus,
-} from '@concordium/common-sdk';
-import {
- buildJsonResponseReviver,
- intToStringTransformer,
- isValidHash,
- stringToInt,
-} from '@concordium/common-sdk/lib/util';
-import {
- intListToStringList,
- unwrapBoolResponse,
- unwrapJsonResponse,
-} from './util';
-
-/**
- * A concordium-node specific gRPC client wrapper.
- *
- * @example
- * import ConcordiumNodeClient from "..."
- * const client = new ConcordiumNodeClient('127.0.0.1', 10000, credentials, metadata, 15000);
- * @deprecated This has been succeeded by the new V2 client, check {@link createConcordiumClient}
- */
-export default class ConcordiumNodeClient {
- client: P2PClient;
-
- metadata: Metadata;
-
- address: string;
-
- port: number;
-
- timeout: number;
-
- /**
- * Initialize a gRPC client for a specific concordium node.
- * @param address the ip address of the node, e.g. 127.0.0.1
- * @param port the port to use when econnecting to the node
- * @param credentials credentials to use to connect to the node
- * @param timeout milliseconds to wait before timing out
- * @param options optional options for the P2PClient
- */
- constructor(
- address: string,
- port: number,
- credentials: ChannelCredentials,
- metadata: Metadata,
- timeout: number,
- options?: Record
- ) {
- if (timeout < 0 || !Number.isSafeInteger(timeout)) {
- throw new Error(
- 'The timeout must be a positive integer, but was: ' + timeout
- );
- }
-
- this.address = address;
- this.port = port;
- this.timeout = timeout;
- this.metadata = metadata;
- this.client = new P2PClient(`${address}:${port}`, credentials, options);
- }
-
- /**
- * Sends a credential deployment transaction, for creating a new account,
- * to the node to be put in a block on the chain.
- *
- * Note that a transaction can still fail even if it was accepted by the node.
- * To keep track of the transaction use getTransactionStatus.
- * @param credentialDeploymentTransaction the credential deployment transaction to send to the node
- * @param signatures the signatures on the hash of the serialized unsigned credential deployment information, in order
- * @returns true if the transaction was accepted, otherwise false
- */
- async sendCredentialDeploymentTransaction(
- credentialDeploymentTransaction: CredentialDeploymentTransaction,
- signatures: string[]
- ): Promise {
- const serializedCredentialDeploymentTransaction: Buffer = Buffer.from(
- serializeCredentialDeploymentTransactionForSubmission(
- credentialDeploymentTransaction,
- signatures
- )
- );
-
- const sendTransactionRequest = new SendTransactionRequest();
- sendTransactionRequest.setNetworkId(100);
- sendTransactionRequest.setPayload(
- serializedCredentialDeploymentTransaction
- );
-
- const response = await this.sendRequest(
- this.client.sendTransaction,
- sendTransactionRequest
- );
- return unwrapBoolResponse(response);
- }
-
- /**
- * Serializes and sends an account transaction to the node to be
- * put in a block on the chain.
- *
- * Note that a transaction can still fail even if it was accepted by the node.
- * To keep track of the transaction use getTransactionStatus.
- * @param accountTransaction the transaction to send to the node
- * @param signatures the signatures on the signing digest of the transaction
- * @returns true if the transaction was accepted, otherwise false
- */
- async sendAccountTransaction(
- accountTransaction: AccountTransaction,
- signatures: AccountTransactionSignature
- ): Promise {
- const serializedAccountTransaction: Buffer = Buffer.from(
- serializeAccountTransactionForSubmission(
- accountTransaction,
- signatures
- )
- );
-
- const sendTransactionRequest = new SendTransactionRequest();
- sendTransactionRequest.setNetworkId(100);
- sendTransactionRequest.setPayload(serializedAccountTransaction);
-
- const response = await this.sendRequest(
- this.client.sendTransaction,
- sendTransactionRequest
- );
- return unwrapBoolResponse(response);
- }
-
- /**
- * Retrieves the account info for the given account. If the provided block
- * hash is in a block prior to the finalization of the account, then the account
- * information will not be available.
- * A credential registration id can also be provided, instead of an address. In this case
- * the node will return the account info of the account, which the corresponding credential
- * is (or was) deployed to.
- * @param accountAddress base58 account address (or a credential registration id) to get the account info for
- * @param blockHash the block hash to get the account info at
- * @returns the account info for the provided account address, undefined is the account does not exist
- */
- async getAccountInfo(
- accountAddress: string | Address | CredentialRegistrationId,
- blockHash: string
- ): Promise {
- if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
-
- const getAddressInfoRequest = new GetAddressInfoRequest();
-
- if (typeof accountAddress === 'string') {
- getAddressInfoRequest.setAddress(accountAddress);
- } else if ('address' in accountAddress) {
- getAddressInfoRequest.setAddress(accountAddress.address);
- } else if ('credId' in accountAddress) {
- getAddressInfoRequest.setAddress(accountAddress.credId);
- } else {
- throw new Error('Invalid accountAddress input');
- }
-
- getAddressInfoRequest.setBlockHash(blockHash);
-
- const response = await this.sendRequest(
- this.client.getAccountInfo,
- getAddressInfoRequest
- );
- const datePropertyKeys: (
- | keyof ReleaseSchedule
- | keyof ReduceStakePendingChangeV1
- )[] = ['timestamp', 'effectiveTime'];
- const bigIntPropertyKeys: (
- | keyof AccountInfo
- | keyof AccountEncryptedAmount
- | keyof AccountReleaseSchedule
- | keyof ReleaseSchedule
- | keyof AccountBakerDetails
- | keyof ReduceStakePendingChangeV0
- )[] = [
- 'accountAmount',
- 'accountNonce',
- 'accountIndex',
- 'startIndex',
- 'total',
- 'amount',
- 'stakedAmount',
- 'bakerId',
- 'newStake',
- 'epoch',
- ];
- return unwrapJsonResponse(
- response,
- buildJsonResponseReviver(datePropertyKeys, bigIntPropertyKeys),
- intToStringTransformer(bigIntPropertyKeys)
- );
- }
-
- /**
- * Retrieves the next account nonce for the given account. The account nonce is
- * used in all account transactions as part of their header.
- * @param accountAddress base58 account address to get the next account nonce for
- * @returns the next account nonce, and a boolean indicating if the nonce is reliable
- */
- async getNextAccountNonce(
- accountAddress: Address
- ): Promise {
- const accountAddressObject = new AccountAddress();
- accountAddressObject.setAccountAddress(accountAddress.address);
-
- const response = await this.sendRequest(
- this.client.getNextAccountNonce,
- accountAddressObject
- );
-
- const bigIntPropertyKeys: (keyof NextAccountNonce)[] = ['nonce'];
-
- return unwrapJsonResponse(
- response,
- buildJsonResponseReviver([], bigIntPropertyKeys),
- intToStringTransformer(bigIntPropertyKeys)
- );
- }
-
- /**
- * Retrieves a status for the given transaction.
- * @param transactionHash the transaction to get a status for
- * @returns the transaction status for the given transaction, or undefined if the transaction does not exist
- */
- async getTransactionStatus(
- transactionHash: string
- ): Promise {
- if (!isValidHash(transactionHash)) {
- throw new Error(
- 'The input was not a valid hash: ' + transactionHash
- );
- }
-
- const bigIntPropertyKeys: (keyof TransactionSummary)[] = [
- 'cost',
- 'energyCost',
- 'index',
- ];
-
- const transactionHashObject = new TransactionHash();
- transactionHashObject.setTransactionHash(transactionHash);
- const response = await this.sendRequest(
- this.client.getTransactionStatus,
- transactionHashObject
- );
- return unwrapJsonResponse(
- response,
- buildJsonResponseReviver([], bigIntPropertyKeys),
- intToStringTransformer(bigIntPropertyKeys)
- );
- }
-
- /**
- * Retrieves the block summary for a specific block. This contains information
- * about finalization, update sequence numbers (their nonce), update queues,
- * updateable chain parameters and transaction summaries for any transaction
- * in the block.
- * @param blockHash the block to get the summary for
- * @returns the block summary for the given block, or undefined if the block does not exist
- */
- async getBlockSummary(
- blockHash: string
- ): Promise {
- if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
-
- const blockHashObject = new BlockHash();
- blockHashObject.setBlockHash(blockHash);
-
- const response = await this.sendRequest(
- this.client.getBlockSummary,
- blockHashObject
- );
-
- const bigIntPropertyKeys: (
- | keyof PartyInfo
- | keyof FinalizationData
- | keyof TransactionSummary
- | keyof (ChainParametersV0 & ChainParametersV1 & ChainParametersV2)
- | keyof BlockSummary
- | keyof PoolParametersV1
- | keyof CooldownParametersV1
- | keyof TimeParametersV1
- | keyof ExchangeRate
- | keyof UpdateQueue
- | keyof KeysWithThreshold
- | keyof TransferredEvent
- | keyof ContractAddress
- | keyof DelegationStakeChangedEvent
- | keyof ConsensusParameters
- | keyof TimeoutParameters
- | keyof Ratio
- )[] = [
- 'bakerId',
- 'newStake',
- 'weight',
- 'finalizationIndex',
- 'finalizationDelay',
- 'cost',
- 'energyCost',
- 'index',
- 'numerator',
- 'denominator',
- 'nextSequenceNumber',
- 'amount',
- 'index',
- 'subindex',
- 'protocolVersion',
- 'foundationAccountIndex',
-
- // v0 keys
- 'bakerCooldownEpochs',
- 'minimumThresholdForBaking',
-
- // v1 keys
- 'rewardPeriodLength',
- 'minimumEquityCapital',
- 'poolOwnerCooldown',
- 'delegatorCooldown',
-
- // v2 keys
- 'timeoutBase',
- 'denominator',
- 'numerator',
- 'minBlockTime',
- 'blockEnergyLimit',
- ];
-
- return unwrapJsonResponse(
- response,
- buildJsonResponseReviver([], bigIntPropertyKeys)
- );
- }
-
- /**
- * Retrieves information about a specific block.
- * @param blockHash the block to get information about
- * @returns the block information for the given block, or undefined if the block does not exist
- */
- async getBlockInfo(blockHash: string): Promise {
- if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
-
- const blockHashObject = new BlockHash();
- blockHashObject.setBlockHash(blockHash);
- const response = await this.sendRequest(
- this.client.getBlockInfo,
- blockHashObject
- );
-
- const datePropertyKeys: (keyof BlockInfo)[] = [
- 'blockArriveTime',
- 'blockReceiveTime',
- 'blockSlotTime',
- ];
- const bigIntPropertyKeys: (keyof (BlockInfoV0 & BlockInfoV1))[] = [
- 'blockHeight',
- 'blockBaker',
- 'blockSlot',
- 'transactionEnergyCost',
- 'transactionCount',
- 'transactionsSize',
- ];
-
- return unwrapJsonResponse(
- response,
- buildJsonResponseReviver(datePropertyKeys, bigIntPropertyKeys),
- intToStringTransformer(bigIntPropertyKeys)
- );
- }
-
- /**
- * Retrieves the blocks are the given height.
- * @param height the block height as a positive integer
- * @returns a string array containing the blocks at the given height, i.e. ['blockHash1', 'blockHash2', ...]
- */
- async getBlocksAtHeight(height: bigint): Promise {
- if (height <= 0n) {
- throw new Error(
- 'The block height has to be a positive integer, but it was: ' +
- height
- );
- }
- const blockHeight = new BlockHeight();
- blockHeight.setBlockHeight(height.toString());
- const response = await this.sendRequest(
- this.client.getBlocksAtHeight,
- blockHeight
- );
-
- const blocksAtHeight = unwrapJsonResponse(response);
- if (!blocksAtHeight) {
- return [];
- }
- return blocksAtHeight;
- }
-
- /**
- * Retrieves the consensus status information from the node. Note that the optional
- * fields will only be unavailable for a newly started node that has not processed
- * enough data yet.
- */
- async getConsensusStatus(): Promise {
- type CS = ConsensusStatusV0 & ConsensusStatusV1;
- const response = await this.sendRequest(
- this.client.getConsensusStatus,
- new Empty()
- );
-
- const datePropertyKeys: (keyof CS | keyof ConcordiumBftStatus)[] = [
- 'blockLastReceivedTime',
- 'blockLastArrivedTime',
- 'genesisTime',
- 'currentEraGenesisTime',
- 'lastFinalizedTime',
-
- //v1
- 'triggerBlockTime',
- ];
- const bigIntPropertyKeys: (keyof CS | keyof ConcordiumBftStatus)[] = [
- 'epochDuration',
- 'slotDuration',
- 'bestBlockHeight',
- 'lastFinalizedBlockHeight',
- 'finalizationCount',
- 'blocksVerifiedCount',
- 'blocksReceivedCount',
- 'protocolVersion',
-
- // v1
- 'currentTimeoutDuration',
- 'currentRound',
- 'currentEpoch',
- ];
-
- const consensusStatus = unwrapJsonResponse(
- response,
- buildJsonResponseReviver(datePropertyKeys, bigIntPropertyKeys),
- intToStringTransformer(bigIntPropertyKeys)
- );
-
- if (!consensusStatus) {
- throw new Error(
- 'Nothing was returned when trying to get the consensus status.'
- );
- }
-
- return consensusStatus;
- }
-
- /**
- * Retrieves the global cryptographic parameters on the blockchain at
- * the provided block.
- * @param blockHash the block to get the cryptographic parameters at
- * @returns the global cryptographic parameters at the given block, or undefined it the block does not exist.
- */
- async getCryptographicParameters(
- blockHash: string
- ): Promise | undefined> {
- if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
-
- const blockHashObject = new BlockHash();
- blockHashObject.setBlockHash(blockHash);
- const response = await this.sendRequest(
- this.client.getCryptographicParameters,
- blockHashObject
- );
-
- return unwrapJsonResponse<
- Versioned | undefined
- >(response);
- }
-
- /**
- * Retrieves a list of the node's peers and connection information related to them.
- * @param includeBootstrappers whether or not any bootstrapper nodes should be included in the list
- * @returns a list of the node's peers and connection information related to them
- */
- async getPeerList(
- includeBootstrappers: boolean
- ): Promise {
- const peersRequest = new PeersRequest();
- peersRequest.setIncludeBootstrappers(includeBootstrappers);
- const response = await this.sendRequest(
- this.client.peerList,
- peersRequest
- );
- return PeerListResponse.deserializeBinary(response);
- }
-
- /**
- * Retrieves the list of identity providers at the provided blockhash.
- * @param blockHash the block to get the identity providers at
- * @returns the list of identity providers at the given block
- */
- async getIdentityProviders(
- blockHash: string
- ): Promise {
- const blockHashObject = new BlockHash();
- blockHashObject.setBlockHash(blockHash);
- const response = await this.sendRequest(
- this.client.getIdentityProviders,
- blockHashObject
- );
- return unwrapJsonResponse(response);
- }
-
- /**
- * Retrieves the list of anonymity revokers at the provided blockhash.
- * @param blockHash the block to get the anonymity revokers at
- * @returns the list of anonymity revokers at the given block
- */
- async getAnonymityRevokers(
- blockHash: string
- ): Promise {
- const blockHashObject = new BlockHash();
- blockHashObject.setBlockHash(blockHash);
- const response = await this.sendRequest(
- this.client.getAnonymityRevokers,
- blockHashObject
- );
- return unwrapJsonResponse(response);
- }
-
- /**
- * Retrieves the addresses of all smart contract instances.
- * @param blockHash the block hash to get the smart contact instances at
- * @returns a list of contract addresses on the chain, i.e. [{"subindex":0,"index":0},{"subindex":0,"index":1}, ....]
- */
- async getInstances(
- blockHash: string
- ): Promise {
- if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
- const blockHashObject = new BlockHash();
- blockHashObject.setBlockHash(blockHash);
-
- const response = await this.sendRequest(
- this.client.getInstances,
- blockHashObject
- );
- const bigIntPropertyKeys: (keyof ContractAddress)[] = [
- 'index',
- 'subindex',
- ];
-
- return unwrapJsonResponse(
- response,
- buildJsonResponseReviver([], bigIntPropertyKeys),
- intToStringTransformer(bigIntPropertyKeys)
- );
- }
-
- /**
- * Retrieve information about a given smart contract instance.
- * @param blockHash the block hash to get the smart contact instances at
- * @param address the address of the smart contract
- * @returns A JSON object with information about the contract instance
- */
- async getInstanceInfo(
- address: ContractAddress,
- blockHash: string
- ): Promise {
- if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
- const getAddressInfoRequest = new GetAddressInfoRequest();
- getAddressInfoRequest.setAddress(
- `{"subindex":${address.subindex},"index":${address.index}}`
- );
- getAddressInfoRequest.setBlockHash(blockHash);
-
- const response = await this.sendRequest(
- this.client.getInstanceInfo,
- getAddressInfoRequest
- );
-
- const result = unwrapJsonResponse(response);
- if (result !== undefined) {
- const common = {
- amount: new CcdAmount(BigInt(result.amount)),
- sourceModule: new ModuleReference(result.sourceModule),
- owner: new Address(result.owner),
- methods: result.methods,
- name: result.name,
- };
-
- switch (result.version) {
- case 1:
- return {
- version: 1,
- ...common,
- };
- case undefined:
- case 0:
- return {
- version: 0,
- ...common,
- model: BufferFormater.from(result.model, 'hex'),
- };
- default:
- throw new Error(
- 'InstanceInfo had unsupported version: ' +
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (result as any).version
- );
- }
- }
- }
-
- async getRewardStatus(
- blockHash: string
- ): Promise {
- if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
-
- type DateKey = KeysMatching;
- type BigIntKey = KeysMatching;
-
- const dates: DateKey[] = ['nextPaydayTime'];
- const bigInts: BigIntKey[] = [
- 'protocolVersion',
- 'gasAccount',
- 'totalAmount',
- 'totalStakedCapital',
- 'bakingRewardAccount',
- 'totalEncryptedAmount',
- 'finalizationRewardAccount',
- 'foundationTransactionRewards',
- ];
-
- const bh = new BlockHash();
- bh.setBlockHash(blockHash);
-
- const response = await this.sendRequest(
- this.client.getRewardStatus,
- bh
- );
-
- return unwrapJsonResponse(
- response,
- buildJsonResponseReviver(dates, bigInts),
- intToStringTransformer(bigInts)
- );
- }
-
- /**
- * Retrieve list of bakers on the network.
- * @param blockHash the block hash to get the smart contact instances at
- * @returns A JSON list of baker IDs
- */
- async getBakerList(blockHash: string): Promise {
- if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
-
- const bh = new BlockHash();
- bh.setBlockHash(blockHash);
-
- const response = await this.sendRequest(this.client.getBakerList, bh);
-
- return unwrapJsonResponse(
- response,
- undefined,
- intListToStringList
- )?.map((v) => BigInt(v));
- }
-
- /**
- * Gets the status of passive delegation.
- * @param blockHash the block hash the status at
- * @returns The status of passive delegation.
- */
- async getPoolStatus(
- blockHash: string
- ): Promise;
- /**
- * Gets the status a baker.
- * @param blockHash the block hash the status at
- * @param bakerId the ID of the baker to get the status for.
- * @returns The status of the corresponding baker pool.
- */
- async getPoolStatus(
- blockHash: string,
- bakerId: BakerId
- ): Promise;
- /**
- * Gets the status of either a baker, if a baker ID is supplied, or passive delegation if left undefined.
- * @param blockHash the block hash the status at
- * @param [bakerId] the ID of the baker to get the status for. If left undefined, the status of passive delegation is returned.
- * @returns The status of the corresponding pool.
- */
- async getPoolStatus(
- blockHash: string,
- bakerId?: BakerId
- ): Promise;
- async getPoolStatus(
- blockHash: string,
- bakerId?: BakerId
- ): Promise {
- if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
-
- const req = new GetPoolStatusRequest();
- req.setBlockHash(blockHash);
- req.setPassiveDelegation(bakerId === undefined);
-
- if (bakerId !== undefined) {
- req.setBakerId(bakerId.toString());
- }
-
- type DateKey = KeysMatching<
- BakerPoolPendingChangeReduceBakerCapitalDetails,
- Date
- >;
- type BigIntKey = KeysMatching<
- BakerPoolStatusDetails &
- PassiveDelegationStatusDetails &
- CurrentPaydayBakerPoolStatus,
- bigint
- >;
-
- const dates: DateKey[] = ['effectiveTime'];
- const bigInts: BigIntKey[] = [
- 'bakerId',
- 'bakerEquityCapital',
- 'delegatedCapital',
- 'delegatedCapitalCap',
- 'currentPaydayTransactionFeesEarned',
- 'currentPaydayDelegatedCapital',
- 'blocksBaked',
- 'transactionFeesEarned',
- 'effectiveStake',
- 'allPoolTotalCapital',
- ];
-
- const response = await this.sendRequest(this.client.getPoolStatus, req);
-
- return unwrapJsonResponse(
- response,
- buildJsonResponseReviver(dates, bigInts),
- intToStringTransformer(bigInts)
- );
- }
-
- /**
- * Retrieves the source of the given module at
- * the provided block.
- * @param moduleReference the module's reference, which is the hex encoded hash of the source.
- * @param blockHash the block to get the cryptographic parameters at
- * @returns the source of the module as raw bytes.
- */
- async getModuleSource(
- moduleReference: ModuleReference,
- blockHash: string
- ): Promise {
- if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
- const requestObject = new GetModuleSourceRequest();
- requestObject.setBlockHash(blockHash);
- requestObject.setModuleRef(moduleReference.moduleRef);
-
- const response = await this.sendRequest(
- this.client.getModuleSource,
- requestObject
- );
-
- if (response.length === 0) {
- return undefined;
- }
- return Buffer.from(response);
- }
-
- /**
- * Invokes a smart contract.
- * @param context the collection of details used to invoke the contract. Must include the address of the contract and the method invoked.
- * @param blockHash the block hash at which the contract should be invoked at. The contract is invoked in the state at the end of this block.
- * @returns If the node was able to invoke, then a object describing the outcome is returned.
- * The outcome is determined by the `tag` field, which is either `success` or `failure`.
- * The `usedEnergy` field will always be present, and is the amount of NRG was used during the execution.
- * If the tag is `success`, then an `events` field is present, and it contains the events that would have been generated.
- * If invoking a V1 contract and it produces a return value, it will be present in the `returnValue` field.
- * If the tag is `failure`, then a `reason` field is present, and it contains the reason the update would have been rejected.
- * If either the block does not exist, or then node fails to parse of any of the inputs, then undefined is returned.
- */
- async invokeContract(
- contractContext: ContractContext,
- blockHash: string
- ): Promise {
- if (!isValidHash(blockHash)) {
- throw new Error('The input was not a valid hash: ' + blockHash);
- }
-
- const requestObject = new InvokeContractRequest();
- requestObject.setBlockHash(blockHash);
- requestObject.setContext(
- stringToInt(
- JSON.stringify({
- invoker: buildInvoker(contractContext.invoker),
- contract: {
- subindex: contractContext.contract.subindex.toString(),
- index: contractContext.contract.index.toString(),
- },
- amount:
- contractContext.amount &&
- contractContext.amount.microCcdAmount.toString(),
- method: contractContext.method,
- parameter:
- contractContext.parameter &&
- contractContext.parameter.toString('hex'),
- energy:
- contractContext.energy &&
- Number(contractContext.energy.toString()),
- }),
- ['index', 'subindex']
- )
- );
-
- const response = await this.sendRequest(
- this.client.invokeContract,
- requestObject
- );
- const bigIntPropertyKeys = [
- 'usedEnergy',
- 'index',
- 'subindex',
- 'amount',
- ];
- return unwrapJsonResponse(
- response,
- buildJsonResponseReviver([], bigIntPropertyKeys),
- intToStringTransformer(bigIntPropertyKeys)
- );
- }
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
- sendRequest(command: any, input: T): Promise {
- const deadline = new Date(Date.now() + this.timeout);
- return new Promise((resolve, reject) => {
- this.client.waitForReady(deadline, (error) => {
- if (error) {
- return reject(error);
- }
-
- return command.bind(this.client)(
- input,
- this.metadata,
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (err: ServiceError | null, response: any) => {
- if (err) {
- return reject(err);
- }
- return resolve(response.serializeBinary());
- }
- );
- });
- });
- }
-}
diff --git a/packages/nodejs/src/clientV2.ts b/packages/nodejs/src/clientV2.ts
deleted file mode 100644
index cb2ac0303..000000000
--- a/packages/nodejs/src/clientV2.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { ChannelCredentials } from '@grpc/grpc-js';
-import { GrpcOptions, GrpcTransport } from '@protobuf-ts/grpc-transport';
-import { ConcordiumGRPCClient } from '@concordium/common-sdk/lib/GRPCClient';
-
-/**
- * Initialize a gRPC client for a specific concordium node.
- * @param address the ip address of the node, e.g. http://127.0.0.1
- * @param port the port to use when econnecting to the node
- * @param credentials channel credentials for communicating with the node
- * @param options optional options for the grpc transport
- */
-export function createConcordiumClient(
- address: string,
- port: number,
- credentials: ChannelCredentials,
- options?: Partial
-): ConcordiumGRPCClient {
- const grpcTransport = new GrpcTransport({
- host: `${address}:${port}`,
- channelCredentials: credentials,
- ...options,
- });
- return new ConcordiumGRPCClient(grpcTransport);
-}
diff --git a/packages/nodejs/src/index.ts b/packages/nodejs/src/index.ts
deleted file mode 100644
index a7f69149c..000000000
--- a/packages/nodejs/src/index.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- * A concordium-node specific gRPC client wrapper.
- *
- * @module NodeJS-SDK
- *
- */
-
-import ConcordiumNodeClient from './client';
-export * from './clientV2';
-
-export { ConcordiumNodeClient };
-export { decryptMobileWalletExport, EncryptedData } from './wallet/crypto';
-export { MobileWalletExport } from './wallet/types';
-export * from '@concordium/common-sdk';
-export { getModuleBuffer } from './util';
diff --git a/packages/nodejs/src/util.ts b/packages/nodejs/src/util.ts
deleted file mode 100644
index 562471977..000000000
--- a/packages/nodejs/src/util.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import * as fs from 'fs';
-import { Buffer } from 'buffer/';
-import { BoolResponse, JsonResponse } from '../grpc/concordium_p2p_rpc_pb';
-
-/**
- * @deprecated This is a helper function for the v1 gRPC client, which has been deprecated
- */
-export function intListToStringList(jsonStruct: string): string {
- return jsonStruct.replace(/(\-?[0-9]+)/g, '"$1"');
-}
-
-/**
- * Unwraps a serialized bool response to the corresponding boolean.
- * @deprecated This is a helper function for the v1 gRPC client, which has been deprecated
- */
-export function unwrapBoolResponse(serializedResponse: Uint8Array): boolean {
- return BoolResponse.deserializeBinary(serializedResponse).getValue();
-}
-
-/**
- * Unwraps a serialized JSON response.
- * @param serializedResponse the JSON response in bytes as received from the gRPC call
- * @param reviver JSON reviver function to change types while parsing
- * @param transformer a function to transform the JSON string prior to parsing the JSON
- * @returns the unwrapped, transformed and parsed JSON object
- * @deprecated This is a helper function for the v1 gRPC client, which has been deprecated
- */
-export function unwrapJsonResponse(
- serializedResponse: Uint8Array,
- reviver?: (this: unknown, key: string, value: unknown) => unknown,
- transformer?: (json: string) => string
-): T | undefined {
- const jsonString =
- JsonResponse.deserializeBinary(serializedResponse).getValue();
-
- if (jsonString === 'null') {
- return undefined;
- }
-
- if (transformer) {
- const transformedJson = transformer(jsonString);
- return JSON.parse(transformedJson, reviver);
- }
-
- return JSON.parse(jsonString, reviver);
-}
-
-/**
- * Loads the module as a buffer, given the given filePath.
- * @param filePath the location of the module
- * @returns the module as a buffer
- */
-export function getModuleBuffer(filePath: string): Buffer {
- return Buffer.from(fs.readFileSync(filePath));
-}
diff --git a/packages/nodejs/test/client.test.ts b/packages/nodejs/test/client.test.ts
deleted file mode 100644
index 81653e540..000000000
--- a/packages/nodejs/test/client.test.ts
+++ /dev/null
@@ -1,280 +0,0 @@
-import {
- isBlockSummaryV0,
- isBlockSummaryV1,
- isBlockSummaryV2,
- isConsensusStatusV0,
- isConsensusStatusV1,
-} from '@concordium/common-sdk';
-import { getNodeClient } from './testHelpers';
-
-/**
- * These tests mostly serve the purpose of making sure that the types exposed follow the format returned by the API,
- * i.e. we don't change the types to conform to the v2 API, but rather translate the v2 types to the v1 types until we can
- * remove the v1 API entirely.
- */
-
-const client = getNodeClient();
-
-// eslint-disable-next-line prefer-const
-let CHAIN_GENESIS_BLOCK: string | undefined = undefined;
-// eslint-disable-next-line prefer-const
-let PV5_BLOCK: string | undefined = undefined;
-// eslint-disable-next-line prefer-const
-let PV6_BLOCK: string | undefined = undefined;
-
-// Testnet blocks.
-CHAIN_GENESIS_BLOCK =
- '4221332d34e1694168c2a0c0b3fd0f273809612cb13d000d5c2e00e85f50f796';
-PV5_BLOCK = '58daebb41ca195442593e10c1a67279bb839a8195c8ea7442ea7116d87114fbb';
-
-test.each([CHAIN_GENESIS_BLOCK, PV5_BLOCK, PV6_BLOCK])(
- 'blockSummary format as expected',
- async (block) => {
- if (block === undefined) {
- return;
- }
-
- const bs = await client.getBlockSummary(block);
-
- if (!bs) {
- throw new Error('could not find block');
- }
-
- // BlockSummary
- expect(typeof bs.protocolVersion).toEqual('bigint');
-
- // UpdateQueues
- expect(
- typeof bs.updates.updateQueues.foundationAccount.nextSequenceNumber
- ).toEqual('bigint');
- expect(
- Array.isArray(bs.updates.updateQueues.foundationAccount.queue)
- ).toBeTruthy();
- expect(
- typeof bs.updates.updateQueues.euroPerEnergy.nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.mintDistribution.nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.microGTUPerEuro.nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.protocol.nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.rootKeys.nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.gasRewards.nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.level1Keys.nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.level2Keys.nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.addAnonymityRevoker
- .nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.addIdentityProvider
- .nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.transactionFeeDistribution
- .nextSequenceNumber
- ).toEqual('bigint');
-
- // Keys
- expect(bs.updates.keys.rootKeys.keys).toBeDefined();
- expect(bs.updates.keys.rootKeys.threshold).toBeDefined();
- expect(bs.updates.keys.level1Keys.keys).toBeDefined();
- expect(bs.updates.keys.level2Keys.keys).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.addAnonymityRevoker.authorizedKeys
- ).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.poolParameters.authorizedKeys
- ).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.transactionFeeDistribution.authorizedKeys
- ).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.addIdentityProvider.authorizedKeys
- ).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.protocol.authorizedKeys
- ).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.microGTUPerEuro.authorizedKeys
- ).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.mintDistribution.authorizedKeys
- ).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.euroPerEnergy.authorizedKeys
- ).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.foundationAccount.authorizedKeys
- ).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.electionDifficulty.authorizedKeys
- ).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.emergency.authorizedKeys
- ).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.paramGASRewards.authorizedKeys
- ).toBeDefined();
-
- // Test format of chain parameters holds
- expect(
- typeof bs.updates.chainParameters.microGTUPerEuro.numerator
- ).toEqual('bigint');
- expect(
- typeof bs.updates.chainParameters.microGTUPerEuro.denominator
- ).toEqual('bigint');
- expect(
- bs.updates.chainParameters.rewardParameters.gASRewards.baker
- ).toBeDefined();
- expect(
- bs.updates.chainParameters.rewardParameters.gASRewards.chainUpdate
- ).toBeDefined();
- expect(
- bs.updates.chainParameters.rewardParameters.gASRewards
- .accountCreation
- ).toBeDefined();
- expect(
- bs.updates.chainParameters.rewardParameters.mintDistribution
- .bakingReward
- ).toBeDefined();
- expect(
- bs.updates.chainParameters.rewardParameters.mintDistribution
- .finalizationReward
- ).toBeDefined();
- expect(bs.updates.chainParameters.euroPerEnergy).toBeDefined();
- expect(bs.updates.chainParameters.foundationAccountIndex).toBeDefined();
- expect(bs.updates.chainParameters.accountCreationLimit).toBeDefined();
-
- if (isBlockSummaryV0(bs)) {
- expect(
- typeof bs.updates.updateQueues.electionDifficulty
- .nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.bakerStakeThreshold
- .nextSequenceNumber
- ).toEqual('bigint');
-
- expect(
- typeof bs.updates.chainParameters.bakerCooldownEpochs
- ).toEqual('bigint');
- } else if (isBlockSummaryV1(bs)) {
- expect(
- typeof bs.updates.updateQueues.electionDifficulty
- .nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.poolParameters.nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.timeParameters.nextSequenceNumber
- ).toEqual('bigint');
- expect(
- typeof bs.updates.updateQueues.cooldownParameters
- .nextSequenceNumber
- ).toEqual('bigint');
-
- expect(
- bs.updates.keys.level2Keys.cooldownParameters.authorizedKeys
- ).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.timeParameters.authorizedKeys
- ).toBeDefined();
-
- expect(bs.updates.chainParameters.electionDifficulty).toBeDefined();
- expect(
- bs.updates.chainParameters.rewardParameters.gASRewards
- .finalizationProof
- );
- expect(bs.updates.chainParameters.mintPerPayday).toBeDefined();
- expect(bs.updates.chainParameters.capitalBound).toBeDefined();
- expect(bs.updates.chainParameters.leverageBound).toBeDefined();
- expect(
- bs.updates.chainParameters.finalizationCommissionRange.min
- ).toBeDefined();
- } else if (isBlockSummaryV2(bs)) {
- expect(
- typeof bs.updates.updateQueues.consensus2TimingParameters
- .nextSequenceNumber
- ).toEqual('bigint');
-
- expect(
- bs.updates.keys.level2Keys.cooldownParameters.authorizedKeys
- ).toBeDefined();
- expect(
- bs.updates.keys.level2Keys.timeParameters.authorizedKeys
- ).toBeDefined();
-
- expect(bs.updates.chainParameters.minimumFinalizers).toBeDefined();
- expect(bs.updates.chainParameters.maximumFinalizers).toBeDefined();
- expect(typeof bs.updates.chainParameters.blockEnergyLimit).toEqual(
- 'bigint'
- );
- expect(typeof bs.updates.chainParameters.minBlockTime).toEqual(
- 'bigint'
- );
- expect(typeof bs.updates.chainParameters.timeoutBase).toEqual(
- 'bigint'
- );
- expect(
- typeof bs.updates.chainParameters.timeoutDecrease.numerator
- ).toEqual('bigint');
- expect(
- typeof bs.updates.chainParameters.timeoutIncrease.denominator
- ).toEqual('bigint');
- expect(
- bs.updates.chainParameters.finalizerRelativeStakeThreshold
- ).toBeDefined();
- }
- }
-);
-
-test('consensusStatus format as expected', async () => {
- const cs = await client.getConsensusStatus();
-
- expect(typeof cs.protocolVersion).toEqual('bigint');
- expect(cs.bestBlock).toBeDefined();
- expect(cs.genesisTime instanceof Date).toBeTruthy();
- expect(cs.genesisBlock).toBeDefined();
- expect(cs.genesisIndex).toBeDefined();
- expect(typeof cs.epochDuration).toEqual('bigint');
- expect(typeof cs.bestBlockHeight).toEqual('bigint');
- expect(typeof cs.finalizationCount).toEqual('bigint');
- expect(cs.lastFinalizedBlock).toBeDefined();
- expect(typeof cs.blocksReceivedCount).toEqual('bigint');
- expect(typeof cs.blocksVerifiedCount).toEqual('bigint');
- expect(cs.blockArriveLatencyEMA).toBeDefined();
- expect(cs.blockLastArrivedTime instanceof Date).toBeTruthy();
- expect(cs.currentEraGenesisTime instanceof Date).toBeTruthy();
- expect(cs.blockArriveLatencyEMSD).toBeDefined();
- expect(cs.currentEraGenesisBlock).toBeDefined();
- expect(cs.transactionsPerBlockEMA).toBeDefined();
- expect(typeof cs.lastFinalizedBlockHeight).toEqual('bigint');
- expect(cs.transactionsPerBlockEMSD).toBeDefined();
-
- if (isConsensusStatusV0(cs)) {
- expect(typeof cs.slotDuration).toEqual('bigint');
- } else if (isConsensusStatusV1(cs)) {
- expect(typeof cs.concordiumBFTStatus.currentTimeoutDuration).toEqual(
- 'bigint'
- );
- expect(typeof cs.concordiumBFTStatus.currentEpoch).toEqual('bigint');
- expect(typeof cs.concordiumBFTStatus.currentRound).toEqual('bigint');
- expect(
- cs.concordiumBFTStatus.triggerBlockTime instanceof Date
- ).toBeTruthy();
- }
-});
diff --git a/packages/nodejs/test/util.test.ts b/packages/nodejs/test/util.test.ts
deleted file mode 100644
index 94998daad..000000000
--- a/packages/nodejs/test/util.test.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { intListToStringList } from '../src/util';
-
-test('Correctly converts stringified list of numbers to stringified list of corresponding strings', () => {
- // List of ints
- let numbers = '[1, 22, 332]';
- let strings = intListToStringList(numbers);
-
- expect(strings).toEqual('["1", "22", "332"]');
-
- // Empty list
- numbers = '[]';
- strings = intListToStringList(numbers);
-
- expect(strings).toEqual('[]');
-
- // Single int list
- numbers = '[1]';
- strings = intListToStringList(numbers);
-
- expect(strings).toEqual('["1"]');
-
- // negative int list
- numbers = '[-1, 21, -32]';
- strings = intListToStringList(numbers);
-
- expect(strings).toEqual('["-1", "21", "-32"]');
-});
diff --git a/packages/nodejs/tsconfig.eslint.json b/packages/nodejs/tsconfig.eslint.json
deleted file mode 100644
index 911b9eefa..000000000
--- a/packages/nodejs/tsconfig.eslint.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "extends": "./tsconfig.json",
- "include": ["src/**/*", "test/**/*"]
-}
\ No newline at end of file
diff --git a/packages/nodejs/tsconfig.jest.json b/packages/nodejs/tsconfig.jest.json
deleted file mode 100644
index d3ce9180d..000000000
--- a/packages/nodejs/tsconfig.jest.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "extends": "./tsconfig",
- "compilerOptions": {
- "module": "CommonJS"
- },
- "exclude": ["lib/pkg/**/*"]
-}
diff --git a/packages/nodejs/tsconfig.json b/packages/nodejs/tsconfig.json
deleted file mode 100644
index b62f8da08..000000000
--- a/packages/nodejs/tsconfig.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "extends": "../../tsconfig-base.json",
- "include": ["src/**/*"],
- "references": [
- { "path": "../common"}
- ],
- "compilerOptions": {
- "rootDir": "src",
- "outDir": "./lib"
- }
-}
diff --git a/packages/rust-bindings/CHANGELOG.md b/packages/rust-bindings/CHANGELOG.md
index e90c74dae..22e033740 100644
--- a/packages/rust-bindings/CHANGELOG.md
+++ b/packages/rust-bindings/CHANGELOG.md
@@ -1,5 +1,19 @@
# Changelog
+## 2.0.0
+
+### Breaking changes
+
+- The package has been split into two entrypoints to decrease the size of bundles produced for applications using only part of the functionality provided.
+ - `@concordium/rust-bindings` (and its alias `@concordium/rust-bindings/dapp`) entrypoints expose functionality commonly used by dApps.
+ - `@concordium/rust-bindings/wallet` entrypoint exposes functionality commonly used by wallets and other applications requiring functionality used in wallets.
+ - If using a bundler, it might be preferable to load the WASM module asynchronously instead of the version which has it inlined. This can be done
+ by adding an alias to your bundler resolve configuration from `@concordium/rust-bindings` to `@concordium/rust-bindings/bundler`.
+ - This change makes the library **incompatible** with node versions <16 and requires bundlers to respect the `exports` field of `package.json`.
+ - For TypeScript projects the minimum required version of typescript is:
+ - NodeJS: 4.7, `"moduleResolution": "node16" // or "nodenext"`
+ - Bundled applications (webpack, esbuild, rollup, etc...): 5.0, `"moduleResolution": "bundler"`
+
## 1.2.0
### Added
@@ -102,7 +116,7 @@
### Changes
-- Bindings for the HdWallet methods: `getAccountSigningKey`, `getAccountPublicKey`, `getPrfKey`, `getSignatureBlindingRandomness` and `getAttributeCommitmentRandomness` now takes the identity provider index as parameter.
+- Bindings for the HdWallet methods: `getAccountSigningKey`, `getAccountPublicKey`, `getPrfKey`, `getSignatureBlindingRandomness` and `getAttributeCommitmentRandomness` now takes the identity provider index as parameter.
## 0.3.0 2022-8-15
@@ -111,4 +125,4 @@
- `createCredentialV1`
- `createIdRequestV1`
- `createIdentityRecoveryRequest`
-- Bindings for the HdWallet methods: `getAccountSigningKey`, `getAccountPublicKey`, `getPrfKey`, `getSignatureBlindingRandomness` and `getAttributeCommitmentRandomness`.
+- Bindings for the HdWallet methods: `getAccountSigningKey`, `getAccountPublicKey`, `getPrfKey`, `getSignatureBlindingRandomness` and `getAttributeCommitmentRandomness`.
diff --git a/packages/rust-bindings/Cargo.lock b/packages/rust-bindings/Cargo.lock
index 670324ebe..abcb9c1d5 100644
--- a/packages/rust-bindings/Cargo.lock
+++ b/packages/rust-bindings/Cargo.lock
@@ -26,9 +26,9 @@ dependencies = [
[[package]]
name = "aho-corasick"
-version = "1.0.2"
+version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "43f6cb1bf222025340178f382c426f13757b2960e89779dfcb319c32542a5a41"
+checksum = "0c378d78423fdad8089616f827526ee33c19f2fddbd5de1629152c9593ba4783"
dependencies = [
"memchr",
]
@@ -50,9 +50,9 @@ dependencies = [
[[package]]
name = "anyhow"
-version = "1.0.71"
+version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8"
+checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
[[package]]
name = "arrayvec"
@@ -68,9 +68,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "base64"
-version = "0.21.2"
+version = "0.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d"
+checksum = "9ba43ea6f343b788c8764558649e08df62f86c6ef251fdaeb1ffd010a9ae50a2"
[[package]]
name = "base64ct"
@@ -198,15 +198,18 @@ checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
[[package]]
name = "bytes"
-version = "1.4.0"
+version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be"
+checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223"
[[package]]
name = "cc"
-version = "1.0.79"
+version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f"
+checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0"
+dependencies = [
+ "libc",
+]
[[package]]
name = "cfg-if"
@@ -216,18 +219,17 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chrono"
-version = "0.4.26"
+version = "0.4.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ec837a71355b28f6556dbd569b37b3f363091c0bd4b2e735674521b4c5fd9bc5"
+checksum = "defd4e7873dbddba6c7c91e199c7fcb946abc4a6a4ac3195400bcfb01b5de877"
dependencies = [
"android-tzdata",
"iana-time-zone",
"js-sys",
"num-traits",
"serde",
- "time 0.1.45",
"wasm-bindgen",
- "winapi",
+ "windows-targets",
]
[[package]]
@@ -241,7 +243,7 @@ dependencies = [
"fnv",
"hashbrown 0.11.2",
"hex",
- "num-bigint 0.4.3",
+ "num-bigint 0.4.4",
"num-integer",
"num-traits",
"rust_decimal",
@@ -256,28 +258,7 @@ version = "4.0.0"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.23",
-]
-
-[[package]]
-name = "concordium-rust-bindings"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "chrono",
- "concordium_base",
- "ed25519-dalek",
- "ed25519_hd_key_derivation",
- "either",
- "hex",
- "key_derivation",
- "rand 0.7.3",
- "serde",
- "serde-wasm-bindgen",
- "serde_json",
- "serde_with",
- "thiserror",
- "wasm-bindgen",
+ "syn 2.0.32",
]
[[package]]
@@ -302,7 +283,7 @@ dependencies = [
"libc",
"nom",
"num",
- "num-bigint 0.4.3",
+ "num-bigint 0.4.4",
"num-traits",
"pairing",
"rand 0.7.3",
@@ -325,7 +306,49 @@ version = "1.0.0"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.23",
+ "syn 2.0.32",
+]
+
+[[package]]
+name = "concordium_rust_bindings_common"
+version = "0.1.0"
+dependencies = [
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "concordium_rust_bindings_dapp"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "concordium_base",
+ "concordium_rust_bindings_common",
+ "hex",
+ "serde-wasm-bindgen",
+ "serde_json",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "concordium_rust_bindings_wallet"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "chrono",
+ "concordium_base",
+ "concordium_rust_bindings_common",
+ "ed25519-dalek",
+ "ed25519_hd_key_derivation",
+ "either",
+ "hex",
+ "key_derivation",
+ "rand 0.7.3",
+ "serde",
+ "serde-wasm-bindgen",
+ "serde_json",
+ "serde_with",
+ "thiserror",
+ "wasm-bindgen",
]
[[package]]
@@ -417,9 +440,9 @@ dependencies = [
[[package]]
name = "darling"
-version = "0.20.1"
+version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0558d22a7b463ed0241e993f76f09f30b126687447751a8638587b864e4b3944"
+checksum = "0209d94da627ab5605dcccf08bb18afa5009cfbef48d8a8b7d7bdbc79be25c5e"
dependencies = [
"darling_core",
"darling_macro",
@@ -427,27 +450,36 @@ dependencies = [
[[package]]
name = "darling_core"
-version = "0.20.1"
+version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ab8bfa2e259f8ee1ce5e97824a3c55ec4404a0d772ca7fa96bf19f0752a046eb"
+checksum = "177e3443818124b357d8e76f53be906d60937f0d3a90773a664fa63fa253e621"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim",
- "syn 2.0.23",
+ "syn 2.0.32",
]
[[package]]
name = "darling_macro"
-version = "0.20.1"
+version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "29a358ff9f12ec09c3e61fef9b5a9902623a695a46a917b07f269bff1445611a"
+checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5"
dependencies = [
"darling_core",
"quote",
- "syn 2.0.23",
+ "syn 2.0.32",
+]
+
+[[package]]
+name = "deranged"
+version = "0.3.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2696e8a945f658fd14dc3b87242e6b80cd0f36ff04ea560fa39082368847946"
+dependencies = [
+ "serde",
]
[[package]]
@@ -520,9 +552,15 @@ dependencies = [
[[package]]
name = "either"
-version = "1.8.1"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07"
+
+[[package]]
+name = "equivalent"
+version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91"
+checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
[[package]]
name = "ff"
@@ -630,6 +668,12 @@ dependencies = [
"ahash 0.8.3",
]
+[[package]]
+name = "hashbrown"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a"
+
[[package]]
name = "hermit-abi"
version = "0.3.2"
@@ -700,6 +744,17 @@ dependencies = [
"serde",
]
+[[package]]
+name = "indexmap"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.14.0",
+ "serde",
+]
+
[[package]]
name = "itertools"
version = "0.10.5"
@@ -711,9 +766,9 @@ dependencies = [
[[package]]
name = "itoa"
-version = "1.0.8"
+version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "62b02a5381cc465bd3041d84623d0fa3b66738b52b8e2fc3bab8ad63ab032f4a"
+checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38"
[[package]]
name = "js-sys"
@@ -773,15 +828,15 @@ checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"
[[package]]
name = "log"
-version = "0.4.19"
+version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4"
+checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
[[package]]
name = "memchr"
-version = "2.5.0"
+version = "2.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
+checksum = "8f232d6ef707e1956a43342693d2a31e72989554d58299d7a88738cc95b0d35c"
[[package]]
name = "memoffset"
@@ -810,11 +865,11 @@ dependencies = [
[[package]]
name = "num"
-version = "0.4.0"
+version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "43db66d1170d347f9a065114077f7dccb00c1b9478c89384490a3425279a4606"
+checksum = "b05180d69e3da0e530ba2a1dae5110317e49e3b7f3d41be227dc5f92e49ee7af"
dependencies = [
- "num-bigint 0.4.3",
+ "num-bigint 0.4.4",
"num-complex",
"num-integer",
"num-iter",
@@ -835,9 +890,9 @@ dependencies = [
[[package]]
name = "num-bigint"
-version = "0.4.3"
+version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f"
+checksum = "608e7659b5c3d7cba262d894801b9ec9d00de989e8a82bd4bef91d08da45cdc0"
dependencies = [
"autocfg",
"num-integer",
@@ -846,9 +901,9 @@ dependencies = [
[[package]]
name = "num-complex"
-version = "0.4.3"
+version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "02e0d21255c828d6f128a1e41534206671e8c3ea0c62f32291e808dc82cff17d"
+checksum = "1ba157ca0885411de85d6ca030ba7e2a83a28636056c7c699b07c8b6f7383214"
dependencies = [
"num-traits",
]
@@ -881,16 +936,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0"
dependencies = [
"autocfg",
- "num-bigint 0.4.3",
+ "num-bigint 0.4.4",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
-version = "0.2.15"
+version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd"
+checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2"
dependencies = [
"autocfg",
]
@@ -969,9 +1024,9 @@ dependencies = [
[[package]]
name = "proc-macro2"
-version = "1.0.63"
+version = "1.0.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7b368fba921b0dce7e60f5e04ec15e565b3303972b42bcfde1d0713b881959eb"
+checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9"
dependencies = [
"unicode-ident",
]
@@ -998,9 +1053,9 @@ dependencies = [
[[package]]
name = "quote"
-version = "1.0.29"
+version = "1.0.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "573015e8ab27661678357f27dc26460738fd2b6c86e46f386fde94cb5d913105"
+checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"
dependencies = [
"proc-macro2",
]
@@ -1115,9 +1170,9 @@ dependencies = [
[[package]]
name = "regex"
-version = "1.9.0"
+version = "1.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "89089e897c013b3deb627116ae56a6955a72b8bed395c9526af31c9fe528b484"
+checksum = "697061221ea1b4a94a624f67d0ae2bfe4e22b8a17b6a192afb11046542cc8c47"
dependencies = [
"aho-corasick",
"memchr",
@@ -1127,9 +1182,9 @@ dependencies = [
[[package]]
name = "regex-automata"
-version = "0.3.0"
+version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fa250384981ea14565685dea16a9ccc4d1c541a13f82b9c168572264d1df8c56"
+checksum = "c2f401f4955220693b56f8ec66ee9c78abffd8d1c4f23dc41a23839eb88f0795"
dependencies = [
"aho-corasick",
"memchr",
@@ -1138,9 +1193,9 @@ dependencies = [
[[package]]
name = "regex-syntax"
-version = "0.7.3"
+version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2ab07dc67230e4a4718e70fd5c20055a4334b121f1f9db8fe63ef39ce9b8c846"
+checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da"
[[package]]
name = "rend"
@@ -1181,14 +1236,12 @@ dependencies = [
[[package]]
name = "rust_decimal"
-version = "1.30.0"
+version = "1.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d0446843641c69436765a35a5a77088e28c2e6a12da93e84aa3ab1cd4aa5a042"
+checksum = "a4c4216490d5a413bc6d10fa4742bd7d4955941d062c0ef873141d6b0e7b30fd"
dependencies = [
"arrayvec",
"borsh",
- "bytecheck",
- "byteorder",
"bytes",
"num-traits",
"rand 0.8.5",
@@ -1208,15 +1261,15 @@ dependencies = [
[[package]]
name = "ryu"
-version = "1.0.14"
+version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fe232bdf6be8c8de797b22184ee71118d63780ea42ac85b61d1baa6d3b782ae9"
+checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741"
[[package]]
name = "scopeguard"
-version = "1.1.0"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "seahash"
@@ -1226,15 +1279,15 @@ checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
[[package]]
name = "semver"
-version = "1.0.17"
+version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed"
+checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918"
[[package]]
name = "serde"
-version = "1.0.166"
+version = "1.0.188"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d01b7404f9d441d3ad40e6a636a7782c377d2abdbe4fa2440e2edcc2f4f10db8"
+checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e"
dependencies = [
"serde_derive",
]
@@ -1252,20 +1305,20 @@ dependencies = [
[[package]]
name = "serde_derive"
-version = "1.0.166"
+version = "1.0.188"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5dd83d6dde2b6b2d466e14d9d1acce8816dedee94f735eac6395808b3483c6d6"
+checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.23",
+ "syn 2.0.32",
]
[[package]]
name = "serde_json"
-version = "1.0.100"
+version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0f1e14e89be7aa4c4b78bdbdc9eb5bf8517829a600ae8eaa39a6e1d960b5185c"
+checksum = "2cc66a619ed80bf7a0f6b17dd063a84b88f6dea1813737cf469aef1d081142c2"
dependencies = [
"itoa",
"ryu",
@@ -1274,30 +1327,31 @@ dependencies = [
[[package]]
name = "serde_with"
-version = "3.0.0"
+version = "3.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9f02d8aa6e3c385bf084924f660ce2a3a6bd333ba55b35e8590b321f35d88513"
+checksum = "1ca3b16a3d82c4088f343b7480a93550b3eabe1a358569c2dfe38bbcead07237"
dependencies = [
"base64",
"chrono",
"hex",
- "indexmap",
+ "indexmap 1.9.3",
+ "indexmap 2.0.0",
"serde",
"serde_json",
"serde_with_macros",
- "time 0.3.22",
+ "time",
]
[[package]]
name = "serde_with_macros"
-version = "3.0.0"
+version = "3.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "edc7d5d3932fb12ce722ee5e64dd38c504efba37567f0c402f6ca728c3b8b070"
+checksum = "2e6be15c453eb305019bfa438b1593c731f36a289a7853f7707ee29e870b3b3c"
dependencies = [
"darling",
"proc-macro2",
"quote",
- "syn 2.0.23",
+ "syn 2.0.32",
]
[[package]]
@@ -1371,9 +1425,9 @@ dependencies = [
[[package]]
name = "syn"
-version = "2.0.23"
+version = "2.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "59fb7d6d8281a51045d62b8eb3a7d1ce347b76f312af50cd3dc0af39c87c1737"
+checksum = "239814284fd6f1a4ffe4ca893952cdd93c224b6a1571c9a9eadd670295c0c9e2"
dependencies = [
"proc-macro2",
"quote",
@@ -1388,41 +1442,31 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "thiserror"
-version = "1.0.41"
+version = "1.0.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c16a64ba9387ef3fdae4f9c1a7f07a0997fce91985c0336f1ddc1822b3b37802"
+checksum = "9d6d7a740b8a666a7e828dd00da9c0dc290dff53154ea77ac109281de90589b7"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
-version = "1.0.41"
+version = "1.0.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d14928354b01c4d6a4f0e549069adef399a284e7995c7ccca94e8a07a5346c59"
+checksum = "49922ecae66cc8a249b77e68d1d0623c1b2c514f0060c27cdc68bd62a1219d35"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.23",
+ "syn 2.0.32",
]
[[package]]
name = "time"
-version = "0.1.45"
+version = "0.3.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a"
-dependencies = [
- "libc",
- "wasi 0.10.0+wasi-snapshot-preview1",
- "winapi",
-]
-
-[[package]]
-name = "time"
-version = "0.3.22"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ea9e1b3cf1243ae005d9e74085d4d542f3125458f3a81af210d901dcd7411efd"
+checksum = "17f6bb557fd245c28e6411aa56b6403c689ad95061f50e4be16c274e70a17e48"
dependencies = [
+ "deranged",
"itoa",
"serde",
"time-core",
@@ -1437,9 +1481,9 @@ checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb"
[[package]]
name = "time-macros"
-version = "0.2.9"
+version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "372950940a5f07bf38dbe211d7283c9e6d7327df53794992d293e534c733d09b"
+checksum = "1a942f44339478ef67935ab2bbaec2fb0322496cf3cbe84b261e06ac3814c572"
dependencies = [
"time-core",
]
@@ -1476,15 +1520,15 @@ checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba"
[[package]]
name = "unicode-ident"
-version = "1.0.10"
+version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "22049a19f4a68748a168c0fc439f9516686aa045927ff767eca0a85101fb6e73"
+checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c"
[[package]]
name = "uuid"
-version = "1.4.0"
+version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d023da39d1fde5a8a3fe1f3e01ca9632ada0a63e9797de55a879d6e2236277be"
+checksum = "79daa5ed5740825c40b389c5e50312b9c86df53fccd33f281df655642b43869d"
[[package]]
name = "version_check"
@@ -1498,12 +1542,6 @@ version = "0.9.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
-[[package]]
-name = "wasi"
-version = "0.10.0+wasi-snapshot-preview1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"
-
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
@@ -1533,7 +1571,7 @@ dependencies = [
"once_cell",
"proc-macro2",
"quote",
- "syn 2.0.23",
+ "syn 2.0.32",
"wasm-bindgen-shared",
]
@@ -1555,7 +1593,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.23",
+ "syn 2.0.32",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
@@ -1566,28 +1604,6 @@ version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1"
-[[package]]
-name = "winapi"
-version = "0.3.9"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
-dependencies = [
- "winapi-i686-pc-windows-gnu",
- "winapi-x86_64-pc-windows-gnu",
-]
-
-[[package]]
-name = "winapi-i686-pc-windows-gnu"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
-
-[[package]]
-name = "winapi-x86_64-pc-windows-gnu"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
-
[[package]]
name = "windows"
version = "0.48.0"
@@ -1599,9 +1615,9 @@ dependencies = [
[[package]]
name = "windows-targets"
-version = "0.48.1"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "05d4b17490f70499f20b9e791dcf6a299785ce8af4d709018206dc5b4953e95f"
+checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
@@ -1614,45 +1630,45 @@ dependencies = [
[[package]]
name = "windows_aarch64_gnullvm"
-version = "0.48.0"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc"
+checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_msvc"
-version = "0.48.0"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3"
+checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_i686_gnu"
-version = "0.48.0"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241"
+checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_msvc"
-version = "0.48.0"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00"
+checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_x86_64_gnu"
-version = "0.48.0"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1"
+checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnullvm"
-version = "0.48.0"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953"
+checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_msvc"
-version = "0.48.0"
+version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a"
+checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "wyz"
@@ -1680,5 +1696,5 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.23",
+ "syn 2.0.32",
]
diff --git a/packages/rust-bindings/Cargo.toml b/packages/rust-bindings/Cargo.toml
index 37fcbd182..4fa3c8774 100644
--- a/packages/rust-bindings/Cargo.toml
+++ b/packages/rust-bindings/Cargo.toml
@@ -1,36 +1,30 @@
-[package]
-name = "concordium-rust-bindings"
-version = "0.1.0"
+[workspace]
+members = ["packages/*"]
+
+[workspace.package]
authors = ["Concordium AG "]
-edition = "2018"
+edition = "2021"
[profile.dev]
opt-level = 3
-[dependencies]
-serde = { version = "1.0", features = ["derive"] }
-serde_json = "1.0"
-wasm-bindgen = { version = "0.2.80", features = ["serde-serialize"] }
+[workspace.dependencies]
anyhow = "1.0"
-hex = "0.4"
+concordium_rust_bindings_common = { path = "./packages/common" }
either = "1.6"
-thiserror = "1.0"
-rand = { version = "=0.7", features = [ "wasm-bindgen" ] }
-ed25519-dalek = { version = "=1.0" }
-chrono = "0.4.24"
-serde_with = "3.0.0"
+hex = "0.4"
+rand = { version = "=0.7", features = ["wasm-bindgen"] }
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
serde-wasm-bindgen = "0.5"
+thiserror = "1.0"
+wasm-bindgen = { version = "0.2.80", features = ["serde-serialize"] }
-[dependencies.concordium_base]
+[workspace.dependencies.concordium_base]
path = "../../deps/concordium-base/rust-src/concordium_base"
-[dependencies.ed25519_hd_key_derivation]
+[workspace.dependencies.ed25519_hd_key_derivation]
path = "../../deps/concordium-base/rust-src/ed25519_hd_key_derivation"
-[dependencies.key_derivation]
+[workspace.dependencies.key_derivation]
path = "../../deps/concordium-base/rust-src/key_derivation"
-
-[lib]
-name = "concordium_rust_bindings"
-crate-type = ["cdylib"]
-path = "src/lib.rs"
diff --git a/packages/rust-bindings/package.json b/packages/rust-bindings/package.json
index 4cfed00cf..f0c883a42 100644
--- a/packages/rust-bindings/package.json
+++ b/packages/rust-bindings/package.json
@@ -1,26 +1,104 @@
{
"name": "@concordium/rust-bindings",
- "version": "1.2.0",
+ "version": "2.0.0",
"license": "Apache-2.0",
"engines": {
- "node": ">=14.16.0"
+ "node": ">=16"
},
"repository": {
"type": "git",
"url": "https://github.com/Concordium/concordium-node-sdk-js",
"directory": "packages/rust-bindings"
},
- "main": "pkg/node/concordium_rust_bindings.js",
- "browser": "pkg/bundler/concordium_rust_bindings.js",
- "types": "pkg/bundler/concordium_rust_bindings.d.ts",
+ "sideEffects": [
+ "./lib/*/web/index.min.js",
+ "./lib/*/bundler/index.js"
+ ],
+ "main": "lib/dapp/node/cjs/index.js",
+ "browser": "lib/dapp/web/umd/index.min.js",
+ "types": "lib/dapp/node/cjs/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./lib/dapp/node/cjs/index.d.ts",
+ "node": {
+ "module": "./lib/dapp/node/umd/index.min.js",
+ "default": "./lib/dapp/node/cjs/index.js"
+ },
+ "browser": {
+ "module": "./lib/dapp/web/umd/index.min.js",
+ "types": "./lib/dapp/web/esm/index.d.ts",
+ "import": "./lib/dapp/web/esm/index.js",
+ "default": "./lib/dapp/web/umd/index.min.js"
+ },
+ "default": "./lib/dapp/web/umd/index.min.js"
+ },
+ "./dapp": {
+ "types": "./lib/dapp/node/cjs/index.d.ts",
+ "node": {
+ "module": "./lib/dapp/node/umd/index.min.js",
+ "default": "./lib/dapp/node/cjs/index.js"
+ },
+ "browser": {
+ "module": "./lib/dapp/web/umd/index.min.js",
+ "types": "./lib/dapp/web/esm/index.d.ts",
+ "import": "./lib/dapp/web/esm/index.js",
+ "default": "./lib/dapp/web/umd/index.min.js"
+ },
+ "default": "./lib/dapp/web/umd/index.min.js"
+ },
+ "./wallet": {
+ "types": "./lib/wallet/node/cjs/index.d.ts",
+ "node": {
+ "module": "./lib/wallet/node/umd/index.min.js",
+ "default": "./lib/wallet/node/cjs/index.js"
+ },
+ "browser": {
+ "module": "./lib/wallet/web/umd/index.min.js",
+ "types": "./lib/wallet/web/esm/index.d.ts",
+ "import": "./lib/wallet/web/esm/index.js",
+ "default": "./lib/wallet/web/umd/index.min.js"
+ },
+ "default": "./lib/wallet/web/umd/index.min.js"
+ },
+ "./bundler": {
+ "types": "./lib/dapp/bundler/index.d.ts",
+ "default": "./lib/dapp/bundler/index.js"
+ },
+ "./bundler/dapp": {
+ "types": "./lib/dapp/bundler/index.d.ts",
+ "default": "./lib/dapp/bundler/index.js"
+ },
+ "./bundler/wallet": {
+ "types": "./lib/wallet/bundler/index.d.ts",
+ "default": "./lib/wallet/bundler/index.js"
+ }
+ },
"files": [
- "/pkg/**/concordium_rust_bindings*"
+ "./lib/**/index*"
],
"scripts": {
"fmt": "cargo +nightly-2023-04-01-x86_64-unknown-linux-gnu fmt -- --color=always --check",
"clippy": "cargo +1.62 clippy --color=always --tests --benches -- -Dclippy::all",
- "build": "wasm-pack build --target web --out-dir pkg/bundler \"$@\" && wasm-pack build --target nodejs --out-dir pkg/node \"$@\"",
- "build-dev": "yarn build --dev",
- "build:rust-bindings": "yarn build"
+ "build-web": "wasm-pack build ./packages/dapp --target web --out-dir $INIT_CWD/lib/dapp/web/esm --out-name index \"$@\" && wasm-pack build ./packages/wallet --target web --out-dir $INIT_CWD/lib/wallet/web/esm --out-name index \"$@\" && webpack",
+ "build-node": "wasm-pack build ./packages/dapp --target nodejs --out-dir $INIT_CWD/lib/dapp/node/cjs --out-name index \"$@\" && wasm-pack build ./packages/wallet --target nodejs --out-dir $INIT_CWD/lib/wallet/node/cjs --out-name index \"$@\"",
+ "build-bundler": "wasm-pack build ./packages/dapp --target bundler --out-dir $INIT_CWD/lib/dapp/bundler --out-name index \"$@\" && wasm-pack build ./packages/wallet --target bundler --out-dir $INIT_CWD/lib/wallet/bundler --out-name index \"$@\"",
+ "build": "yarn build-node \"$@\" && yarn build-bundler \"$@\" && yarn build-web \"$@\" && yarn sanitize",
+ "build:rust-bindings": "yarn build",
+ "clean": "rimraf -- target lib .webpack-cache",
+ "sanitize": "find . -name \"*.gitignore\" -delete",
+ "lint": "eslint . --cache --ext .ts,.tsx --max-warnings 0",
+ "lint-fix": "yarn --silent lint --fix; exit 0"
+ },
+ "devDependencies": {
+ "eslint": "^8.50.0",
+ "rimraf": "^5.0.1",
+ "ts-loader": "^9.4.4",
+ "typescript": "^5.2.2",
+ "wasm-pack": "^0.12.1",
+ "webpack": "^5.88.2",
+ "webpack-cli": "^5.1.4"
+ },
+ "dependencies": {
+ "buffer": "^6.0.3"
}
}
diff --git a/packages/rust-bindings/packages/common/Cargo.toml b/packages/rust-bindings/packages/common/Cargo.toml
new file mode 100644
index 000000000..79ba561c0
--- /dev/null
+++ b/packages/rust-bindings/packages/common/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+name = "concordium_rust_bindings_common"
+authors.workspace = true
+version = "0.1.0"
+edition.workspace = true
+
+[dependencies]
+wasm-bindgen.workspace = true
+
+[lib]
+name = "concordium_rust_bindings_common"
+# crate-type = ["lib"]
+path = "src/lib.rs"
diff --git a/packages/rust-bindings/packages/common/src/helpers.rs b/packages/rust-bindings/packages/common/src/helpers.rs
new file mode 100644
index 000000000..72d3eea8b
--- /dev/null
+++ b/packages/rust-bindings/packages/common/src/helpers.rs
@@ -0,0 +1,8 @@
+use std::fmt::Display;
+use wasm_bindgen::prelude::*;
+
+use crate::types::JsonString;
+
+pub type JsResult = Result;
+
+pub fn to_js_error(error: impl Display) -> JsError { JsError::new(&format!("{}", error)) }
diff --git a/packages/rust-bindings/packages/common/src/lib.rs b/packages/rust-bindings/packages/common/src/lib.rs
new file mode 100644
index 000000000..52af0f9cd
--- /dev/null
+++ b/packages/rust-bindings/packages/common/src/lib.rs
@@ -0,0 +1,2 @@
+pub mod helpers;
+pub mod types;
diff --git a/packages/rust-bindings/packages/common/src/types.rs b/packages/rust-bindings/packages/common/src/types.rs
new file mode 100644
index 000000000..bea6624ca
--- /dev/null
+++ b/packages/rust-bindings/packages/common/src/types.rs
@@ -0,0 +1,3 @@
+pub type JsonString = String;
+pub type HexString = String;
+pub type Base58String = String;
diff --git a/packages/rust-bindings/packages/dapp/Cargo.toml b/packages/rust-bindings/packages/dapp/Cargo.toml
new file mode 100644
index 000000000..2db6c918d
--- /dev/null
+++ b/packages/rust-bindings/packages/dapp/Cargo.toml
@@ -0,0 +1,21 @@
+[package]
+name = "concordium_rust_bindings_dapp"
+authors.workspace = true
+version = "0.1.0"
+edition.workspace = true
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+serde_json.workspace = true
+wasm-bindgen.workspace = true
+anyhow.workspace = true
+hex.workspace = true
+serde-wasm-bindgen.workspace = true
+concordium_base.workspace = true
+concordium_rust_bindings_common.workspace = true
+
+[lib]
+name = "concordium_rust_bindings_dapp"
+crate-type = ["cdylib"]
+path = "src/lib.rs"
diff --git a/packages/rust-bindings/packages/dapp/src/aux_functions.rs b/packages/rust-bindings/packages/dapp/src/aux_functions.rs
new file mode 100644
index 000000000..257906e90
--- /dev/null
+++ b/packages/rust-bindings/packages/dapp/src/aux_functions.rs
@@ -0,0 +1,198 @@
+use anyhow::{anyhow, Result};
+use concordium_base::contracts_common::{
+ from_bytes,
+ schema::{ModuleV0, Type, VersionedModuleSchema},
+ Cursor,
+};
+use concordium_rust_bindings_common::types::{HexString, JsonString};
+use serde_json::{to_string, Value as SerdeValue};
+
+/// Given the bytes of a contract's state, deserialize them to a json object,
+/// using the provided schema. Both the state bytes and the schema are given as
+/// hex-encoded strings.
+pub fn deserialize_state_aux(
+ contract_name: &str,
+ state_bytes: HexString,
+ schema: HexString,
+ verbose_error_message: bool,
+) -> Result {
+ let module_schema: ModuleV0 = match from_bytes(&hex::decode(schema)?) {
+ Ok(o) => o,
+ Err(e) => return Err(anyhow!("unable to parse schema: {:#?}", e)),
+ };
+ let contract_schema = module_schema
+ .contracts
+ .get(contract_name)
+ .ok_or_else(|| anyhow!("Unable to get contract schema: not included in module schema"))?;
+ let state_schema = contract_schema
+ .state
+ .as_ref()
+ .ok_or_else(|| anyhow!("Unable to get state schema: not included in contract schema"))?;
+
+ deserialize_type_value(state_bytes, state_schema, verbose_error_message)
+}
+
+/// Given the bytes of a receive function's return value, deserialize them to a
+/// json object, using the provided schema.
+pub fn deserialize_receive_return_value_aux(
+ return_value_bytes: HexString,
+ schema: HexString,
+ contract_name: &str,
+ function_name: &str,
+ schema_version: Option,
+ verbose_error_message: bool,
+) -> Result {
+ let module_schema = VersionedModuleSchema::new(&hex::decode(schema)?, &schema_version)?;
+ let return_value_schema =
+ module_schema.get_receive_return_value_schema(contract_name, function_name)?;
+
+ deserialize_type_value(
+ return_value_bytes,
+ &return_value_schema,
+ verbose_error_message,
+ )
+}
+
+/// Given the bytes of a receive function's error, deserialize them to a json
+/// object, using the provided schema.
+pub fn deserialize_receive_error_aux(
+ error_bytes: HexString,
+ schema: HexString,
+ contract_name: &str,
+ function_name: &str,
+ verbose_error_message: bool,
+) -> Result {
+ let module_schema = VersionedModuleSchema::new(&hex::decode(schema)?, &None)?;
+ let error_schema = module_schema.get_receive_error_schema(contract_name, function_name)?;
+
+ deserialize_type_value(error_bytes, &error_schema, verbose_error_message)
+}
+
+/// Given the bytes of an init function's error, deserialize them to a json
+/// object, using the provided schema.
+pub fn deserialize_init_error_aux(
+ error_bytes: HexString,
+ schema: HexString,
+ contract_name: &str,
+ verbose_error_message: bool,
+) -> Result {
+ let module_schema = VersionedModuleSchema::new(&hex::decode(schema)?, &None)?;
+ let error_schema = module_schema.get_init_error_schema(contract_name)?;
+
+ deserialize_type_value(error_bytes, &error_schema, verbose_error_message)
+}
+
+/// Given parameters to a receive function as a stringified json, serialize them
+/// using the provided schema.
+pub fn serialize_receive_contract_parameters_aux(
+ parameters: JsonString,
+ schema: HexString,
+ contract_name: &str,
+ function_name: &str,
+ schema_version: Option,
+ verbose_error_message: bool,
+) -> Result {
+ let module_schema = VersionedModuleSchema::new(&hex::decode(schema)?, &schema_version)?;
+ let parameter_type = module_schema.get_receive_param_schema(contract_name, function_name)?;
+ let value: SerdeValue = serde_json::from_str(¶meters)?;
+
+ let buf = parameter_type
+ .serial_value(&value)
+ .map_err(|e| anyhow!("{}", e.display(verbose_error_message)))?;
+
+ Ok(hex::encode(buf))
+}
+
+/// Given parameters to an init function as a stringified json, serialize them
+/// using the provided schema.
+pub fn serialize_init_contract_parameters_aux(
+ parameters: JsonString,
+ schema: HexString,
+ contract_name: &str,
+ schema_version: Option,
+ verbose_error_message: bool,
+) -> Result {
+ let module_schema = VersionedModuleSchema::new(&hex::decode(schema)?, &schema_version)?;
+ let parameter_type = module_schema.get_init_param_schema(contract_name)?;
+ let value: SerdeValue = serde_json::from_str(¶meters)?;
+
+ let buf = parameter_type
+ .serial_value(&value)
+ .map_err(|e| anyhow!("{}", e.display(verbose_error_message)))?;
+
+ Ok(hex::encode(buf))
+}
+
+pub fn get_receive_contract_parameter_schema_aux(
+ schema: HexString,
+ contract_name: &str,
+ function_name: &str,
+ schema_version: Option,
+) -> Result {
+ let module_schema = VersionedModuleSchema::new(&hex::decode(schema)?, &schema_version)?;
+ let parameter_type = module_schema.get_receive_param_schema(contract_name, function_name)?;
+ Ok(hex::encode(concordium_base::contracts_common::to_bytes(
+ ¶meter_type,
+ )))
+}
+
+pub fn get_init_contract_parameter_schema_aux(
+ schema: HexString,
+ contract_name: &str,
+ schema_version: Option,
+) -> Result {
+ let module_schema = VersionedModuleSchema::new(&hex::decode(schema)?, &schema_version)?;
+ let parameter_type = module_schema.get_init_param_schema(contract_name)?;
+ Ok(hex::encode(concordium_base::contracts_common::to_bytes(
+ ¶meter_type,
+ )))
+}
+
+pub fn serialize_type_value_aux(
+ parameters: JsonString,
+ schema: HexString,
+ verbose_error_message: bool,
+) -> Result {
+ let parameter_type: Type = from_bytes(&hex::decode(schema)?)?;
+ serialize_type_value(parameters, parameter_type, verbose_error_message)
+}
+
+fn serialize_type_value(
+ raw_value: JsonString,
+ value_type: Type,
+ verbose_error_message: bool,
+) -> Result {
+ let value: SerdeValue = serde_json::from_str(&raw_value)?;
+
+ let buf = value_type
+ .serial_value(&value)
+ .map_err(|e| anyhow!("{}", e.display(verbose_error_message)))?;
+ Ok(hex::encode(buf))
+}
+
+pub fn deserialize_type_value_aux(
+ serialized_value: HexString,
+ schema: HexString,
+ verbose_error_message: bool,
+) -> Result {
+ let value_type: Type = from_bytes(&hex::decode(schema)?)?;
+ deserialize_type_value(serialized_value, &value_type, verbose_error_message)
+}
+
+fn deserialize_type_value(
+ serialized_value: HexString,
+ value_type: &Type,
+ verbose_error_message: bool,
+) -> Result {
+ let mut cursor = Cursor::new(hex::decode(serialized_value)?);
+ match value_type.to_json(&mut cursor) {
+ Ok(v) => Ok(to_string(&v)?),
+ Err(e) => Err(anyhow!("{}", e.display(verbose_error_message))),
+ }
+}
+
+pub fn display_type_schema_template_aux(schema: HexString) -> Result {
+ let value_type: Type = from_bytes(&hex::decode(schema)?)?;
+ let v = value_type.to_json_template();
+ Ok(to_string(&v)?)
+}
diff --git a/packages/rust-bindings/packages/dapp/src/external_functions.rs b/packages/rust-bindings/packages/dapp/src/external_functions.rs
new file mode 100644
index 000000000..7809d834c
--- /dev/null
+++ b/packages/rust-bindings/packages/dapp/src/external_functions.rs
@@ -0,0 +1,165 @@
+use crate::aux_functions::*;
+use concordium_rust_bindings_common::{
+ helpers::{to_js_error, JsResult},
+ types::{HexString, JsonString},
+};
+use wasm_bindgen::prelude::*;
+
+#[wasm_bindgen(js_name = deserializeState)]
+pub fn deserialize_state(
+ contract_name: &str,
+ state_bytes: HexString,
+ schema: String,
+ verbose_error_message: Option,
+) -> JsResult {
+ deserialize_state_aux(
+ contract_name,
+ state_bytes,
+ schema,
+ verbose_error_message.unwrap_or(false),
+ )
+ .map_err(to_js_error)
+}
+
+#[wasm_bindgen(js_name = deserializeReceiveReturnValue)]
+pub fn deserialize_receive_return_value(
+ return_value_bytes: HexString,
+ module_schema: HexString,
+ contract_name: &str,
+ function_name: &str,
+ schema_version: Option,
+ verbose_error_message: Option,
+) -> JsResult {
+ deserialize_receive_return_value_aux(
+ return_value_bytes,
+ module_schema,
+ contract_name,
+ function_name,
+ schema_version,
+ verbose_error_message.unwrap_or(false),
+ )
+ .map_err(to_js_error)
+}
+
+#[wasm_bindgen(js_name = deserializeReceiveError)]
+pub fn deserialize_receive_error(
+ error_bytes: HexString,
+ schema: HexString,
+ contract_name: &str,
+ function_name: &str,
+ verbose_error_message: Option,
+) -> JsResult {
+ deserialize_receive_error_aux(
+ error_bytes,
+ schema,
+ contract_name,
+ function_name,
+ verbose_error_message.unwrap_or(false),
+ )
+ .map_err(to_js_error)
+}
+
+#[wasm_bindgen(js_name = deserializeInitError)]
+pub fn deserialize_init_error(
+ error_bytes: HexString,
+ schema: HexString,
+ contract_name: &str,
+ verbose_error_message: Option,
+) -> JsResult {
+ deserialize_init_error_aux(
+ error_bytes,
+ schema,
+ contract_name,
+ verbose_error_message.unwrap_or(false),
+ )
+ .map_err(to_js_error)
+}
+
+#[wasm_bindgen(js_name = serializeReceiveContractParameters)]
+pub fn serialize_receive_contract_parameters(
+ parameters: JsonString,
+ schema: HexString,
+ contract_name: &str,
+ function_name: &str,
+ schema_version: Option,
+ verbose_error_message: Option,
+) -> JsResult {
+ serialize_receive_contract_parameters_aux(
+ parameters,
+ schema,
+ contract_name,
+ function_name,
+ schema_version,
+ verbose_error_message.unwrap_or(false),
+ )
+ .map_err(|e| JsError::new(&format!("Unable to serialize parameters, due to: {}", e)))
+}
+
+#[wasm_bindgen(js_name = serializeInitContractParameters)]
+pub fn serialize_init_contract_parameters(
+ parameters: JsonString,
+ schema: HexString,
+ contract_name: &str,
+ schema_version: Option,
+ verbose_error_message: Option,
+) -> JsResult {
+ serialize_init_contract_parameters_aux(
+ parameters,
+ schema,
+ contract_name,
+ schema_version,
+ verbose_error_message.unwrap_or(false),
+ )
+ .map_err(|e| JsError::new(&format!("Unable to serialize parameters, due to: {}", e)))
+}
+
+#[wasm_bindgen(js_name = getReceiveContractParameterSchema)]
+pub fn get_receive_contract_parameter_schema_ext(
+ schema: HexString,
+ contract_name: &str,
+ function_name: &str,
+ schema_version: Option,
+) -> JsResult {
+ get_receive_contract_parameter_schema_aux(schema, contract_name, function_name, schema_version)
+ .map_err(|e| JsError::new(&format!("Unable to get parameter schema, due to: {}", e)))
+}
+
+#[wasm_bindgen(js_name = getInitContractParameterSchema)]
+pub fn get_init_contract_parameter_schema_ext(
+ schema: HexString,
+ contract_name: &str,
+ schema_version: Option,
+) -> JsResult {
+ get_init_contract_parameter_schema_aux(schema, contract_name, schema_version)
+ .map_err(|e| JsError::new(&format!("unable to get parameter schema, due to: {}", e)))
+}
+
+#[wasm_bindgen(js_name = serializeTypeValue)]
+pub fn serialize_type_value_ext(
+ value: JsonString,
+ schema: HexString,
+ verbose_error_message: Option,
+) -> JsResult {
+ serialize_type_value_aux(value, schema, verbose_error_message.unwrap_or(false))
+ .map_err(|e| JsError::new(&format!("Unable to serialize value due to: {}", e)))
+}
+
+#[wasm_bindgen(js_name = deserializeTypeValue)]
+pub fn deserialize_type_value_ext(
+ serialized_value: HexString,
+ schema: HexString,
+ verbose_error_message: Option,
+) -> JsResult {
+ deserialize_type_value_aux(
+ serialized_value,
+ schema,
+ verbose_error_message.unwrap_or(false),
+ )
+ .map_err(|e| JsError::new(&format!("Unable to deserialize value due to: {}", e)))
+}
+
+#[wasm_bindgen(js_name = displayTypeSchemaTemplate)]
+pub fn display_type_schema_template(schema: HexString) -> JsResult {
+ display_type_schema_template_aux(schema)
+ .map_err(|e| JsError::new(&format!("Unable to get template of schema: {}", e)))
+}
diff --git a/packages/rust-bindings/packages/dapp/src/lib.rs b/packages/rust-bindings/packages/dapp/src/lib.rs
new file mode 100644
index 000000000..7b7333f1d
--- /dev/null
+++ b/packages/rust-bindings/packages/dapp/src/lib.rs
@@ -0,0 +1,2 @@
+mod aux_functions;
+pub mod external_functions;
diff --git a/packages/rust-bindings/packages/wallet/Cargo.toml b/packages/rust-bindings/packages/wallet/Cargo.toml
new file mode 100644
index 000000000..763e885f6
--- /dev/null
+++ b/packages/rust-bindings/packages/wallet/Cargo.toml
@@ -0,0 +1,30 @@
+[package]
+name = "concordium_rust_bindings_wallet"
+authors.workspace = true
+version = "0.1.0"
+edition.workspace = true
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+serde.workspace = true
+serde_json.workspace = true
+wasm-bindgen.workspace = true
+anyhow.workspace = true
+hex.workspace = true
+either.workspace = true
+thiserror.workspace = true
+rand.workspace = true
+serde-wasm-bindgen.workspace = true
+concordium_base.workspace = true
+ed25519_hd_key_derivation.workspace = true
+key_derivation.workspace = true
+concordium_rust_bindings_common.workspace = true
+ed25519-dalek = { version = "=1.0" }
+chrono = "0.4.24"
+serde_with = "3.0.0"
+
+[lib]
+name = "concordium_rust_bindings_wallet"
+crate-type = ["cdylib"]
+path = "src/lib.rs"
diff --git a/packages/rust-bindings/src/aux_functions.rs b/packages/rust-bindings/packages/wallet/src/aux_functions.rs
similarity index 78%
rename from packages/rust-bindings/src/aux_functions.rs
rename to packages/rust-bindings/packages/wallet/src/aux_functions.rs
index bf660f2aa..af61026d4 100644
--- a/packages/rust-bindings/src/aux_functions.rs
+++ b/packages/rust-bindings/packages/wallet/src/aux_functions.rs
@@ -1,4 +1,3 @@
-use crate::{helpers::*, types::*};
use anyhow::{anyhow, bail, ensure, Context, Result};
use concordium_base::{
base::{BakerAggregationSignKey, BakerElectionSignKey, BakerKeyPairs, BakerSignatureSignKey},
@@ -7,11 +6,8 @@ use concordium_base::{
types::{KeyIndex, KeyPair, TransactionTime},
*,
},
- contracts_common::{
- from_bytes,
- schema::{ModuleV0, Type, VersionedModuleSchema},
- ContractAddress, Cursor,
- },
+ contracts_common::ContractAddress,
+ curve_arithmetic::Pairing,
id::{
account_holder::{
create_credential, create_unsigned_credential, generate_id_recovery_request,
@@ -28,21 +24,83 @@ use concordium_base::{
secret_sharing::Threshold,
types::*,
},
+ ps_sig::SigRetrievalRandomness,
transactions::{ConfigureBakerKeysPayload, Payload},
web3id::{
CredentialHolderId, OwnedCommitmentInputs, Request, SignedCommitments, Web3IdAttribute,
Web3IdSigner,
},
};
+use concordium_rust_bindings_common::types::{HexString, JsonString};
use either::Either::Left;
-use hex;
use key_derivation::{ConcordiumHdWallet, CredentialContext, Net};
use rand::thread_rng;
use serde::{Deserialize as SerdeDeserialize, Serialize as SerdeSerialize};
-use serde_json::{from_str, to_string, Value as SerdeValue};
+use serde_json::{from_str, from_value, to_string, Value as SerdeValue};
use std::{collections::BTreeMap, convert::TryInto};
use thiserror::Error;
+#[derive(SerdeSerialize, SerdeDeserialize)]
+#[serde(bound(serialize = "P: Pairing", deserialize = "P: Pairing"))]
+pub struct RandomnessWrapper {
+ #[serde(
+ rename = "randomness",
+ serialize_with = "base16_encode",
+ deserialize_with = "base16_decode"
+ )]
+ pub randomness: SigRetrievalRandomness,
+}
+
+fn build_key_map(keys: &[VerifyKey]) -> BTreeMap {
+ keys.iter()
+ .enumerate()
+ .map(|(index, key)| (KeyIndex(index.try_into().unwrap()), key.clone()))
+ .collect()
+}
+
+fn build_signature_map(signatures: &[String]) -> BTreeMap {
+ signatures
+ .iter()
+ .enumerate()
+ .map(|(index, key)| {
+ (
+ KeyIndex(index.try_into().unwrap()),
+ base16_decode_string(key).unwrap(),
+ )
+ })
+ .collect()
+}
+
+fn build_policy(
+ attributes: &AttributeList,
+ revealed_attributes: Vec,
+) -> Result> {
+ let mut policy_vec = std::collections::BTreeMap::new();
+ for tag in revealed_attributes {
+ if let Some(att) = attributes.alist.get(&tag) {
+ if policy_vec.insert(tag, att.clone()).is_some() {
+ bail!("Cannot reveal an attribute more than once.")
+ }
+ } else {
+ bail!("Cannot reveal an attribute which is not part of the attribute list.")
+ }
+ }
+ Ok(Policy {
+ valid_to: attributes.valid_to,
+ created_at: attributes.created_at,
+ policy_vec,
+ _phantom: Default::default(),
+ })
+}
+
+/// Try to extract a field with a given name from the JSON value.
+fn try_get(v: &SerdeValue, fname: &str) -> Result {
+ match v.get(fname) {
+ Some(v) => Ok(from_value(v.clone())?),
+ None => Err(anyhow!("Field {} not present, but should be.", fname)),
+ }
+}
+
#[derive(SerdeSerialize, SerdeDeserialize)]
pub struct CredId {
#[serde(
@@ -65,13 +123,6 @@ pub struct IdRequestInput {
ar_threshold: u8,
}
-pub fn error_to_string(result: Result) -> String {
- match result {
- Ok(s) => s,
- Err(e) => format!("{}", e),
- }
-}
-
fn get_net(net: &str) -> Result {
Ok(match net {
"Mainnet" => Net::Mainnet,
@@ -572,196 +623,6 @@ pub fn get_credential_deployment_info_aux(
Ok(cdi_json.to_string())
}
-/// Given the bytes of a contract's state, deserialize them to a json object,
-/// using the provided schema. Both the state bytes and the schema are given as
-/// hex-encoded strings.
-pub fn deserialize_state_aux(
- contract_name: &str,
- state_bytes: HexString,
- schema: HexString,
- verbose_error_message: bool,
-) -> Result {
- let module_schema: ModuleV0 = match from_bytes(&hex::decode(schema)?) {
- Ok(o) => o,
- Err(e) => return Err(anyhow!("unable to parse schema: {:#?}", e)),
- };
- let contract_schema = module_schema
- .contracts
- .get(contract_name)
- .ok_or_else(|| anyhow!("Unable to get contract schema: not included in module schema"))?;
- let state_schema = contract_schema
- .state
- .as_ref()
- .ok_or_else(|| anyhow!("Unable to get state schema: not included in contract schema"))?;
-
- deserialize_type_value(state_bytes, state_schema, verbose_error_message)
-}
-
-/// Given the bytes of a receive function's return value, deserialize them to a
-/// json object, using the provided schema.
-pub fn deserialize_receive_return_value_aux(
- return_value_bytes: HexString,
- schema: HexString,
- contract_name: &str,
- function_name: &str,
- schema_version: Option,
- verbose_error_message: bool,
-) -> Result {
- let module_schema = VersionedModuleSchema::new(&hex::decode(schema)?, &schema_version)?;
- let return_value_schema =
- module_schema.get_receive_return_value_schema(contract_name, function_name)?;
-
- deserialize_type_value(
- return_value_bytes,
- &return_value_schema,
- verbose_error_message,
- )
-}
-
-/// Given the bytes of a receive function's error, deserialize them to a json
-/// object, using the provided schema.
-pub fn deserialize_receive_error_aux(
- error_bytes: HexString,
- schema: HexString,
- contract_name: &str,
- function_name: &str,
- verbose_error_message: bool,
-) -> Result