Compare commits

..
57 changed files with 1779 additions and 572 deletions
+28
View File
@@ -0,0 +1,28 @@
---
name: Feature Epic
about: A template to capture and scope user requirements, high level process, and basic mockups for an upcoming feature as part of the initial core spec review process.
title: 'FEATURE EPIC: '
labels: feature-epic
---
## Core Feature
<Name>
## Tasks
- [ ] Define high level requirements
- [ ] Create basic mockups
- [ ] Update "API Requirements" in core spec
- [ ] Update "User-Interface Spec" in relevant front end repo
- [ ] Create detailed user stories using normal template
## High Level Requirements
## Basic Mockups
## Link to API Requirements in Core spec
## Link to User Interface Specs
## Linked User Stories
+1 -1
View File
@@ -1,6 +1,6 @@
# Related issues 🔗
Closes #[Issue number here]
Issue: #[Issue number here]
# Description
@@ -7,7 +7,7 @@ on:
jobs:
after-release:
runs-on: ubuntu-22.04
timeout-minutes: 30
timeout-minutes: 45
steps:
- name: Checkout
uses: actions/checkout@v3
@@ -30,18 +30,20 @@ jobs:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Wait for publish to complete
uses: lewagon/wait-on-check-action@v1.3.1
with:
ref: ${{ github.event.release.tag_name }}
check-name: '(CD) publish dist / trading'
repo-token: ${{ secrets.GITHUB_TOKEN }}
wait-interval: 10
- name: resolve ipfs hashes for release
run: |
echo "Name: ${{ github.event.release.name }}"
echo "Description: ${{ github.event.release.body }}"
echo "Tag: ${{ github.event.release.tag_name }}"
commit="$(git rev-list -n 1 ${{ github.event.release.tag_name }})"
echo "Commit: $commit"
until docker pull vegaprotocol/trading:$commit; do
echo "Image not pushed yet, waiting 60 seconds"
sleep 60
done
docker run --rm vegaprotocol/trading:$commit cat /ipfs-hash > ipfs-hash
docker run --rm vegaprotocol/trading:mainnet cat /ipfs-hash > ipfs-hash
curl -L https://dist.ipfs.tech/kubo/v0.20.0/kubo_v0.20.0_linux-amd64.tar.gz -o kubo.tgz
tar -xzf kubo.tgz
export PATH="$PATH:$PWD/kubo"
+1 -1
View File
@@ -6,7 +6,7 @@ name: 'Add Issues To Project Board'
types:
- opened
env:
GH_TOKEN: ${{ secrets.GH_NEW_CARD_TO_PROJECT }}
GH_TOKEN: ${{ secrets.PROJECT_MANAGE_ACTION }}
PROJECT_ID: ${{ secrets.FRONT_END_PROJECT_ID }}
ISSUE_ID: ${{ github.event.issue.node_id }}
USER: ${{ github.actor }}
+39 -111
View File
@@ -5,10 +5,7 @@ on:
branches:
- release/*
- develop
- main
# uncomment pull_request and comment pull_request_target to test CI changes against feature branch not target branch (develop)
# pull_request:
pull_request_target:
pull_request:
types:
- opened
- ready_for_review
@@ -49,7 +46,7 @@ jobs:
lint-pr-title:
needs: node-modules
if: ${{ github.event_name == 'pull_request' || github.event_name == 'pull_request_target' }}
if: ${{ github.event_name == 'pull_request' }}
name: Verify PR title
uses: ./.github/workflows/lint-pr.yml
secrets: inherit
@@ -84,6 +81,22 @@ jobs:
with:
main-branch-name: develop
# See affected apps
- name: See affected apps
run: |
branch_slug="$(echo '${{ github.head_ref || github.ref_name }}' | sed -r s/[^a-zA-Z0-9]+/-/g | sed -r s/^-+\|-+$//g | cut -c 1-50 )"
python3 tools/ci/check-affected.py --github-ref="${{ github.ref }}" --branch-slug="$branch_slug" --event-name="${{ github.event_name }}"
- name: Verify script result
run: |
echo "Check outputs from script"
echo "projects: ${{ env.PROJECTS }}"
echo "projects-e2e: ${{ env.PROJECTS_E2E }}"
echo "preview_governance: ${{ env.PREVIEW_GOVERNANCE }}"
echo "preview_trading: ${{ env.PREVIEW_TRADING }}"
echo "preview_explorer: ${{ env.PREVIEW_EXPLORER }}"
echo "preview_tools: ${{ env.PREVIEW_TOOLS }}"
- name: Check formatting
run: yarn nx format:check
@@ -99,100 +112,6 @@ jobs:
- name: Build affected
run: yarn nx affected:build || (yarn install && yarn nx affected:build)
# See affected apps
- name: See affected apps
run: |
affected="$(yarn nx print-affected --base=${{ env.NX_BASE }} --head=${{ env.NX_HEAD }} --select=projects)"
branch_slug="$(echo '${{ github.head_ref || github.ref_name }}' | sed -r s/[^a-zA-Z0-9]+/-/g | sed -r s/^-+\|-+$//g | cut -c 1-50 )"
echo ">>>> debug"
echo "NX_BASE: ${{ env.NX_BASE }}"
echo "NX_HEAD: ${{ env.NX_HEAD }}"
echo "Affected: ${affected}"
echo "Branch slug: ${branch_slug}"
echo ">>>> eof debug"
projects_array=()
preview_governance="not deployed"
preview_trading="not deployed"
preview_explorer="not deployed"
preview_tools="not deployed"
# parse if affected is any of three main applications, if none - use all of them
if echo "$affected" | grep -q governance; then
echo "Governance is affected"
projects_array+=("governance")
preview_governance=$(printf "https://%s.%s.vega.rocks" "governance" "$branch_slug")
fi
if echo "$affected" | grep -q trading; then
echo "Trading is affected"
projects_array+=("trading")
preview_trading=$(printf "https://%s.%s.vega.rocks" "trading" "$branch_slug")
fi
if echo "$affected" | grep -q explorer; then
echo "Explorer is affected"
projects_array+=("explorer")
preview_explorer=$(printf "https://%s.%s.vega.rocks" "explorer" "$branch_slug")
fi
if [[ ${#projects_array[@]} -eq 0 ]]; then
projects_array=("governance" "trading" "explorer")
preview_governance=$(printf "https://%s.%s.vega.rocks" "governance" "$branch_slug")
preview_trading=$(printf "https://%s.%s.vega.rocks" "trading" "$branch_slug")
preview_explorer=$(printf "https://%s.%s.vega.rocks" "explorer" "$branch_slug")
fi
# applications parsed before this loop are applicable for running e2e-tests
projects_e2e_array=()
for project in "${projects_array[@]}"; do
projects_e2e_array+=("${project}-e2e")
done
# all applications below this loop are not applicable for running e2e-test
# check if pull request event to deploy tools
if [[ "${{ github.event_name }}" = "pull_request" ]]; then
if echo "$affected" | grep -q multisig-signer; then
echo "Tools are affected"
echo "Deploying tools on preview"
preview_tools=$(printf "https://%s.%s.vega.rocks" "tools" "$branch_slug")
projects_array+=("multisig-signer")
fi
# those apps deploy only from develop to mainnet
elif [[ "${{ github.ref }}" =~ .*develop$ ]]; then
if echo "$affected" | grep -q multisig-signer; then
echo "Tools are affected"
echo "Deploying tools on s3"
projects_array+=("multisig-signer")
fi
if echo "$affected" | grep -q static; then
echo "static is affected"
echo "Deploying static on s3"
projects_array+=("static")
fi
if echo "$affected" | grep -q ui-toolkit; then
echo "ui-toolkit is affected"
echo "Deploying ui-toolkit on s3"
projects_array+=("ui-toolkit")
fi
fi
echo "Projects: ${projects_array[@]}"
echo "Projects E2E: ${projects_e2e_array[@]}"
projects_json=$(jq -M --compact-output --null-input '$ARGS.positional' --args -- "${projects_array[@]}")
projects_e2e_json=$(jq -M --compact-output --null-input '$ARGS.positional' --args -- "${projects_e2e_array[@]}")
echo PROJECTS_E2E=$projects_e2e_json >> $GITHUB_ENV
echo PROJECTS=$projects_json >> $GITHUB_ENV
echo PREVIEW_GOVERNANCE=$preview_governance >> $GITHUB_ENV
echo PREVIEW_TRADING=$preview_trading >> $GITHUB_ENV
echo PREVIEW_EXPLORER=$preview_explorer >> $GITHUB_ENV
echo PREVIEW_TOOLS=$preview_tools >> $GITHUB_ENV
outputs:
projects: ${{ env.PROJECTS }}
projects-e2e: ${{ env.PROJECTS_E2E }}
@@ -201,6 +120,15 @@ jobs:
preview_explorer: ${{ env.PREVIEW_EXPLORER }}
preview_tools: ${{ env.PREVIEW_TOOLS }}
console-e2e:
needs: lint-test-build
name: '(CI) console python'
uses: ./.github/workflows/console-test-run.yml
secrets: inherit
if: ${{ contains(fromJSON(needs.lint-test-build.outputs.projects), 'trading') && github.event_name == 'pull_request' }}
with:
github-sha: ${{ github.event.pull_request.head.sha || github.sha }}
cypress:
needs: lint-test-build
name: '(CI) cypress'
@@ -209,12 +137,12 @@ jobs:
secrets: inherit
with:
projects: ${{ needs.lint-test-build.outputs.projects-e2e }}
tags: '@smoke @regression'
tags: '@smoke'
publish-dist:
needs: lint-test-build
name: '(CD) publish dist'
# if: ${{ needs.lint-test-build.outputs.projects != '[]' }}
if: ${{ (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'vegaprotocol/frontend-monorepo') || github.event_name == 'push' }}
uses: ./.github/workflows/publish-dist.yml
secrets: inherit
with:
@@ -225,7 +153,7 @@ jobs:
needs:
- publish-dist
- lint-test-build
if: ${{ github.event_name == 'pull_request' || github.event_name == 'pull_request_target' }}
if: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == 'vegaprotocol/frontend-monorepo' }}
timeout-minutes: 60
name: '(CD) comment preview links'
steps:
@@ -241,26 +169,26 @@ jobs:
# https://stackoverflow.com/questions/3183444/check-for-valid-link-url
regex='(https?|ftp|file)://[-[:alnum:]\+&@#/%?=~_|!:,.;]*[-[:alnum:]\+&@#/%=~_|]'
if [[ "${{ needs.lint-test-build.outputs.preview_governance }}" =~ $regex ]]; then
until curl -L --fail "${{ needs.lint-test-build.outputs.preview_governance }}"; do
echo "waiting for governance preview"
until curl --insecure --location --fail "${{ needs.lint-test-build.outputs.preview_governance }}"; do
echo "waiting for governance preview: ${{ needs.lint-test-build.outputs.preview_governance }}"
sleep 5
done
fi
if [[ "${{ needs.lint-test-build.outputs.preview_explorer }}" =~ $regex ]]; then
until curl -L --fail "${{ needs.lint-test-build.outputs.preview_explorer }}"; do
echo "waiting for explorer preview"
until curl --insecure --location --fail "${{ needs.lint-test-build.outputs.preview_explorer }}"; do
echo "waiting for explorer preview: ${{ needs.lint-test-build.outputs.preview_explorer }}"
sleep 5
done
fi
if [[ "${{ needs.lint-test-build.outputs.preview_trading }}" =~ $regex ]]; then
until curl -L --fail "${{ needs.lint-test-build.outputs.preview_trading }}"; do
echo "waiting for trading preview"
until curl --insecure --location --fail "${{ needs.lint-test-build.outputs.preview_trading }}"; do
echo "waiting for trading preview: ${{ needs.lint-test-build.outputs.preview_trading }}"
sleep 5
done
fi
if [[ "${{ needs.lint-test-build.outputs.preview_tools }}" =~ $regex ]]; then
until curl -L --fail "${{ needs.lint-test-build.outputs.preview_tools }}"; do
echo "waiting for tools preview"
until curl --insecure --location --fail "${{ needs.lint-test-build.outputs.preview_tools }}"; do
echo "waiting for tools preview: ${{ needs.lint-test-build.outputs.preview_tools }}"
sleep 5
done
fi
@@ -271,7 +199,7 @@ jobs:
with:
issue-number: ${{ github.event.pull_request.number }}
body: |
Previews:
Previews
* governance: ${{ needs.lint-test-build.outputs.preview_governance }}
* explorer: ${{ needs.lint-test-build.outputs.preview_explorer }}
* trading: ${{ needs.lint-test-build.outputs.preview_trading }}
+142
View File
@@ -0,0 +1,142 @@
name: (CI) Console tests
on:
workflow_call:
inputs:
github-sha:
required: true
type: string
jobs:
run-tests:
name: run-tests
runs-on: 8-cores
timeout-minutes: 20
steps:
#----------------------------------------------
# check-out frontend-monorepo
#----------------------------------------------
- name: Checkout console test repo
uses: actions/checkout@v3
with:
ref: ${{ inputs.github-sha }}
#----------------------------------------------
# cache node modules
#----------------------------------------------
- name: Cache node modules
id: cache
uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-cache-node-modules-${{ hashFiles('yarn.lock') }}
# comment out "restore-keys" if you need to rebuild yarn from 0
restore-keys: |
${{ runner.os }}-cache-node-modules-
#----------------------------------------------
# setup node
#----------------------------------------------
- name: Setup node
uses: actions/setup-node@v3
with:
node-version-file: '.nvmrc'
# https://stackoverflow.com/questions/61010294/how-to-cache-yarn-packages-in-github-actions
cache: yarn
#----------------------------------------------
# install deps if cache missing
#----------------------------------------------
- name: yarn install
if: steps.cache.outputs.cache-hit != 'true'
run: yarn install --pure-lockfile
#----------------------------------------------
# build trading
#----------------------------------------------
- name: Build affected spec
run: |
yarn env-cmd -f ./apps/trading/.env.stagnet1 yarn nx export trading
#----------------------------------------------
# run trading server
#----------------------------------------------
- name: Run trading server
run: |
docker run -d -p 80:4200 -v $PWD/docker/nginx.conf:/etc/nginx/conf.d/default.conf -v $PWD/dist/apps/trading/exported:/usr/share/nginx/html nginx:1.23-alpine@sha256:6318314189b40e73145a48060bff4783a116c34cc7241532d0d94198fb2c9629
sleep 5
docker ps
#----------------------------------------------
# check if container persists between runs
#----------------------------------------------
- name: Check server
run: |
docker ps
#----------------------------------------------
# check-out tests repo
#----------------------------------------------
- name: Checkout console test repo
uses: actions/checkout@v3
with:
repository: vegaprotocol/console-test
path: './console-test'
#----------------------------------------------
# set-up python
#----------------------------------------------
- name: Set up python
id: setup-python
uses: actions/setup-python@v4
with:
python-version: '3.10.11'
#----------------------------------------------
# ----- install & configure poetry -----
#----------------------------------------------
- name: Install Poetry
uses: snok/install-poetry@v1
with:
virtualenvs-create: true
virtualenvs-in-project: true
virtualenvs-path: console-test/.venv
#----------------------------------------------
# load cached venv if cache exists
#----------------------------------------------
- name: Load cached venv
id: cached-poetry-dependencies
uses: actions/cache@v3
with:
path: console-test/.venv
key: venv-${{ runner.os }}-${{ steps.setup-python.outputs.python-version }}-${{ hashFiles('**/poetry.lock') }}
#----------------------------------------------
# install dependencies if cache does not exist
#----------------------------------------------
- name: Install dependencies
working-directory: ./console-test
if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true'
run: poetry install --no-interaction --no-root
#----------------------------------------------
# install vega binaries
#----------------------------------------------
- name: Install vega binaries
working-directory: ./console-test
run: poetry run python -m vega_sim.tools.load_binaries --force
#----------------------------------------------
# install playwright
#----------------------------------------------
- name: install playwright
run: poetry run playwright install
working-directory: ./console-test
#----------------------------------------------
# run tests
#----------------------------------------------
- name: Run tests
working-directory: ./console-test
run: poetry run pytest -v -s --numprocesses auto --dist loadfile --durations=20
- name: Check files
run: |
ls -al .
ls -al console-test
#----------------------------------------------
# upload traces
#----------------------------------------------
- name: Upload Playwright Trace
uses: actions/upload-artifact@v3
if: always()
with:
name: playwright-trace
path: ./traces/
retention-days: 15
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
project: ${{ fromJSON(inputs.projects) }}
name: ${{ matrix.project }}
runs-on: self-hosted-runner
timeout-minutes: 100
timeout-minutes: 120
steps:
# Checks if skip cache was requested
- name: Set skip-nx-cache flag
+67 -63
View File
@@ -22,6 +22,45 @@ jobs:
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
- name: Init variables
run: |
echo IS_PR=false >> $GITHUB_ENV
echo IS_MAINNET_RELEASE=false >> $GITHUB_ENV
echo IS_TESTNET_RELEASE=false >> $GITHUB_ENV
echo IS_IPFS_RELEASE=false >> $GITHUB_ENV
echo IS_S3_RELEASE=false >> $GITHUB_ENV
echo IS_DEV_IMAGE=false >> $GITHUB_ENV
- name: Is dev image
if: ${{ contains(github.ref, 'develop') && github.event_name == 'push' && matrix.app == 'trading' }}
run: |
echo IS_DEV_IMAGE=true >> $GITHUB_ENV
- name: Is PR
if: ${{ github.event_name == 'pull_request' }}
run: |
echo IS_PR=true >> $GITHUB_ENV
- name: Is mainnet release
if: ${{ contains(github.ref, 'release/mainnet') && !contains(github.ref, 'mirror') }}
run: |
echo IS_MAINNET_RELEASE=true >> $GITHUB_ENV
- name: Is testnet release
if: ${{ contains(github.ref, 'release/testnet') }}
run: |
echo IS_TESTNET_RELEASE=true >> $GITHUB_ENV
- name: Is IPFS Release
if: ${{ matrix.app == 'trading' && github.event_name == 'push' && ( env.IS_MAINNET_RELEASE == 'true' || env.IS_TESTNET_RELEASE == 'true' ) }}
run: |
echo IS_IPFS_RELEASE=true >> $GITHUB_ENV
- name: Is S3 Release
if: ${{ env.IS_IPFS_RELEASE == 'false' && github.event_name == 'push' }}
run: |
echo IS_S3_RELEASE=true >> $GITHUB_ENV
- name: Set up QEMU
id: quemu
uses: docker/setup-qemu-action@v2
@@ -33,7 +72,7 @@ jobs:
uses: docker/setup-buildx-action@v2
- name: Log in to the Container registry (ghcr)
if: ${{ github.event_name == 'pull_request' || github.event_name == 'pull_request_target' }}
if: ${{ env.IS_PR == 'true' }}
uses: docker/login-action@v2
with:
registry: ghcr.io
@@ -42,9 +81,8 @@ jobs:
- name: Log in to the Container registry (docker hub)
uses: docker/login-action@v2
if: ${{ matrix.app == 'trading' && github.event_name == 'push' && ( endsWith(github.ref, 'main') || endsWith(github.ref, 'release/testnet') ) }}
if: ${{ env.IS_IPFS_RELEASE == 'true' || env.IS_DEV_IMAGE == 'true' }}
with:
# registry: registry.hub.docker.com
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
@@ -65,51 +103,13 @@ jobs:
- name: Define dist variables
if: ${{ github.event_name == 'push' }}
run: |
envName=''
domain="vega.rocks"
bucketName=''
python3 tools/ci/define-dist-variables.py --github-ref="${{ github.ref }}" --app="${{ matrix.app }}"
if [[ "${{ github.ref }}" =~ .*release/.* ]]; then
envName="$(echo ${{ github.ref }} | rev | cut -d '/' -f 1 | rev)"
elif [[ "${{ github.ref }}" =~ .*develop$ ]]; then
envName="stagnet1"
if [[ "${{ matrix.app }}" = "multisig-signer" ]]; then
envName="mainnet"
bucketName="tools.vega.xyz"
fi
if [[ "${{ matrix.app }}" = "static" ]]; then
envName="mainnet"
bucketName="static.vega.xyz"
fi
if [[ "${{ matrix.app }}" = "ui-toolkit" ]]; then
envName="mainnet"
bucketName="ui.vega.rocks"
fi
elif [[ "${{ github.ref }}" =~ .*main$ ]]; then
envName="mainnet"
fi
if [[ "${envName}" = "mainnet" ]]; then
domain="vega.xyz"
if [[ -z "${bucketName}" ]]; then
bucketName="${{ matrix.app }}.${domain}"
fi
elif [[ "${envName}" = "testnet" ]]; then
domain="fairground.wtf"
if [[ -z "${bucketName}" ]]; then
bucketName="${{ matrix.app }}.${domain}"
fi
fi
if [[ -z "${bucketName}" ]]; then
bucketName="${{ matrix.app }}.${envName}.${domain}"
fi
echo "bucket name: ${bucketName}"
echo "env name: ${envName}"
echo BUCKET_NAME=${bucketName} >> $GITHUB_ENV
echo ENV_NAME=${envName} >> $GITHUB_ENV
- name: Verify script result
if: ${{ github.event_name == 'push' }}
run: |
echo "BUCKET_NAME=${{ env.BUCKET_NAME }}"
echo "ENV_NAME=${{ env.ENV_NAME }}"
- name: Build local dist
run: |
@@ -124,8 +124,12 @@ jobs:
elif [ "${{ matrix.app }}" = "ui-toolkit" ]; then
NODE_ENV=production yarn nx run ui-toolkit:build-storybook
DIST_LOCATION=dist/storybook/ui-toolkit
elif [ "${{ matrix.app }}" = "static" ]; then
yarn nx build static || (yarn install && yarn nx build static)
else
$envCmd yarn nx build ${{ matrix.app }} || (yarn install && $envCmd yarn nx build ${{ matrix.app }})
fi
if [[ -z "$DIST_LOCATION" ]]; then
DIST_LOCATION=dist/apps/${{ matrix.app }}
fi
mv $DIST_LOCATION dist-result
@@ -145,7 +149,7 @@ jobs:
ghcr.io/vegaprotocol/frontend/${{ matrix.app }}:local
- name: Image digest
if: ${{ github.event_name == 'pull_request' || github.event_name == 'pull_request_target' }}
if: ${{ env.IS_PR == 'true' }}
run: echo ${{ steps.docker_build.outputs.digest }}
- name: Sanity check docker image
@@ -160,7 +164,7 @@ jobs:
uses: docker/build-push-action@v3
continue-on-error: true
id: ghcr-push
if: ${{ github.event_name == 'pull_request' || github.event_name == 'pull_request_target' }}
if: ${{ env.IS_PR == 'true' }}
with:
context: .
file: docker/node-outside-docker.Dockerfile
@@ -175,7 +179,7 @@ jobs:
uses: docker/build-push-action@v3
continue-on-error: true
id: dockerhub-push
if: ${{ matrix.app == 'trading' && github.event_name == 'push' && ( endsWith(github.ref, 'main') || endsWith(github.ref, 'release/testnet') ) }}
if: ${{ env.IS_IPFS_RELEASE == 'true' || env.IS_DEV_IMAGE == 'true' }}
with:
context: .
file: docker/node-outside-docker.Dockerfile
@@ -185,7 +189,7 @@ jobs:
ENV_NAME=${{ env.ENV_NAME }}
tags: |
vegaprotocol/${{ matrix.app }}:${{ github.sha }}
vegaprotocol/${{ matrix.app }}:${{ endsWith(github.ref, 'main') && 'mainnet' || endsWith(github.ref, 'release/testnet') && 'testnet' || '' }}
vegaprotocol/${{ matrix.app }}:${{ env.IS_MAINNET_RELEASE == 'true' && 'mainnet' || env.IS_TESTNET_RELEASE == 'true' && 'testnet' || env.IS_DEV_IMAGE == 'true' && 'develop' || '' }}
- name: Publish dist as docker image (ghcr - retry)
uses: docker/build-push-action@v3
@@ -212,13 +216,13 @@ jobs:
ENV_NAME=${{ env.ENV_NAME }}
tags: |
vegaprotocol/${{ matrix.app }}:${{ github.sha }}
vegaprotocol/${{ matrix.app }}:${{ endsWith(github.ref, 'main') && 'mainnet' || endsWith(github.ref, 'release/testnet') && 'testnet' || '' }}
vegaprotocol/${{ matrix.app }}:${{ env.IS_MAINNET_RELEASE == 'true' && 'mainnet' || env.IS_TESTNET_RELEASE == 'true' && 'testnet' || '' }}
# bucket creation in github.com/vegaprotocol/terraform//frontend
- name: Publish dist to s3
uses: jakejarvis/s3-sync-action@master
# s3 releases are not happening for trading on mainnet - it's IPFS
if: ${{ github.event_name == 'push' && ( matrix.app != 'trading' || (matrix.app == 'trading' && !( endsWith(github.ref, 'main') || endsWith(github.ref, 'release/testnet') ) ) ) }}
if: ${{ env.IS_S3_RELEASE == 'true' }}
with:
args: --acl private --follow-symlinks --delete
env:
@@ -229,11 +233,11 @@ jobs:
SOURCE_DIR: 'dist-result'
- name: Install aws CLI
if: ${{ github.event_name == 'push' && ( matrix.app != 'trading' || (matrix.app == 'trading' && !( endsWith(github.ref, 'main') || endsWith(github.ref, 'release/testnet') ) ) ) }}
if: ${{ env.IS_S3_RELEASE == 'true' }}
uses: unfor19/install-aws-cli-action@master
- name: Perform cache invalidation
if: ${{ github.event_name == 'push' && ( matrix.app != 'trading' || (matrix.app == 'trading' && !( endsWith(github.ref, 'main') || endsWith(github.ref, 'release/testnet') ) ) ) }}
if: ${{ env.IS_S3_RELEASE == 'true' }}
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
@@ -246,16 +250,16 @@ jobs:
- name: Add preview label
uses: actions-ecosystem/action-add-labels@v1
if: ${{ github.event_name == 'pull_request' || github.event_name == 'pull_request_target' }}
if: ${{ env.IS_PR == 'true' }}
with:
labels: ${{ matrix.app }}-preview
number: ${{ github.event.number }}
- name: Trigger fleek deployment
# release to ipfs happens only on mainnet (represented by main branch) for trading
if: ${{ matrix.app == 'trading' && github.event_name == 'push' && ( endsWith(github.ref, 'main') || endsWith(github.ref, 'release/testnet') ) }}
if: ${{ env.IS_IPFS_RELEASE == 'true' }}
run: |
if echo ${{ github.ref }} | grep -q main; then
if [[ "${{ env.IS_MAINNET_RELEASE }}" = "true" ]]; then
# display info about app
curl --fail -H "Authorization: ${{ secrets.FLEEK_API_KEY }}" \
-H "Content-Type: application/json" \
@@ -268,7 +272,7 @@ jobs:
-d '{"query": "mutation{triggerDeploy(siteId:\"f8f2e051-f18e-49e6-b876-0a39369dc0d8\"){id status}}"}' \
https://api.fleek.co/graphql
elif echo ${{ github.ref }} | grep -q release/testnet; then
elif [[ "${{ env.IS_TESTNET_RELEASE }}" = "true" ]]; then
# display info about app
curl --fail -H "Authorization: ${{ secrets.FLEEK_API_KEY }}" \
-H "Content-Type: application/json" \
@@ -283,7 +287,7 @@ jobs:
fi
- name: Check out ipfs-redirect
if: ${{ matrix.app == 'trading' && github.event_name == 'push' && ( endsWith(github.ref, 'main') || endsWith(github.ref, 'testnet') ) }}
if: ${{ env.IS_IPFS_RELEASE == 'true' }}
uses: actions/checkout@v3
with:
repository: 'vegaprotocol/ipfs-redirect'
@@ -292,7 +296,7 @@ jobs:
token: ${{ secrets.VEGA_CI_BOT_GITHUB_TOKEN }}
- name: Update interstitial page to point to the new console
if: ${{ matrix.app == 'trading' && github.event_name == 'push' && ( endsWith(github.ref, 'main') || endsWith(github.ref, 'testnet') ) }}
if: ${{ env.IS_IPFS_RELEASE == 'true' }}
env:
GH_TOKEN: ${{ secrets.VEGA_CI_BOT_GITHUB_TOKEN }}
run: |
@@ -314,11 +318,11 @@ jobs:
git config --global user.name "vega-ci-bot"
# update CID files
if echo ${{ github.ref }} | grep -q main; then
if [[ "${{ env.IS_MAINNET_RELEASE }}" = "true" ]]; then
echo $new_hash > cidv0-mainnet.txt
echo $new_cid > cidv1-mainnet.txt
git add cidv0-mainnet.txt cidv1-mainnet.txt
elif echo ${{ github.ref }} | grep -q release/testnet; then
elif [[ "${{ env.IS_TESTNET_RELEASE }}" = "true" ]]; then
echo $new_hash > cidv0-fairground.txt
echo $new_cid > cidv1-fairground.txt
git add cidv0-fairground.txt cidv1-fairground.txt
+1
View File
@@ -15,6 +15,7 @@ on:
- types
- utils
- i18n
- wallet
jobs:
publish:
+1 -1
View File
@@ -1,5 +1,5 @@
# App configuration variables
NX_TENDERMINT_URL=https://tm.be.devnet1.vega.xyz/tm
NX_TENDERMINT_URL=https://tm.be.devnet1.vega.xyz/
NX_TENDERMINT_WEBSOCKET_URL=wss://be.devnet1.vega.xyz/websocket
NX_VEGA_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/networks-internal/main/devnet1/vegawallet-devnet1.toml
NX_VEGA_ENV=DEVNET
+1 -1
View File
@@ -77,7 +77,7 @@
"executor": "nx:run-commands",
"options": {
"commands": [
"npx openapi-typescript https://raw.githubusercontent.com/vegaprotocol/documentation/main/specs/v0.71.4/blockexplorer.openapi.json --output apps/explorer/src/types/explorer.d.ts --immutable-types"
"npx openapi-typescript https://raw.githubusercontent.com/vegaprotocol/documentation/spec-update-v0.72.0-preview.2/specs/v0.72.0-preview.2/blockexplorer.openapi.json --output apps/explorer/src/types/explorer.d.ts --immutable-types"
]
}
},
@@ -6,10 +6,32 @@ import {
SPECIAL_CASE_NETWORK_ID,
} from '../../../../links/party-link/party-link';
import SizeInAsset from '../../../../size-in-asset/size-in-asset';
import { AccountTypeMapping } from '@vegaprotocol/types';
import { AccountType } from '@vegaprotocol/types';
import { headerClasses, wrapperClasses } from '../transfer-details';
import type { Transfer } from '../transfer-details';
import type { components } from '../../../../../../types/explorer';
type Transfer = components['schemas']['commandsv1Transfer'];
type AccountTypes = components['schemas']['vegaAccountType'];
const AccountType: Record<AccountTypes, string> = {
ACCOUNT_TYPE_UNSPECIFIED: 'Unspecified',
ACCOUNT_TYPE_INSURANCE: 'Insurance',
ACCOUNT_TYPE_SETTLEMENT: 'Settlement',
ACCOUNT_TYPE_MARGIN: 'Margin',
ACCOUNT_TYPE_GENERAL: 'General',
ACCOUNT_TYPE_FEES_INFRASTRUCTURE: 'Infrastructure',
ACCOUNT_TYPE_FEES_LIQUIDITY: 'Liquidity',
ACCOUNT_TYPE_FEES_MAKER: 'Maker',
ACCOUNT_TYPE_BOND: 'Bond',
ACCOUNT_TYPE_EXTERNAL: 'External',
ACCOUNT_TYPE_GLOBAL_INSURANCE: 'Global Insurance',
ACCOUNT_TYPE_GLOBAL_REWARD: 'Global Reward',
ACCOUNT_TYPE_PENDING_TRANSFERS: 'Pending Transfers',
ACCOUNT_TYPE_REWARD_MAKER_PAID_FEES: 'Maker Paid Fees',
ACCOUNT_TYPE_REWARD_MAKER_RECEIVED_FEES: 'Maker Received Fees',
ACCOUNT_TYPE_REWARD_LP_RECEIVED_FEES: 'LP Received Fees',
ACCOUNT_TYPE_REWARD_MARKET_PROPOSERS: 'Market Proposers',
ACCOUNT_TYPE_HOLDING: 'Holding',
};
interface TransferParticipantsProps {
transfer: Transfer;
@@ -30,22 +52,22 @@ export function TransferParticipants({
}: TransferParticipantsProps) {
// This mapping is required as the global account types require a type to be set, while
// the underlying protobufs allow for every field to be undefined.
const fromAcct =
const fromAcct: AccountTypes =
transfer.fromAccountType &&
transfer.fromAccountType !== 'ACCOUNT_TYPE_UNSPECIFIED'
? AccountType[transfer.fromAccountType]
: AccountType.ACCOUNT_TYPE_GENERAL;
const fromAccountTypeLabel = transfer.fromAccountType
? AccountTypeMapping[fromAcct]
? transfer.fromAccountType
: 'ACCOUNT_TYPE_GENERAL';
const fromAccountTypeLabel: string = transfer.fromAccountType
? AccountType[fromAcct]
: 'Unknown';
const toAcct =
const toAcct: AccountTypes =
transfer.toAccountType &&
transfer.toAccountType !== 'ACCOUNT_TYPE_UNSPECIFIED'
? AccountType[transfer.toAccountType]
: AccountType.ACCOUNT_TYPE_GENERAL;
? transfer.toAccountType
: 'ACCOUNT_TYPE_GENERAL';
const toAccountTypeLabel = transfer.fromAccountType
? AccountTypeMapping[toAcct]
? AccountType[toAcct]
: 'Unknown';
return (
@@ -27,9 +27,9 @@ export function TransferRepeat({ recurring }: TransferRepeatProps) {
<div className={wrapperClasses}>
<h2 className={headerClasses}>{t('Active epochs')}</h2>
<div className="relative block rounded-lg py-6 text-center p-6">
<p>
<div>
<EpochOverview id={recurring.startEpoch} />
</p>
</div>
<p className="leading-10 my-2">
<IconForEpoch
start={recurring.startEpoch}
@@ -37,13 +37,13 @@ export function TransferRepeat({ recurring }: TransferRepeatProps) {
current={data?.epoch.id}
/>
</p>
<p>
<div>
{recurring.endEpoch ? (
<EpochOverview id={recurring.endEpoch} />
) : (
<span>{t('Forever')}</span>
)}
</p>
</div>
</div>
</div>
);
@@ -8,7 +8,7 @@ import { DispatchMetricLabels } from '@vegaprotocol/types';
export type Metric = components['schemas']['vegaDispatchMetric'];
export type Strategy = components['schemas']['vegaDispatchStrategy'];
const metricLabels = {
const metricLabels: Record<Metric, string> = {
DISPATCH_METRIC_UNSPECIFIED: 'Unknown metric',
...DispatchMetricLabels,
};
@@ -3,7 +3,7 @@ import { TransferRepeat } from './blocks/transfer-repeat';
import { TransferRewards } from './blocks/transfer-rewards';
import { TransferParticipants } from './blocks/transfer-participants';
export type Recurring = components['schemas']['v1RecurringTransfer'];
export type Recurring = components['schemas']['commandsv1RecurringTransfer'];
export type Metric = components['schemas']['vegaDispatchMetric'];
export const wrapperClasses =
@@ -16,7 +16,7 @@ interface StringMap {
const displayString: StringMap = {
OrderSubmission: 'Order Submission',
'Submit Order': 'Order',
OrderCancellation: 'Order Cancellation',
OrderCancellation: 'Cancel order',
OrderAmendment: 'Order Amendment',
VoteSubmission: 'Vote Submission',
WithdrawSubmission: 'Withdraw Submission',
@@ -44,8 +44,27 @@ const displayString: StringMap = {
ValidatorHeartbeat: 'Heartbeat',
'Validator Heartbeat': 'Heartbeat',
'Batch Market Instructions': 'Batch',
'Stop Orders Submission': 'Stop',
StopOrdersSubmission: 'Stop',
StopOrdersCancellation: 'Cancel stop',
'Stop Orders Cancellation': 'Cancel stop',
};
export function getLabelForOrderType(
orderType: string,
command: components['schemas']['v1InputData']
): string {
if (command.orderSubmission) {
if (command.orderSubmission.peggedOrder) {
return 'Peg';
}
if (command.orderSubmission.icebergOpts) {
return 'Iceberg';
}
}
return 'Order';
}
/**
* Given a proposal, will return a specific label
* @param chainEvent
@@ -117,6 +136,8 @@ export function getLabelForChainEvent(
return t('Signer threshold');
}
return t('Multisig update');
} else if (chainEvent.contractCall) {
return t('Contract call');
}
return t('Chain Event');
}
+398 -72
View File
@@ -3,7 +3,7 @@
* Do not make direct changes to the file.
*/
/** Type helpers */
/** OneOf type helpers */
type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
type XOR<T, U> = T | U extends object
? (Without<T, U> & U) | (Without<U, T> & T)
@@ -41,6 +41,8 @@ export interface paths {
};
}
export type webhooks = Record<string, never>;
export interface components {
schemas: {
/**
@@ -101,6 +103,17 @@ export interface components {
| 'TIME_IN_FORCE_FOK'
| 'TIME_IN_FORCE_GFA'
| 'TIME_IN_FORCE_GFN';
/**
* @description - EXPIRY_STRATEGY_UNSPECIFIED: Never valid
* - EXPIRY_STRATEGY_CANCELS: Stop order should be cancelled if the expiry time is reached.
* - EXPIRY_STRATEGY_SUBMIT: Order should be submitted if the expiry time is reached.
* @default EXPIRY_STRATEGY_UNSPECIFIED
* @enum {string}
*/
readonly StopOrderExpiryStrategy:
| 'EXPIRY_STRATEGY_UNSPECIFIED'
| 'EXPIRY_STRATEGY_CANCELS'
| 'EXPIRY_STRATEGY_SUBMIT';
/**
* @default METHOD_UNSPECIFIED
* @enum {string}
@@ -143,6 +156,36 @@ export interface components {
/** Type of transaction */
readonly type?: string;
};
/** Request for cancelling a recurring transfer */
readonly commandsv1CancelTransfer: {
/** @description Transfer ID of the transfer to cancel. */
readonly transferId?: string;
};
/** Specific details for a one off transfer */
readonly commandsv1OneOffTransfer: {
/**
* Format: int64
* @description Timestamp in Unix nanoseconds for when the transfer should be delivered into the receiver's account.
*/
readonly deliverOn?: string;
};
/** Specific details for a recurring transfer */
readonly commandsv1RecurringTransfer: {
/** @description Optional parameter defining how a transfer is dispatched. */
readonly dispatchStrategy?: components['schemas']['vegaDispatchStrategy'];
/**
* Format: uint64
* @description Last epoch at which this transfer shall be paid.
*/
readonly endEpoch?: string;
/** @description Factor needs to be > 0. */
readonly factor?: string;
/**
* Format: uint64
* @description First epoch from which this transfer shall be paid.
*/
readonly startEpoch?: string;
};
/** Transfer initiated by a party */
readonly commandsv1Transfer: {
/** @description Amount to be taken from the source account. This field is an unsigned integer scaled to the asset's decimal places. */
@@ -154,8 +197,8 @@ export interface components {
* should be taken.
*/
readonly fromAccountType?: components['schemas']['vegaAccountType'];
readonly oneOff?: components['schemas']['v1OneOffTransfer'];
readonly recurring?: components['schemas']['v1RecurringTransfer'];
readonly oneOff?: components['schemas']['commandsv1OneOffTransfer'];
readonly recurring?: components['schemas']['commandsv1RecurringTransfer'];
/** @description Reference to be attached to the transfer. */
readonly reference?: string;
/** @description Public key of the destination account. */
@@ -171,8 +214,19 @@ export interface components {
};
readonly protobufAny: {
readonly '@type'?: string;
[key: string]: unknown | undefined;
[key: string]: unknown;
};
/**
* @description `NullValue` is a singleton enumeration to represent the null value for the
* `Value` type union.
*
* The JSON representation for `NullValue` is JSON `null`.
*
* - NULL_VALUE: Null value.
* @default NULL_VALUE
* @enum {string}
*/
readonly protobufNullValue: 'NULL_VALUE';
/** Used to announce a node as a new pending validator */
readonly v1AnnounceNode: {
/** @description AvatarURL of the validator. */
@@ -225,18 +279,19 @@ export interface components {
readonly amendments?: readonly components['schemas']['v1OrderAmendment'][];
/** @description List of order cancellations to be processed sequentially. */
readonly cancellations?: readonly components['schemas']['v1OrderCancellation'][];
/** @description List of stop order cancellations to be processed sequentially. */
readonly stopOrdersCancellation?: readonly components['schemas']['v1StopOrdersCancellation'][];
/** @description List of stop order submissions to be processed sequentially. */
readonly stopOrdersSubmission?: readonly components['schemas']['v1StopOrdersSubmission'][];
/** @description List of order submissions to be processed sequentially. */
readonly submissions?: readonly components['schemas']['v1OrderSubmission'][];
};
/** Request for cancelling a recurring transfer */
readonly v1CancelTransfer: {
/** @description Transfer ID of the transfer to cancel. */
readonly transferId?: string;
};
/** Event forwarded to the Vega network to provide information on events happening on other networks */
readonly v1ChainEvent: {
/** @description Built-in asset event. */
readonly builtin?: components['schemas']['vegaBuiltinAssetEvent'];
/** Arbitrary contract call */
readonly contractCall?: components['schemas']['vegaEthContractCallEvent'];
/** @description Ethereum ERC20 event. */
readonly erc20?: components['schemas']['vegaERC20Event'];
/** @description Ethereum ERC20 multisig event. */
@@ -301,6 +356,19 @@ export interface components {
/** Transaction corresponding to the hash */
readonly transaction?: components['schemas']['blockexplorerapiv1Transaction'];
};
/** Iceberg order options */
readonly v1IcebergOpts: {
/**
* Format: uint64
* @description Minimum allowed remaining size of the order before it is replenished back to its peak size.
*/
readonly minimumVisibleSize?: string;
/**
* Format: uint64
* @description Size of the order that is made visible and can be traded with during the execution of a single order.
*/
readonly peakSize?: string;
};
readonly v1InfoResponse: {
/** Commit hash from which the data node was built */
readonly commitHash?: string;
@@ -325,7 +393,7 @@ export interface components {
*/
readonly blockHeight?: string;
/** @description Command to request cancelling a recurring transfer. */
readonly cancelTransfer?: components['schemas']['v1CancelTransfer'];
readonly cancelTransfer?: components['schemas']['commandsv1CancelTransfer'];
/**
* @description Command used by a validator to submit an event forwarded to the Vega network to provide information
* on events happening on other networks, to be used by a foreign chain
@@ -381,6 +449,10 @@ export interface components {
readonly protocolUpgradeProposal?: components['schemas']['v1ProtocolUpgradeProposal'];
/** @description Command used by a validator to submit a floating point value. */
readonly stateVariableProposal?: components['schemas']['v1StateVariableProposal'];
/** @description Command to cancel stop orders. */
readonly stopOrdersCancellation?: components['schemas']['v1StopOrdersCancellation'];
/** @description Command to submit a pair of stop orders. */
readonly stopOrdersSubmission?: components['schemas']['v1StopOrdersSubmission'];
/** @description Command to submit a transfer. */
readonly transfer?: components['schemas']['commandsv1Transfer'];
/** @description Command to remove tokens delegated to a validator. */
@@ -448,9 +520,9 @@ export interface components {
readonly commitmentAmount?: string;
/** @description Nominated liquidity fee factor, which is an input to the calculation of taker fees on the market, as per setting fees and rewarding liquidity providers. */
readonly fee?: string;
/** @description Market ID for the order, required field. */
/** @description Market ID for the order. */
readonly marketId?: string;
/** @description Reference to be added to every order created out of this liquidityProvisionSubmission. */
/** @description Reference to be added to every order created out of this liquidity provision submission. */
readonly reference?: string;
/** @description Set of liquidity sell orders to meet the liquidity provision obligation. */
readonly sells?: readonly components['schemas']['vegaLiquidityOrder'][];
@@ -530,15 +602,6 @@ export interface components {
| 'TYPE_STAKE_TOTAL_SUPPLY'
| 'TYPE_SIGNER_THRESHOLD_SET'
| 'TYPE_GOVERNANCE_VALIDATE_ASSET';
/** Specific details for a one off transfer */
readonly v1OneOffTransfer: {
/**
* Format: int64
* @description Unix timestamp in nanoseconds. Time at which the
* transfer should be delivered into the To account.
*/
readonly deliverOn?: string;
};
/** Command to submit new Oracle data from third party providers */
readonly v1OracleDataSubmission: {
/**
@@ -596,10 +659,12 @@ export interface components {
readonly v1OrderSubmission: {
/**
* Format: int64
* @description Timestamp for when the order will expire, in nanoseconds,
* @description Timestamp in Unix nanoseconds for when the order will expire,
* required field only for `Order.TimeInForce`.TIME_IN_FORCE_GTT`.
*/
readonly expiresAt?: string;
/** @description Parameters used to specify an iceberg order. */
readonly icebergOpts?: components['schemas']['v1IcebergOpts'];
/** @description Market ID for the order, required field. */
readonly marketId?: string;
/** @description Used to specify the details for a pegged order. */
@@ -699,23 +764,6 @@ export interface components {
readonly v1PubKey: {
readonly key?: string;
};
/** Specific details for a recurring transfer */
readonly v1RecurringTransfer: {
/** @description Optional parameter defining how a transfer is dispatched. */
readonly dispatchStrategy?: components['schemas']['vegaDispatchStrategy'];
/**
* Format: uint64
* @description Last epoch at which this transfer shall be paid.
*/
readonly endEpoch?: string;
/** @description Factor needs to be > 0. */
readonly factor?: string;
/**
* Format: uint64
* @description First epoch from which this transfer shall be paid.
*/
readonly startEpoch?: string;
};
/**
* @description Signature to authenticate a transaction and to be verified by the Vega
* network.
@@ -732,7 +780,7 @@ export interface components {
readonly version?: number;
};
readonly v1Signer: {
/** In case of an open oracle - Ethereum address will be submitted */
/** @description In case of an open oracle - Ethereum address will be submitted. */
readonly ethAddress?: components['schemas']['v1ETHAddress'];
/**
* @description List of authorized public keys that signed the data for this
@@ -746,6 +794,55 @@ export interface components {
/** @description State value proposal details. */
readonly proposal?: components['schemas']['vegaStateValueProposal'];
};
/** Price and expiry configuration for a stop order */
readonly v1StopOrderSetup: {
/**
* Format: int64
* @description Optional expiry timestamp.
*/
readonly expiresAt?: string;
/** @description Strategy to adopt if the expiry time is reached. */
readonly expiryStrategy?: components['schemas']['StopOrderExpiryStrategy'];
/** @description Order to be submitted once the trigger is breached. */
readonly orderSubmission?: components['schemas']['v1OrderSubmission'];
/** @description Fixed price at which the order will be submitted. */
readonly price?: string;
/** @description Trailing percentage at which the order will be submitted. */
readonly trailingPercentOffset?: string;
};
/**
* Cancel a stop order.
* The following combinations are available:
* Empty object will cancel all stop orders for the party
* Market ID alone will cancel all stop orders in a market
* Market ID and order ID will cancel a specific stop order in a market
* If the stop order is part of an OCO, both stop orders will be cancelled
*/
readonly v1StopOrdersCancellation: {
/** @description Optional market ID. */
readonly marketId?: string;
/** @description Optional order ID. */
readonly stopOrderId?: string;
};
/**
* Stop order submission submits stops orders.
* It is possible to make a single stop order submission by
* specifying a single direction,
* or an OCO (One Cancels the Other) stop order submission
* by specifying a configuration for both directions
*/
readonly v1StopOrdersSubmission: {
/**
* @description Stop order that will be triggered
* if the price falls below a given trigger price.
*/
readonly fallsBelow?: components['schemas']['v1StopOrderSetup'];
/**
* @description Stop order that will be triggered
* if the price rises above a given trigger price.
*/
readonly risesAbove?: components['schemas']['v1StopOrderSetup'];
};
readonly v1UndelegateSubmission: {
/**
* @description Optional, if not specified = ALL.
@@ -822,6 +919,7 @@ export interface components {
* - ACCOUNT_TYPE_REWARD_MAKER_RECEIVED_FEES: Per asset reward account for fees received by makers
* - ACCOUNT_TYPE_REWARD_LP_RECEIVED_FEES: Per asset reward account for fees received by liquidity providers
* - ACCOUNT_TYPE_REWARD_MARKET_PROPOSERS: Per asset reward account for market proposers when the market goes above some trading threshold
* - ACCOUNT_TYPE_HOLDING: Per asset account for holding in-flight unfilled orders' funds
* @default ACCOUNT_TYPE_UNSPECIFIED
* @enum {string}
*/
@@ -842,7 +940,8 @@ export interface components {
| 'ACCOUNT_TYPE_REWARD_MAKER_PAID_FEES'
| 'ACCOUNT_TYPE_REWARD_MAKER_RECEIVED_FEES'
| 'ACCOUNT_TYPE_REWARD_LP_RECEIVED_FEES'
| 'ACCOUNT_TYPE_REWARD_MARKET_PROPOSERS';
| 'ACCOUNT_TYPE_REWARD_MARKET_PROPOSERS'
| 'ACCOUNT_TYPE_HOLDING';
/** Vega representation of an external asset */
readonly vegaAssetDetails: {
/** @description Vega built-in asset. */
@@ -898,6 +997,14 @@ export interface components {
/** @description Vega network internal asset ID. */
readonly vegaAssetId?: string;
};
readonly vegaCancelTransfer: {
/** Configuration for cancellation of a governance-initiated transfer */
readonly changes?: components['schemas']['vegaCancelTransferConfiguration'];
};
readonly vegaCancelTransferConfiguration: {
/** @description ID of the governance transfer proposal. */
readonly transferId?: string;
};
/**
* @description DataSourceDefinition represents the top level object that deals with data sources.
* DataSourceDefinition can be external or internal, with whatever number of data sources are defined
@@ -912,6 +1019,7 @@ export interface components {
* It contains one of any of the defined `SourceType` variants.
*/
readonly vegaDataSourceDefinitionExternal: {
readonly ethCall?: components['schemas']['vegaEthCallSpec'];
readonly oracle?: components['schemas']['vegaDataSourceSpecConfiguration'];
};
/**
@@ -1147,6 +1255,64 @@ export interface components {
/** @description Address into which the bridge will release the funds. */
readonly receiverAddress?: string;
};
/** @description Specifies a data source that derives its content from calling a read method on an Ethereum contract. */
readonly vegaEthCallSpec: {
/** @description The ABI of that contract. */
readonly abi?: readonly Record<string, never>[];
/** @description Ethereum address of the contract to call. */
readonly address?: string;
/**
* @description List of arguments to pass to method call.
* Protobuf 'Value' wraps an arbitrary JSON type that is mapped to an Ethereum type according to the ABI.
*/
readonly args?: readonly Record<string, never>[];
/** @description Name of the method on the contract to call. */
readonly method?: string;
/** @description Conditions for determining when to call the contract method. */
readonly trigger?: components['schemas']['vegaEthCallTrigger'];
};
/** @description Determines when the contract method should be called. */
readonly vegaEthCallTrigger: {
readonly timeTrigger?: components['schemas']['vegaEthTimeTrigger'];
};
/** Result of calling an arbitrary Ethereum contract method */
readonly vegaEthContractCallEvent: {
/**
* Format: uint64
* @description Ethereum block height.
*/
readonly blockHeight?: string;
/**
* Format: uint64
* @description Ethereum block time in Unix seconds.
*/
readonly blockTime?: string;
/**
* Format: byte
* @description Result of contract call, packed according to the ABI stored in the associated data source spec.
*/
readonly result?: string;
/** @description ID of the data source spec that triggered this contract call. */
readonly specId?: string;
};
/** @description Trigger for an Ethereum call based on the Ethereum block timestamp. Can be one-off or repeating. */
readonly vegaEthTimeTrigger: {
/**
* Format: uint64
* @description Repeat the call every n seconds after the inital call. If no time for initial call was specified, begin repeating immediately.
*/
readonly every?: string;
/**
* Format: uint64
* @description Trigger when the Ethereum time is greater or equal to this time, in Unix seconds.
*/
readonly initial?: string;
/**
* Format: uint64
* @description If repeating, stop once Ethereum time is greater than this time, in Unix seconds. If not set, then repeat indefinitely.
*/
readonly until?: string;
};
/** Future product configuration */
readonly vegaFutureProduct: {
/** @description Binding between the data source spec and the settlement data. */
@@ -1160,6 +1326,14 @@ export interface components {
/** @description Asset ID for the product's settlement asset. */
readonly settlementAsset?: string;
};
/**
* @default GOVERNANCE_TRANSFER_TYPE_UNSPECIFIED
* @enum {string}
*/
readonly vegaGovernanceTransferType:
| 'GOVERNANCE_TRANSFER_TYPE_UNSPECIFIED'
| 'GOVERNANCE_TRANSFER_TYPE_ALL_OR_NOTHING'
| 'GOVERNANCE_TRANSFER_TYPE_BEST_EFFORT';
/** Instrument configuration */
readonly vegaInstrumentConfiguration: {
/** @description Instrument code, human-readable shortcode used to describe the instrument. */
@@ -1168,6 +1342,8 @@ export interface components {
readonly future?: components['schemas']['vegaFutureProduct'];
/** @description Instrument name. */
readonly name?: string;
/** @description Spot. */
readonly spot?: components['schemas']['vegaSpotProduct'];
};
readonly vegaKeyValueBundle: {
readonly key?: string;
@@ -1258,14 +1434,14 @@ export interface components {
/** @description Configuration of the new market. */
readonly changes?: components['schemas']['vegaNewMarketConfiguration'];
};
/** Configuration for a new market on Vega */
/** Configuration for a new futures market on Vega */
readonly vegaNewMarketConfiguration: {
/**
* Format: uint64
* @description Decimal places used for the new market, sets the smallest price increment on the book.
* @description Decimal places used for the new futures market, sets the smallest price increment on the book.
*/
readonly decimalPlaces?: string;
/** @description New market instrument configuration. */
/** @description New futures market instrument configuration. */
readonly instrument?: components['schemas']['vegaInstrumentConfiguration'];
/** @description Linear slippage factor is used to cap the slippage component of maintenance margin - it is applied to the slippage volume. */
readonly linearSlippageFactor?: string;
@@ -1278,11 +1454,11 @@ export interface components {
* price levels over which automated liquidity provision orders will be deployed.
*/
readonly lpPriceRange?: string;
/** @description Optional new market metadata, tags. */
/** @description Optional new futures market metadata, tags. */
readonly metadata?: readonly string[];
/**
* Format: int64
* @description Decimal places for order sizes, sets what size the smallest order / position on the market can be.
* @description Decimal places for order sizes, sets what size the smallest order / position on the futures market can be.
*/
readonly positionDecimalPlaces?: string;
/** @description Price monitoring parameters. */
@@ -1291,6 +1467,80 @@ export interface components {
readonly quadraticSlippageFactor?: string;
/** @description Simple risk model parameters, valid only if MODEL_SIMPLE is selected. */
readonly simple?: components['schemas']['vegaSimpleModelParams'];
/** @description Successor configuration. If this proposal is meant to succeed a given market, then this should be set. */
readonly successor?: components['schemas']['vegaSuccessorConfiguration'];
};
/** New spot market on Vega */
readonly vegaNewSpotMarket: {
/** @description Configuration of the new spot market. */
readonly changes?: components['schemas']['vegaNewSpotMarketConfiguration'];
};
/** Configuration for a new spot market on Vega */
readonly vegaNewSpotMarketConfiguration: {
/**
* Format: uint64
* @description Decimal places used for the new spot market, sets the smallest price increment on the book.
*/
readonly decimalPlaces?: string;
/** @description New spot market instrument configuration. */
readonly instrument?: components['schemas']['vegaInstrumentConfiguration'];
/** @description Log normal risk model parameters, valid only if MODEL_LOG_NORMAL is selected. */
readonly logNormal?: components['schemas']['vegaLogNormalRiskModel'];
/** @description Optional new spot market metadata, tags. */
readonly metadata?: readonly string[];
/**
* Format: int64
* @description Decimal places for order sizes, sets what size the smallest order / position on the spot market can be.
*/
readonly positionDecimalPlaces?: string;
/** @description Price monitoring parameters. */
readonly priceMonitoringParameters?: components['schemas']['vegaPriceMonitoringParameters'];
/** @description Simple risk model parameters, valid only if MODEL_SIMPLE is selected. */
readonly simple?: components['schemas']['vegaSimpleModelParams'];
/** @description Specifies parameters related to target stake calculation. */
readonly targetStakeParameters?: components['schemas']['vegaTargetStakeParameters'];
};
/** New governance transfer */
readonly vegaNewTransfer: {
/** @description Configuration for a new transfer. */
readonly changes?: components['schemas']['vegaNewTransferConfiguration'];
};
readonly vegaNewTransferConfiguration: {
/** Maximum amount to transfer */
readonly amount?: string;
/** ID of asset to transfer */
readonly asset?: string;
/**
* Specifies the account to transfer to, depending on the account type:
* Network treasury: leave empty
* Party: party's public key
* Market insurance pool: market ID
*/
readonly destination?: string;
/** Specifies the account type to transfer to: reward pool, party, network insurance pool, market insurance pool */
readonly destinationType?: components['schemas']['vegaAccountType'];
/** Maximum fraction of the source account's balance to transfer as a decimal - i.e. 0.1 = 10% of the balance */
readonly fractionOfBalance?: string;
readonly oneOff?: components['schemas']['vegaOneOffTransfer'];
readonly recurring?: components['schemas']['vegaRecurringTransfer'];
/** If network treasury, field is empty, otherwise uses the market ID */
readonly source?: string;
/** Source account type, such as network treasury, market insurance pool */
readonly sourceType?: components['schemas']['vegaAccountType'];
/**
* "All or nothing" or "best effort":
* All or nothing: Transfers the specified amount or does not transfer anything
* Best effort: Transfers the specified amount or the max allowable amount if this is less than the specified amount
*/
readonly transferType?: components['schemas']['vegaGovernanceTransferType'];
};
/** Specific details for a one off transfer */
readonly vegaOneOffTransfer: {
/**
* Format: int64
* @description Timestamp in Unix nanoseconds for when the transfer should be delivered into the receiver's account.
*/
readonly deliverOn?: string;
};
/**
* Type values for an order
@@ -1369,6 +1619,8 @@ export interface components {
};
/** Terms for a governance proposal on Vega */
readonly vegaProposalTerms: {
/** @description Cancel a governance transfer. */
readonly cancelTransfer?: components['schemas']['vegaCancelTransfer'];
/**
* Format: int64
* @description Timestamp as Unix time in seconds when voting closes for this proposal,
@@ -1388,20 +1640,39 @@ export interface components {
* and can be used to gauge community sentiment.
*/
readonly newFreeform?: components['schemas']['vegaNewFreeform'];
/** @description Proposal change for creating new market on Vega. */
/** @description Proposal change for creating new futures market on Vega. */
readonly newMarket?: components['schemas']['vegaNewMarket'];
/** @description Proposal change for creating new spot market on Vega. */
readonly newSpotMarket?: components['schemas']['vegaNewSpotMarket'];
/** @description Proposal change for a governance transfer. */
readonly newTransfer?: components['schemas']['vegaNewTransfer'];
/** @description Proposal change for updating an asset. */
readonly updateAsset?: components['schemas']['vegaUpdateAsset'];
/** @description Proposal change for modifying an existing market on Vega. */
/** @description Proposal change for modifying an existing futures market on Vega. */
readonly updateMarket?: components['schemas']['vegaUpdateMarket'];
/** @description Proposal change for updating Vega network parameters. */
readonly updateNetworkParameter?: components['schemas']['vegaUpdateNetworkParameter'];
/** @description Proposal change for modifying an existing spot market on Vega. */
readonly updateSpotMarket?: components['schemas']['vegaUpdateSpotMarket'];
/**
* Format: int64
* @description Validation timestamp as Unix time in seconds.
*/
readonly validationTimestamp?: string;
};
/** Specific details for a recurring transfer */
readonly vegaRecurringTransfer: {
/**
* Format: uint64
* @description Last epoch at which this transfer shall be paid.
*/
readonly endEpoch?: string;
/**
* Format: uint64
* @description First epoch from which this transfer shall be paid.
*/
readonly startEpoch?: string;
};
readonly vegaScalarValue: {
readonly value?: string;
};
@@ -1442,6 +1713,15 @@ export interface components {
*/
readonly probabilityOfTrading?: number;
};
/** Spot product configuration */
readonly vegaSpotProduct: {
/** @description Base asset ID. */
readonly baseAsset?: string;
/** @description Product name. */
readonly name?: string;
/** @description Quote asset ID. */
readonly quoteAsset?: string;
};
readonly vegaStakeDeposited: {
/** @description Amount deposited as an unsigned base 10 integer scaled to the asset's decimal places. */
readonly amount?: string;
@@ -1507,6 +1787,13 @@ export interface components {
readonly scalarVal?: components['schemas']['vegaScalarValue'];
readonly vectorVal?: components['schemas']['vegaVectorValue'];
};
/** @description Configuration required to turn a new market proposal in to a successor market proposal. */
readonly vegaSuccessorConfiguration: {
/** @description A decimal value between or equal to 0 and 1, specifying the fraction of the insurance pool balance that is carried over from the parent market to the successor. */
readonly insurancePoolFraction?: string;
/** @description ID of the market that the successor should take over from. */
readonly parentMarketId?: string;
};
/** TargetStakeParameters contains parameters used in target stake calculation */
readonly vegaTargetStakeParameters: {
/**
@@ -1547,14 +1834,14 @@ export interface components {
};
/** Update an existing market on Vega */
readonly vegaUpdateMarket: {
/** @description Updated configuration of the market. */
/** @description Updated configuration of the futures market. */
readonly changes?: components['schemas']['vegaUpdateMarketConfiguration'];
/** @description Market ID the update is for. */
readonly marketId?: string;
};
/** Configuration to update a market on Vega */
/** Configuration to update a futures market on Vega */
readonly vegaUpdateMarketConfiguration: {
/** @description Updated market instrument configuration. */
/** @description Updated futures market instrument configuration. */
readonly instrument?: components['schemas']['vegaUpdateInstrumentConfiguration'];
/** @description Linear slippage factor is used to cap the slippage component of maintenance margin - it is applied to the slippage volume. */
readonly linearSlippageFactor?: string;
@@ -1567,7 +1854,7 @@ export interface components {
* price levels over which automated liquidity provision orders will be deployed.
*/
readonly lpPriceRange?: string;
/** @description Optional market metadata, tags. */
/** @description Optional futures market metadata, tags. */
readonly metadata?: readonly string[];
/** @description Price monitoring parameters. */
readonly priceMonitoringParameters?: components['schemas']['vegaPriceMonitoringParameters'];
@@ -1581,6 +1868,26 @@ export interface components {
/** @description The network parameter to update. */
readonly changes?: components['schemas']['vegaNetworkParameter'];
};
/** Update an existing spot market on Vega */
readonly vegaUpdateSpotMarket: {
/** @description Updated configuration of the spot market. */
readonly changes?: components['schemas']['vegaUpdateSpotMarketConfiguration'];
/** @description Market ID the update is for. */
readonly marketId?: string;
};
/** Configuration to update a spot market on Vega */
readonly vegaUpdateSpotMarketConfiguration: {
/** @description Log normal risk model parameters, valid only if MODEL_LOG_NORMAL is selected. */
readonly logNormal?: components['schemas']['vegaLogNormalRiskModel'];
/** @description Optional spot market metadata, tags. */
readonly metadata?: readonly string[];
/** @description Price monitoring parameters. */
readonly priceMonitoringParameters?: components['schemas']['vegaPriceMonitoringParameters'];
/** @description Simple risk model parameters, valid only if MODEL_SIMPLE is selected. */
readonly simple?: components['schemas']['vegaSimpleModelParams'];
/** @description Specifies parameters related to target stake calculation. */
readonly targetStakeParameters?: components['schemas']['vegaTargetStakeParameters'];
};
readonly vegaVectorValue: {
readonly value?: readonly string[];
};
@@ -1609,12 +1916,12 @@ export interface components {
export type external = Record<string, never>;
export interface operations {
/**
* Info
* @description Get information about the block explorer.
* Response contains a semver formatted version of the data node and the commit hash, from which the block explorer was built
*/
BlockExplorer_Info: {
/**
* Info
* @description Get information about the block explorer.
* Response contains a semver formatted version of the data node and the commit hash, from which the block explorer was built
*/
responses: {
/** @description A successful response. */
200: {
@@ -1630,19 +1937,38 @@ export interface operations {
};
};
};
/**
* List transactions
* @description List transactions from the Vega blockchain
*/
BlockExplorer_ListTransactions: {
/**
* List transactions
* @description List transactions from the Vega blockchain
*/
parameters?: {
/** @description Number of transactions to be returned from the blockchain. */
/** @description Optional cursor to paginate the request. */
/** @description Optional cursor to paginate the request. */
readonly query?: {
parameters: {
query?: {
/**
* @description Number of transactions to be returned from the blockchain.
* This is deprecated, use first and last instead.
*/
limit?: number;
/** @description Optional cursor to paginate the request. */
before?: string;
/** @description Optional cursor to paginate the request. */
after?: string;
/** @description Transaction command types filter, for listing transactions with specified command types. */
cmdTypes?: readonly string[];
/** @description Transaction command types exclusion filter, for listing all the transactions except the ones with specified command types. */
excludeCmdTypes?: readonly string[];
/** @description Party IDs filter, can be sender or receiver. */
parties?: readonly string[];
/**
* @description Number of transactions to be returned from the blockchain. Use in conjunction with the `after` cursor to paginate forwards.
* On its own, this will return the first `first` transactions.
*/
first?: number;
/**
* @description Number of transactions to be returned from the blockchain. Use in conjunction with the `before` cursor to paginate backwards.
* On its own, this will return the last `last` transactions.
*/
last?: number;
};
};
responses: {
@@ -1660,14 +1986,14 @@ export interface operations {
};
};
};
/**
* Get transaction
* @description Get a transaction from the Vega blockchain
*/
BlockExplorer_GetTransaction: {
/**
* Get transaction
* @description Get a transaction from the Vega blockchain
*/
parameters: {
/** @description Hash of the transaction */
readonly path: {
path: {
/** @description Hash of the transaction */
hash: string;
};
};
+1
View File
@@ -15,5 +15,6 @@ module.exports = composePlugins(withNx(), withReact(), (config) => {
return {
...config,
plugins: [...additionalPlugins, ...config.plugins],
ignoreWarnings: [/Failed to parse source map/],
};
});
@@ -295,7 +295,6 @@ context(
// Will fail if run after 'Able to submit update market proposal and vote for proposal'
// 3002-PROP-022
// Skipping due to #4262
it.skip('Unable to submit update market proposal without equity-like share in the market', function () {
switchVegaWalletPubKey();
stakingPageAssociateTokens('1');
@@ -13,12 +13,6 @@ export const VegaWalletDialogs = () => {
<>
<VegaConnectDialog
connectors={Connectors}
onChangeOpen={(open) =>
appDispatch({
type: AppStateActionType.SET_VEGA_WALLET_OVERLAY,
isOpen: open,
})
}
riskMessage={<RiskMessage />}
/>
@@ -2,15 +2,18 @@ import {
RestConnector,
JsonRpcConnector,
ViewConnector,
InjectedConnector,
} from '@vegaprotocol/wallet';
const urlParams = new URLSearchParams(window.location.search);
export const rest = new RestConnector();
export const jsonRpc = new JsonRpcConnector();
export const injected = new InjectedConnector();
export const view = new ViewConnector(urlParams.get('address'));
export const Connectors = {
injected,
rest,
jsonRpc,
view,
@@ -8,9 +8,10 @@ import { TxState } from '../../../hooks/transaction-reducer';
import { useTransaction } from '../../../hooks/use-transaction';
import { BigNumber } from '../../../lib/bignumber';
import { AssociateInfo } from './associate-info';
import { removeDecimal, toBigNum } from '@vegaprotocol/utils';
import { toBigNum } from '@vegaprotocol/utils';
import type { EthereumConfig } from '@vegaprotocol/web3';
import { useBalances } from '../../../lib/balances/balances-store';
import { MaxUint256 } from '@ethersproject/constants';
export const WalletAssociate = ({
perform,
@@ -42,7 +43,7 @@ export const WalletAssociate = ({
} = useTransaction(() => {
return token.approve(
ethereumConfig.staking_bridge_contract.address,
removeDecimal('1000000', decimals).toString()
MaxUint256.toString()
);
});
+1
View File
@@ -14,5 +14,6 @@ module.exports = composePlugins(withNx(), withReact(), (config, context) => {
return {
...config,
plugins: [...additionalPlugins, ...config.plugins],
ignoreWarnings: [/Failed to parse source map/],
};
});
+1 -1
View File
@@ -14,4 +14,4 @@ NX_ANNOUNCEMENTS_CONFIG_URL=https://raw.githubusercontent.com/vegaprotocol/annou
NX_VEGA_INCIDENT_URL=https://blog.vega.xyz/tagged/vega-incident-reports
NX_VEGA_CONSOLE_URL=https://console.vega.xyz
# TAG name of the current app version - TODO: bump to the latest upon release
NX_APP_VERSION=v0.20.19-core-0.71.6
NX_APP_VERSION=v0.20.23-core-0.71.6
+2 -2
View File
@@ -11,7 +11,7 @@ cp .env.[environment] .env.local
Starting the app:
```bash
yarn nx serve explorer
yarn nx serve trading
```
### Configuration
@@ -26,7 +26,7 @@ Example configurations are provided here:
For convenience, you can boot the app injecting one of the configurations above by running:
```bash
yarn env-cmd -f .\apps\token\.env.{env} yarn nx run token:serve # e.g. stagnet1
yarn env-cmd -f .\apps\trading\.env.{env} yarn nx run trading:serve # e.g. stagnet1
```
There are a few different configuration options offered for this app:
@@ -316,7 +316,7 @@ export const TradeGrid = ({ market, pinnedAsset }: TradeGridProps) => {
<div className="border-b border-default min-w-0">
<HeaderStats market={market} />
</div>
<div className="col-span-2 bg-vega-green">
<div className="col-span-2">
<OracleBanner marketId={market?.id || ''} />
</div>
{sidebarOpen && (
+3
View File
@@ -2,10 +2,12 @@ import {
RestConnector,
JsonRpcConnector,
ViewConnector,
InjectedConnector,
} from '@vegaprotocol/wallet';
export const rest = new RestConnector();
export const jsonRpc = new JsonRpcConnector();
export const injected = new InjectedConnector();
let view: ViewConnector;
if (typeof window !== 'undefined') {
@@ -16,6 +18,7 @@ if (typeof window !== 'undefined') {
}
export const Connectors = {
injected,
rest,
jsonRpc,
view,
+22 -14
View File
@@ -48,30 +48,38 @@ html [data-theme='light'] {
html [data-theme='light'] {
/* candles */
--pennant-color-buy-fill: theme('colors.market.green.500');
--pennant-color-buy-stroke: theme('colors.market.green.600');
--pennant-color-buy-fill: theme(colors.market.green.500);
--pennant-color-buy-stroke: theme(colors.market.green.600);
/* sell uses stroke for fill and stroke */
--pennant-color-sell-stroke: theme(colors.market.red.500);
/* depth chart */
--pennant-color-depth-buy-fill: theme('colors.market.green.500');
--pennant-color-depth-buy-stroke: theme('colors.market.green.600');
--pennant-color-depth-sell-fill: theme('colors.market.red.500');
--pennant-color-depth-sell-stroke: theme('colors.market.red.600');
--pennant-color-depth-buy-fill: theme(colors.market.green.500);
--pennant-color-depth-buy-stroke: theme(colors.market.green.600);
--pennant-color-depth-sell-fill: theme(colors.market.red.500);
--pennant-color-depth-sell-stroke: theme(colors.market.red.600);
--pennant-color-volume-buy: theme('colors.market.green.500');
--pennant-color-volume-buy: theme(colors.market.green.400);
--pennant-color-volume-sell: theme(colors.market.red.400);
}
html [data-theme='dark'] {
/* candles */
--pennant-color-buy-fill: theme('colors.market.green.600');
--pennant-color-buy-stroke: theme('colors.market.green.500');
--pennant-color-buy-fill: theme(colors.market.green.600);
--pennant-color-buy-stroke: theme(colors.market.green.500);
/* sell uses stroke for fill and stroke */
--pennant-color-sell-stroke: theme(colors.market.red.500);
/* depth chart */
--pennant-color-depth-buy-fill: theme('colors.market.green.600');
--pennant-color-depth-buy-stroke: theme('colors.market.green.500');
--pennant-color-depth-sell-fill: theme('colors.market.red.600');
--pennant-color-depth-sell-stroke: theme('colors.market.red.500');
--pennant-color-depth-buy-fill: theme(colors.market.green.600);
--pennant-color-depth-buy-stroke: theme(colors.market.green.500);
--pennant-color-depth-sell-fill: theme(colors.market.red.600);
--pennant-color-depth-sell-stroke: theme(colors.market.red.500);
--pennant-color-volume-buy: theme('colors.market.green.600');
--pennant-color-volume-buy: theme(colors.market.green.600);
--pennant-color-volume-sell: theme(colors.market.red.600);
}
/* AG GRID - Do not edit without updating other global stylesheets for each app */
+1 -1
View File
@@ -33,7 +33,7 @@ const colorClass = (percentageUsed: number, neutral = false) => {
return classNames('text-right', {
'text-neutral-500 dark:text-neutral-400': percentageUsed < 75 && !neutral,
'text-vega-orange': percentageUsed >= 75 && percentageUsed < 90,
'text-vega-pink': percentageUsed >= 90,
'text-vega-red': percentageUsed >= 90,
});
};
@@ -189,7 +189,7 @@ export const MarginHealthChart = ({
>
<div
data-testid="margin-health-chart-red"
className="bg-vega-pink-550"
className="bg-vega-red-550"
style={{
height: '100%',
width: `${red * 100}%`,
@@ -1,17 +1,24 @@
import { t } from '@vegaprotocol/i18n';
import type { ButtonVariant } from '@vegaprotocol/ui-toolkit';
import { Button } from '@vegaprotocol/ui-toolkit';
import { Side } from '@vegaprotocol/types';
import classNames from 'classnames';
interface Props {
variant: ButtonVariant;
side: Side;
}
export const DealTicketButton = ({ variant }: Props) => {
export const DealTicketButton = ({ side }: Props) => {
const buttonClasses = classNames(
'px-10 py-2 uppercase rounded-md text-white w-full',
{
'bg-market-red-500': side === Side.SIDE_SELL,
'bg-market-green-550': side === Side.SIDE_BUY,
}
);
return (
<div className="mb-2">
<Button variant={variant} fill type="submit" data-testid="place-order">
<button type="submit" data-testid="place-order" className={buttonClasses}>
{t('Place order')}
</Button>
</button>
</div>
);
};
@@ -476,11 +476,7 @@ export const DealTicket = ({
pubKey={pubKey}
onClickCollateral={onClickCollateral}
/>
<DealTicketButton
variant={
order.side === Schema.Side.SIDE_BUY ? 'ternary' : 'secondary'
}
/>
<DealTicketButton side={order.side} />
<DealTicketFeeDetails
onMarketClick={onMarketClick}
feeEstimate={feeEstimate}
+2 -2
View File
@@ -28,8 +28,8 @@ const CumulationBar = ({
className={classNames(
'absolute top-0 left-0 h-full transition-all',
type === VolumeType.bid
? 'bg-market-green/20 dark:bg-market-green/50'
: 'bg-market-red/20 dark:bg-market-red/30'
? 'bg-market-green-300 dark:bg-market-green/50'
: 'bg-market-red-300 dark:bg-market-red/30'
)}
style={{
width: `${cumulativeValue}%`,
@@ -104,7 +104,7 @@ export const OracleBasicProfile = ({
'text-vega-blue': intent === Intent.Primary,
'text-vega-green dark:text-vega-green': intent === Intent.Success,
'text-yellow-600 dark:text-yellow': intent === Intent.Warning,
'text-vega-pink': intent === Intent.Danger,
'text-vega-red': intent === Intent.Danger,
},
'flex items-start align-text-bottom p-1'
)}
@@ -40,7 +40,7 @@ export const OracleProfileTitle = ({ provider }: { provider: Provider }) => {
'text-vega-blue': intent === Intent.Primary,
'text-vega-green dark:text-vega-green': intent === Intent.Success,
'text-yellow-600 dark:text-yellow': intent === Intent.Warning,
'text-vega-pink': intent === Intent.Danger,
'text-vega-red': intent === Intent.Danger,
},
'flex items-start align-text-bottom p-1'
)}
@@ -6,6 +6,7 @@ import type { Position } from './positions-data-providers';
import * as Schema from '@vegaprotocol/types';
import { PositionStatus, PositionStatusMapping } from '@vegaprotocol/types';
import type { ICellRendererParams } from 'ag-grid-community';
import { addDecimalsFormatNumber } from '@vegaprotocol/utils';
jest.mock('./liquidation-price', () => ({
LiquidationPrice: () => (
@@ -19,7 +20,7 @@ const singleRow: Position = {
assetSymbol: 'BTC',
averageEntryPrice: '133',
currentLeverage: 1.1,
decimals: 2,
decimals: 2, // this is settlementAsset.decimals
quantum: '0.1',
lossSocializationAmount: '0',
marginAccountBalance: '12345600',
@@ -177,12 +178,22 @@ it('displays allocated margin', async () => {
});
it('displays realised and unrealised PNL', async () => {
// pnl cells should be rendered with asset dps
const expectedRealised = addDecimalsFormatNumber(
singleRow.realisedPNL,
singleRow.decimals
);
const expectedUnrealised = addDecimalsFormatNumber(
singleRow.unrealisedPNL,
singleRow.decimals
);
await act(async () => {
render(<PositionsTable rowData={singleRowData} isReadOnly={false} />);
});
const cells = screen.getAllByRole('gridcell');
expect(cells[9].textContent).toEqual('12.3');
expect(cells[10].textContent).toEqual('45.6');
expect(cells[9].textContent).toEqual(expectedRealised);
expect(cells[10].textContent).toEqual(expectedUnrealised);
});
it('displays close button', async () => {
+4 -16
View File
@@ -365,20 +365,14 @@ export const PositionsTable = forwardRef<AgGridReact, Props>(
valueGetter: ({ data }: VegaValueGetterParams<Position>) => {
return !data
? undefined
: toBigNum(
data.realisedPNL,
data.marketDecimalPlaces
).toNumber();
: toBigNum(data.realisedPNL, data.decimals).toNumber();
},
valueFormatter: ({
data,
}: VegaValueFormatterParams<Position, 'realisedPNL'>) => {
return !data
? ''
: addDecimalsFormatNumber(
data.realisedPNL,
data.marketDecimalPlaces
);
: addDecimalsFormatNumber(data.realisedPNL, data.decimals);
},
headerTooltip: t(
'Profit or loss is realised whenever your position is reduced to zero and the margin is released back to your collateral balance. P&L excludes any fees paid.'
@@ -396,20 +390,14 @@ export const PositionsTable = forwardRef<AgGridReact, Props>(
valueGetter: ({ data }: VegaValueGetterParams<Position>) => {
return !data
? undefined
: toBigNum(
data.unrealisedPNL,
data.marketDecimalPlaces
).toNumber();
: toBigNum(data.unrealisedPNL, data.decimals).toNumber();
},
valueFormatter: ({
data,
}: VegaValueFormatterParams<Position, 'unrealisedPNL'>) =>
!data
? ''
: addDecimalsFormatNumber(
data.unrealisedPNL,
data.marketDecimalPlaces
),
: addDecimalsFormatNumber(data.unrealisedPNL, data.decimals),
headerTooltip: t(
'Unrealised profit is the current profit on your open position. Margin is still allocated to your position.'
),
+4
View File
@@ -21,6 +21,8 @@ module.exports = {
550: '#B3002E',
DEFAULT: '#EC003C',
500: '#EC003C',
400: '#F57382',
300: '#FDD9DC',
},
green: {
// same as vega-green
@@ -29,6 +31,8 @@ module.exports = {
550: '#01C566',
DEFAULT: '#00F780',
500: '#00F780',
400: '#74BE8E',
300: '#DDFEE8',
},
},
vega: {
@@ -0,0 +1,7 @@
export const IconChevronLeft = ({ size = 16 }: { size: number }) => {
return (
<svg width={size} height={size} viewBox="0 0 16 16">
<path d="M10.38 1.62L11.13 2.38L5.5 8L11.13 13.62L10.38 14.38L4 8L10.38 1.62Z" />
</svg>
);
};
@@ -2,6 +2,7 @@ import { IconArrowDown } from './svg-icons/icon-arrow-down';
import { IconArrowRight } from './svg-icons/icon-arrow-right';
import { IconBreakdown } from './svg-icons/icon-breakdown';
import { IconChevronDown } from './svg-icons/icon-chevron-down';
import { IconChevronLeft } from './svg-icons/icon-chevron-left';
import { IconChevronUp } from './svg-icons/icon-chevron-up';
import { IconCopy } from './svg-icons/icon-copy';
import { IconCross } from './svg-icons/icon-cross';
@@ -26,6 +27,7 @@ export enum VegaIconNames {
ARROW_RIGHT = 'arrow-right',
BREAKDOWN = 'breakdown',
CHEVRON_DOWN = 'chevron-down',
CHEVRON_LEFT = 'chevron-left',
CHEVRON_UP = 'chevron-up',
COPY = 'copy',
CROSS = 'cross',
@@ -53,6 +55,7 @@ export const VegaIconNameMap: Record<
'arrow-down': IconArrowDown,
'arrow-right': IconArrowRight,
'chevron-down': IconChevronDown,
'chevron-left': IconChevronLeft,
'chevron-up': IconChevronUp,
'open-external': IconOpenExternal,
'question-mark': IconQuestionMark,
@@ -25,7 +25,7 @@ export const NotificationBanner = ({
'bg-vega-green-300 dark:bg-vega-green-700': intent === Intent.Success,
'bg-vega-orange-300 dark:bg-vega-orange-700':
intent === Intent.Warning,
'bg-vega-pink-300 dark:bg-vega-pink-700': intent === Intent.Danger,
'bg-vega-red-300 dark:bg-vega-red-700': intent === Intent.Danger,
},
{
'border-b-vega-light-200 dark:border-b-vega-dark-200 ':
@@ -40,7 +40,7 @@ export const NotificationBanner = ({
'border-b-vega-orange-500 dark:border-b-vega-orange-500':
intent === Intent.Warning,
'border-b-vega-pink-500 dark:border-b-vega-pink-500':
'border-b-vega-red-500 dark:border-b-vega-red-500':
intent === Intent.Danger,
}
)}
@@ -59,7 +59,7 @@ export const NotificationBanner = ({
'text-vega-orange-500 dark:text-vega-orange-500':
intent === Intent.Warning,
'text-vega-pink-500 dark:text-vega-pink-500':
'text-vega-red-500 dark:text-vega-red-500':
intent === Intent.Danger,
})}
/>
@@ -38,14 +38,12 @@ export const Toggle = ({
'relative inline-flex w-full h-full text-center items-center justify-center',
'peer-checked:rounded-full',
{
'peer-checked:bg-neutral-400 dark:peer-checked:bg-white dark:peer-checked:text-black':
'peer-checked:bg-neutral-400 dark:peer-checked:bg-white peer-checked:text-white dark:peer-checked:text-black':
type === 'primary',
'dark:peer-checked:bg-vega-green peer-checked:bg-vega-green-550':
'peer-checked:bg-market-green-550 peer-checked:text-white':
type === 'buy',
'dark:peer-checked:bg-vega-pink peer-checked:bg-vega-pink-550':
type === 'sell',
'peer-checked:bg-market-red-500 peer-checked:text-white': type === 'sell',
},
'peer-checked:text-white dark:peer-checked:text-black',
'cursor-pointer peer-checked:cursor-auto select-none',
{
'px-10 py-2': size === 'lg',
@@ -1,7 +1,10 @@
import { DocsLinks, ExternalLinks } from '@vegaprotocol/environment';
import { t } from '@vegaprotocol/i18n';
import { Link } from '@vegaprotocol/ui-toolkit';
import classNames from 'classnames';
import type { ReactNode } from 'react';
import type { VegaConnector } from '../connectors';
import { RestConnector } from '../connectors';
export const ConnectDialogTitle = ({ children }: { children: ReactNode }) => {
return (
@@ -18,11 +21,35 @@ export const ConnectDialogContent = ({ children }: { children: ReactNode }) => {
return <div>{children}</div>;
};
export const ConnectDialogFooter = ({ children }: { children?: ReactNode }) => {
export const ConnectDialogFooter = ({
connector,
}: {
connector: VegaConnector | undefined;
}) => {
const wrapperClasses = classNames(
'flex justify-center gap-4',
'px-4 md:px-8 pt-4 md:pt-6',
'border-t border-vega-light-200 dark:border-vega-dark-200',
'text-vega-light-400 dark:text-vega-dark-400'
);
const isHostedWalletSelected = connector instanceof RestConnector;
return (
<footer className="flex justify-center gap-4 px-4 md:px-8 pt-4 md:pt-6 -mx-4 md:-mx-8 border-t border-neutral-500 text-neutral-500 dark:text-neutral-400 mt-6">
{children ? (
children
<footer className={wrapperClasses}>
{isHostedWalletSelected ? (
<p className="text-center">
{t('For demo purposes get a ')}
<Link
href={ExternalLinks.VEGA_WALLET_HOSTED_URL}
target="_blank"
rel="noreferrer"
>
{t('hosted wallet')}
</Link>
{t(', or for the real experience create a wallet in the ')}
<Link href={ExternalLinks.VEGA_WALLET_URL}>
{t('Vega wallet app')}
</Link>
</p>
) : (
<>
<Link href={ExternalLinks.VEGA_WALLET_URL}>
@@ -16,6 +16,7 @@ import {
import type { VegaConnectDialogProps } from '..';
import {
ClientErrors,
InjectedConnector,
JsonRpcConnector,
RestConnector,
ViewConnector,
@@ -24,6 +25,12 @@ import {
import { useEnvironment } from '@vegaprotocol/environment';
import type { ChainIdQuery } from './__generated__/ChainId';
import { ChainIdDocument } from './__generated__/ChainId';
import {
mockBrowserWallet,
clearBrowserWallet,
delayedReject,
delayedResolve,
} from '../test-helpers';
const mockUpdateDialogOpen = jest.fn();
const mockCloseVegaDialog = jest.fn();
@@ -49,10 +56,12 @@ const INITIAL_KEY = 'some-key';
const rest = new RestConnector();
const jsonRpc = new JsonRpcConnector();
const view = new ViewConnector(INITIAL_KEY);
const injected = new InjectedConnector();
const connectors = {
rest,
jsonRpc,
view,
injected,
};
beforeEach(() => {
jest.clearAllMocks();
@@ -105,7 +114,7 @@ describe('VegaConnectDialog', () => {
expect(screen.getByTestId('connector-jsonRpc')).toHaveTextContent(
'Connect Vega wallet'
);
expect(screen.getByTestId('connector-hosted')).toHaveTextContent(
expect(screen.getByTestId('connector-rest')).toHaveTextContent(
'Hosted Fairground wallet'
);
expect(screen.getByTestId('connector-view')).toHaveTextContent(
@@ -113,6 +122,17 @@ describe('VegaConnectDialog', () => {
);
});
it('displays browser wallet option if detected on window object', async () => {
mockBrowserWallet();
render(generateJSX());
const list = await screen.findByTestId('connectors-list');
expect(list.children).toHaveLength(4);
expect(screen.getByTestId('connector-injected')).toHaveTextContent(
'Connect Web wallet'
);
clearBrowserWallet();
});
describe('RestConnector', () => {
it('connects', async () => {
const spy = jest
@@ -229,17 +249,19 @@ describe('VegaConnectDialog', () => {
beforeEach(() => {
spyOnCheckCompat = jest
.spyOn(connectors.jsonRpc, 'checkCompat')
.mockImplementation(() => delayedResolve(true));
.mockImplementation(() => delayedResolve(true, delay));
spyOnGetChainId = jest
.spyOn(connectors.jsonRpc, 'getChainId')
.mockImplementation(() => delayedResolve({ chainID: mockChainId }));
.mockImplementation(() =>
delayedResolve({ chainID: mockChainId }, delay)
);
spyOnConnectWallet = jest
.spyOn(connectors.jsonRpc, 'connectWallet')
.mockImplementation(() => delayedResolve(null));
.mockImplementation(() => delayedResolve(null, delay));
spyOnConnect = jest
.spyOn(connectors.jsonRpc, 'connect')
.mockImplementation(() =>
delayedResolve([{ publicKey: 'pubkey', name: 'test key 1' }])
delayedResolve([{ publicKey: 'pubkey', name: 'test key 1' }], delay)
);
});
@@ -351,18 +373,6 @@ describe('VegaConnectDialog', () => {
expect(screen.getByText('An unknown error occurred')).toBeInTheDocument();
});
function delayedResolve<T>(result: T): Promise<T> {
return new Promise((resolve) => {
setTimeout(() => resolve(result), delay);
});
}
function delayedReject<T>(result: T): Promise<T> {
return new Promise((_, reject) => {
setTimeout(() => reject(result), delay);
});
}
async function selectJsonRpc() {
expect(await screen.findByRole('dialog')).toBeInTheDocument();
fireEvent.click(await screen.findByTestId('connector-jsonRpc'));
@@ -439,4 +449,109 @@ describe('VegaConnectDialog', () => {
});
});
});
describe('InjectedConnector', () => {
beforeAll(() => {
jest.useFakeTimers();
});
afterAll(() => {
jest.useRealTimers();
localStorage.clear();
});
afterEach(() => {
clearBrowserWallet();
});
it('connects', async () => {
const delay = 100;
const vegaWindow = {
getChainId: jest.fn(() =>
delayedResolve({ chainID: mockChainId }, delay)
),
connectWallet: jest.fn(() => delayedResolve(null, delay)),
disconnectWallet: jest.fn(() => delayedResolve(undefined, delay)),
listKeys: jest.fn(() =>
delayedResolve(
{
keys: [{ name: 'test key', publicKey: '0x123' }],
},
100
)
),
};
mockBrowserWallet(vegaWindow);
render(generateJSX());
await selectInjected();
// Chain check
expect(screen.getByText('Verifying chain')).toBeInTheDocument();
expect(vegaWindow.getChainId).toHaveBeenCalled();
await act(async () => {
jest.advanceTimersByTime(delay);
});
// Await user connect
expect(screen.getByText('Connecting...')).toBeInTheDocument();
expect(vegaWindow.connectWallet).toHaveBeenCalled();
await act(async () => {
jest.advanceTimersByTime(delay);
});
// Connect (list keys)
expect(vegaWindow.listKeys).toHaveBeenCalled();
await act(async () => {
jest.advanceTimersByTime(delay);
});
expect(screen.getByText('Successfully connected')).toBeInTheDocument();
await act(async () => {
jest.advanceTimersByTime(CLOSE_DELAY);
});
expect(mockCloseVegaDialog).toHaveBeenCalledWith();
});
it('handles invalid chain', async () => {
const delay = 100;
const invalidChain = 'invalid chain';
const vegaWindow = {
getChainId: jest.fn(() =>
delayedResolve({ chainID: invalidChain }, delay)
),
connectWallet: jest.fn(() => delayedResolve(null, delay)),
disconnectWallet: jest.fn(() => delayedResolve(undefined, delay)),
listKeys: jest.fn(() =>
delayedResolve(
{
keys: [{ name: 'test key', publicKey: '0x123' }],
},
100
)
),
};
mockBrowserWallet(vegaWindow);
render(generateJSX());
await selectInjected();
// Chain check
expect(screen.getByText('Verifying chain')).toBeInTheDocument();
expect(vegaWindow.getChainId).toHaveBeenCalled();
await act(async () => {
jest.advanceTimersByTime(delay);
});
expect(screen.getByText('Wrong network')).toBeInTheDocument();
expect(
screen.getByText(
new RegExp(`set your wallet network in your app to "${mockChainId}"`)
)
).toBeInTheDocument();
});
async function selectInjected() {
expect(await screen.findByRole('dialog')).toBeInTheDocument();
fireEvent.click(await screen.findByTestId('connector-injected'));
}
});
});
+150 -187
View File
@@ -3,45 +3,50 @@ import {
Button,
Dialog,
FormGroup,
Icon,
Input,
Link,
Loader,
VegaIcon,
VegaIconNames,
} from '@vegaprotocol/ui-toolkit';
import { useCallback, useState } from 'react';
import type { WalletClientError } from '@vegaprotocol/wallet-client';
import { t } from '@vegaprotocol/i18n';
import type { VegaConnector } from '../connectors';
import { InjectedConnector } from '../connectors';
import { ViewConnector } from '../connectors';
import { JsonRpcConnector, RestConnector } from '../connectors';
import { RestConnectorForm } from './rest-connector-form';
import { JsonRpcConnectorForm } from './json-rpc-connector-form';
import {
Networks,
useEnvironment,
ExternalLinks,
} from '@vegaprotocol/environment';
import { Networks, useEnvironment } from '@vegaprotocol/environment';
import {
ConnectDialogContent,
ConnectDialogFooter,
ConnectDialogTitle,
} from './connect-dialog-elements';
import type { Status } from '../use-json-rpc-connect';
import type { Status as JsonRpcStatus } from '../use-json-rpc-connect';
import type { Status as InjectedStatus } from '../use-injected-connector';
import { useJsonRpcConnect } from '../use-json-rpc-connect';
import { ViewConnectorForm } from './view-connector-form';
import { useChainIdQuery } from './__generated__/ChainId';
import { useVegaWallet } from '../use-vega-wallet';
import { useInjectedConnector } from '../use-injected-connector';
import { InjectedConnectorForm } from './injected-connector-form';
export const CLOSE_DELAY = 1700;
type Connectors = { [key: string]: VegaConnector };
type WalletType = 'jsonRpc' | 'hosted' | 'view';
export type WalletType = 'injected' | 'jsonRpc' | 'rest' | 'view';
export interface VegaConnectDialogProps {
connectors: Connectors;
onChangeOpen?: (open: boolean) => void;
riskMessage?: React.ReactNode;
}
export interface VegaWalletDialogStore {
vegaWalletDialogOpen: boolean;
updateVegaWalletDialog: (open: boolean) => void;
openVegaWalletDialog: () => void;
closeVegaWalletDialog: () => void;
}
export const useVegaWalletDialogStore = create<VegaWalletDialogStore>()(
(set) => ({
vegaWalletDialogOpen: false,
@@ -52,32 +57,20 @@ export const useVegaWalletDialogStore = create<VegaWalletDialogStore>()(
})
);
export interface VegaWalletDialogStore {
vegaWalletDialogOpen: boolean;
updateVegaWalletDialog: (open: boolean) => void;
openVegaWalletDialog: () => void;
closeVegaWalletDialog: () => void;
}
export const VegaConnectDialog = ({
connectors,
onChangeOpen,
riskMessage,
}: VegaConnectDialogProps) => {
const { disconnect, acknowledgeNeeded } = useVegaWallet();
const vegaWalletDialogOpen = useVegaWalletDialogStore(
(store) => store.vegaWalletDialogOpen
);
const updateVegaWalletDialog = useVegaWalletDialogStore(
(store) => (open: boolean) => {
store.updateVegaWalletDialog(open);
onChangeOpen?.(open);
}
);
const closeVegaWalletDialog = useVegaWalletDialogStore((store) => () => {
store.closeVegaWalletDialog();
onChangeOpen?.(false);
});
const { disconnect, acknowledgeNeeded } = useVegaWallet();
const onVegaWalletDialogChange = useCallback(
(open: boolean) => {
updateVegaWalletDialog(open);
@@ -88,41 +81,9 @@ export const VegaConnectDialog = ({
[updateVegaWalletDialog, acknowledgeNeeded, disconnect]
);
const { data, error, loading } = useChainIdQuery();
const renderContent = () => {
if (error) {
return (
<ConnectDialogContent>
<ConnectDialogTitle>
{t('Could not retrieve chain id')}
</ConnectDialogTitle>
<ConnectDialogFooter />
</ConnectDialogContent>
);
}
if (loading || !data) {
return (
<ConnectDialogContent>
<ConnectDialogTitle>{t('Fetching chain ID')}</ConnectDialogTitle>
<div className="flex justify-center items-center my-6">
<Loader />
</div>
<ConnectDialogFooter />
</ConnectDialogContent>
);
}
return (
<ConnectDialogContainer
connectors={connectors}
closeDialog={closeVegaWalletDialog}
appChainId={data.statistics.chainId}
riskMessage={riskMessage}
/>
);
};
// Ensure we have a chain Id so we can compare with wallet chain id.
// This value will already be in the cache, if it failed the app wont render
const { data } = useChainIdQuery();
return (
<Dialog
@@ -130,29 +91,35 @@ export const VegaConnectDialog = ({
size="small"
onChange={onVegaWalletDialogChange}
>
{renderContent()}
{data && (
<ConnectDialogContainer
connectors={connectors}
appChainId={data.statistics.chainId}
riskMessage={riskMessage}
/>
)}
</Dialog>
);
};
const ConnectDialogContainer = ({
connectors,
closeDialog,
appChainId,
riskMessage,
}: {
connectors: Connectors;
closeDialog: () => void;
appChainId: string;
riskMessage?: React.ReactNode;
}) => {
const { VEGA_WALLET_URL, VEGA_ENV, HOSTED_WALLET_URL } = useEnvironment();
const closeDialog = useVegaWalletDialogStore(
(store) => store.closeVegaWalletDialog
);
const [selectedConnector, setSelectedConnector] = useState<VegaConnector>();
const [walletUrl, setWalletUrl] = useState(VEGA_WALLET_URL || '');
const [walletType, setWalletType] = useState<WalletType>();
const reset = useCallback(() => {
setSelectedConnector(undefined);
setWalletType(undefined);
}, []);
const delayedOnConnect = useCallback(() => {
@@ -161,52 +128,59 @@ const ConnectDialogContainer = ({
}, CLOSE_DELAY);
}, [closeDialog]);
const { connect, ...jsonRpcState } = useJsonRpcConnect(delayedOnConnect);
const { connect: jsonRpcConnect, ...jsonRpcState } =
useJsonRpcConnect(delayedOnConnect);
const { connect: injectedConnect, ...injectedState } =
useInjectedConnector(delayedOnConnect);
const handleSelect = (type: WalletType, isHosted = false) => {
let connector;
const handleSelect = (type: WalletType) => {
const connector = connectors[type];
if (isHosted) {
// If the user has selected hosted wallet ensure that we are connecting to https://vega-hosted-wallet.on.fleek.co/
// otherwise use the default walletUrl or what has been put in the input
connector = connectors['rest'];
connector.url = HOSTED_WALLET_URL || walletUrl;
} else {
connector = connectors[type];
connector.url = walletUrl;
}
// If type is rest user has selected the hosted wallet option. So here
// we ensure that we are connecting to https://vega-hosted-wallet.on.fleek.co/
// otherwise use walletUrl which defaults to the localhost:1789
connector.url = type === 'rest' ? HOSTED_WALLET_URL : walletUrl;
if (!connector) {
// we should never get here unless connectors are not configured correctly
throw new Error(`Connector type: ${type} not configured`);
}
setSelectedConnector(connector);
setWalletType(type);
// Immediately connect on selection if jsonRpc is selected, we can't do this
// for rest because we need to show an authentication form
if (connector instanceof JsonRpcConnector) {
connect(connector, appChainId);
jsonRpcConnect(connector, appChainId);
} else if (connector instanceof InjectedConnector) {
injectedConnect(connector, appChainId);
}
};
return selectedConnector !== undefined && walletType !== undefined ? (
<SelectedForm
type={walletType}
connector={selectedConnector}
jsonRpcState={jsonRpcState}
onConnect={closeDialog}
appChainId={appChainId}
reset={reset}
riskMessage={riskMessage}
/>
) : (
<ConnectorList
walletUrl={walletUrl}
setWalletUrl={setWalletUrl}
onSelect={handleSelect}
isMainnet={VEGA_ENV === Networks.MAINNET}
/>
return (
<>
<ConnectDialogContent>
{selectedConnector !== undefined ? (
<SelectedForm
connector={selectedConnector}
jsonRpcState={jsonRpcState}
injectedState={injectedState}
onConnect={closeDialog}
appChainId={appChainId}
reset={reset}
riskMessage={riskMessage}
/>
) : (
<ConnectorList
walletUrl={walletUrl}
setWalletUrl={setWalletUrl}
onSelect={handleSelect}
isMainnet={VEGA_ENV === Networks.MAINNET}
/>
)}
</ConnectDialogContent>
<ConnectDialogFooter connector={selectedConnector} />
</>
);
};
@@ -216,136 +190,129 @@ const ConnectorList = ({
setWalletUrl,
isMainnet,
}: {
onSelect: (type: WalletType, isHosted?: boolean) => void;
onSelect: (type: WalletType) => void;
walletUrl: string;
setWalletUrl: (value: string) => void;
isMainnet: boolean;
}) => {
return (
<>
<ConnectDialogContent>
<ConnectDialogTitle>{t('Connect')}</ConnectDialogTitle>
<CustomUrlInput walletUrl={walletUrl} setWalletUrl={setWalletUrl} />
<ul data-testid="connectors-list" className="mb-6">
<ConnectDialogTitle>{t('Connect')}</ConnectDialogTitle>
<CustomUrlInput walletUrl={walletUrl} setWalletUrl={setWalletUrl} />
<ul data-testid="connectors-list" className="mb-6">
<li className="mb-4 last:mb-0">
<ConnectionOption
type="jsonRpc"
text={t('Connect Vega wallet')}
onClick={() => onSelect('jsonRpc')}
/>
</li>
{'vega' in window && (
<li className="mb-4 last:mb-0">
<ConnectionOption
type="jsonRpc"
text={t('Connect Vega wallet')}
onClick={() => onSelect('jsonRpc')}
type="injected"
text={t('Connect Web wallet')}
onClick={() => onSelect('injected')}
/>
</li>
{!isMainnet && (
<li className="mb-4 last:mb-0">
<ConnectionOption
type="hosted"
text={t('Hosted Fairground wallet')}
onClick={() => onSelect('hosted', true)}
/>
</li>
)}
)}
{!isMainnet && (
<li className="mb-4 last:mb-0">
<div className="my-4 text-center text-vega-dark-400">{t('OR')}</div>
<ConnectionOption
type="view"
text={t('View as vega user')}
onClick={() => onSelect('view')}
type="rest"
text={t('Hosted Fairground wallet')}
onClick={() => onSelect('rest')}
/>
</li>
</ul>
</ConnectDialogContent>
<ConnectDialogFooter />
)}
<li className="mb-4 last:mb-0">
<div className="my-4 text-center">{t('OR')}</div>
<ConnectionOption
type="view"
text={t('View as vega user')}
onClick={() => onSelect('view')}
/>
</li>
</ul>
</>
);
};
const SelectedForm = ({
type,
connector,
appChainId,
jsonRpcState,
injectedState,
reset,
onConnect,
riskMessage,
}: {
type: WalletType;
connector: VegaConnector;
appChainId: string;
jsonRpcState: {
status: Status;
status: JsonRpcStatus;
error: WalletClientError | null;
};
injectedState: {
status: InjectedStatus;
error: Error | null;
};
reset: () => void;
onConnect: () => void;
riskMessage?: React.ReactNode;
}) => {
if (connector instanceof InjectedConnector) {
return (
<InjectedConnectorForm
status={injectedState.status}
error={injectedState.error}
onConnect={onConnect}
appChainId={appChainId}
reset={reset}
riskMessage={riskMessage}
/>
);
}
if (connector instanceof RestConnector) {
return (
<>
<ConnectDialogContent>
<button
onClick={reset}
className="absolute p-2 top-0 left-0 md:top-2 md:left-2"
data-testid="back-button"
>
<Icon name={'chevron-left'} ariaLabel="back" size={4} />
</button>
<ConnectDialogTitle>{t('Connect')}</ConnectDialogTitle>
<div className="mb-2">
<RestConnectorForm connector={connector} onConnect={onConnect} />
</div>
</ConnectDialogContent>
{type === 'hosted' ? (
<ConnectDialogFooter>
<p className="text-center">
{t('For demo purposes get a ')}
<Link
href={ExternalLinks.VEGA_WALLET_HOSTED_URL}
target="_blank"
rel="noreferrer"
>
{t('hosted wallet')}
</Link>
{t(', or for the real experience create a wallet in the ')}
<Link href={ExternalLinks.VEGA_WALLET_URL}>
{t('Vega wallet app')}
</Link>
</p>
</ConnectDialogFooter>
) : (
<ConnectDialogFooter />
)}
<button
onClick={reset}
className="absolute p-2 top-0 left-0 md:top-2 md:left-2"
data-testid="back-button"
>
<VegaIcon name={VegaIconNames.CHEVRON_LEFT} />
</button>
<ConnectDialogTitle>{t('Connect')}</ConnectDialogTitle>
<div className="mb-2">
<RestConnectorForm connector={connector} onConnect={onConnect} />
</div>
</>
);
}
if (connector instanceof JsonRpcConnector) {
return (
<ConnectDialogContent>
<JsonRpcConnectorForm
connector={connector}
status={jsonRpcState.status}
error={jsonRpcState.error}
onConnect={onConnect}
appChainId={appChainId}
reset={reset}
riskMessage={riskMessage}
/>
</ConnectDialogContent>
<JsonRpcConnectorForm
connector={connector}
status={jsonRpcState.status}
error={jsonRpcState.error}
onConnect={onConnect}
appChainId={appChainId}
reset={reset}
riskMessage={riskMessage}
/>
);
}
if (connector instanceof ViewConnector) {
return (
<>
<ConnectDialogContent>
<ViewConnectorForm
connector={connector}
onConnect={onConnect}
reset={reset}
/>
</ConnectDialogContent>
<ConnectDialogFooter />
</>
<ViewConnectorForm
connector={connector}
onConnect={onConnect}
reset={reset}
/>
);
}
@@ -366,12 +333,12 @@ const ConnectionOption = ({
onClick={onClick}
size="lg"
fill={true}
variant={['hosted', 'view'].includes(type) ? 'default' : 'primary'}
variant={['rest', 'view'].includes(type) ? 'default' : 'primary'}
data-testid={`connector-${type}`}
>
<span className="-mx-6 flex text-left justify-between items-center">
<span className="-mx-10 flex text-left justify-between items-center">
{text}
<Icon name="chevron-right" />
<VegaIcon name={VegaIconNames.ARROW_RIGHT} />
</span>
</Button>
);
@@ -387,9 +354,7 @@ const CustomUrlInput = ({
const [urlInputExpanded, setUrlInputExpanded] = useState(false);
return urlInputExpanded ? (
<>
<p className="mb-2 text-neutral-600 dark:text-neutral-400">
{t('Custom wallet location')}
</p>
<p className="mb-2">{t('Custom wallet location')}</p>
<FormGroup
labelFor="wallet-url"
label={t('Custom wallet location')}
@@ -401,12 +366,10 @@ const CustomUrlInput = ({
name="wallet-url"
/>
</FormGroup>
<p className="mb-2 text-neutral-600 dark:text-neutral-400">
{t('Choose wallet app to connect')}
</p>
<p className="mb-2">{t('Choose wallet app to connect')}</p>
</>
) : (
<p className="mb-6 text-neutral-600 dark:text-neutral-400">
<p className="mb-6">
{t(
'Choose wallet app to connect, or to change port or server URL enter a '
)}
@@ -0,0 +1,153 @@
import { t } from '@vegaprotocol/i18n';
import { Status } from '../use-injected-connector';
import { ConnectDialogTitle } from './connect-dialog-elements';
import type { ReactNode } from 'react';
import {
Button,
ButtonLink,
Diamond,
Loader,
Tick,
} from '@vegaprotocol/ui-toolkit';
import { setAcknowledged } from '../storage';
import { useVegaWallet } from '../use-vega-wallet';
export const InjectedConnectorForm = ({
status,
onConnect,
riskMessage,
appChainId,
reset,
error,
}: {
// connector: JsonRpcConnector;
appChainId: string;
status: Status;
error: Error | null;
onConnect: () => void;
reset: () => void;
riskMessage?: React.ReactNode;
}) => {
const { disconnect } = useVegaWallet();
if (status === Status.Idle) {
return null;
}
if (status === Status.Error) {
return <Error error={error} appChainId={appChainId} onTryAgain={reset} />;
}
if (status === Status.GettingChainId) {
return (
<>
<ConnectDialogTitle>{t('Verifying chain')}</ConnectDialogTitle>
<Center>
<Loader />
</Center>
</>
);
}
if (status === Status.Connected) {
return (
<>
<ConnectDialogTitle>{t('Successfully connected')}</ConnectDialogTitle>
<Center>
<Tick />
</Center>
</>
);
}
if (status === Status.Connecting) {
return (
<>
<ConnectDialogTitle>{t('Connecting...')}</ConnectDialogTitle>
<Center>
<Diamond />
</Center>
<p className="text-center">
{t(
"Approve the connection from your Vega wallet app. If you have multiple wallets you'll need to choose which to connect with."
)}
</p>
</>
);
}
if (status === Status.AcknowledgeNeeded) {
const setConnection = () => {
setAcknowledged();
onConnect();
};
const handleDisagree = () => {
disconnect();
onConnect(); // this is dialog closing
};
return (
<>
<ConnectDialogTitle>{t('Understand the risk')}</ConnectDialogTitle>
{riskMessage}
<div className="grid grid-cols-2 gap-5">
<div>
<Button onClick={handleDisagree} fill>
{t('Cancel')}
</Button>
</div>
<div>
<Button onClick={setConnection} variant="primary" fill>
{t('I agree')}
</Button>
</div>
</div>
</>
);
}
return null;
};
const Center = ({ children }: { children: ReactNode }) => {
return (
<div className="flex justify-center items-center my-6">{children}</div>
);
};
const Error = ({
error,
appChainId,
onTryAgain,
}: {
error: Error | null;
appChainId: string;
onTryAgain: () => void;
}) => {
let title = t('Something went wrong');
let text: ReactNode | undefined = t('An unknown error occurred');
const tryAgain: ReactNode | null = (
<p className="text-center">
<ButtonLink onClick={onTryAgain}>{t('Try again')}</ButtonLink>
</p>
);
if (error) {
if (error.message === 'Invalid chain') {
title = t('Wrong network');
text = t(
'To complete your wallet connection, set your wallet network in your app to "%s".',
appChainId
);
} else if (error.message === 'window.vega not found') {
title = t('No wallet detected');
text = t('Vega browser extension not installed');
}
}
return (
<>
<ConnectDialogTitle>{title}</ConnectDialogTitle>
<p className="text-center mb-2 first-letter:uppercase">{text}</p>
{tryAgain}
</>
);
};
@@ -1,21 +1,83 @@
import type { VegaConnector } from './vega-connector';
import { clearConfig, setConfig } from '../storage';
import type { Transaction, VegaConnector } from './vega-connector';
declare global {
interface Vega {
getChainId: () => Promise<{ chainID: string }>;
connectWallet: () => Promise<null>;
disconnectWallet: () => Promise<void>;
listKeys: () => Promise<{
keys: Array<{ name: string; publicKey: string }>;
}>;
sendTransaction: (params: {
publicKey: string;
transaction: Transaction;
sendingMode: 'TYPE_SYNC';
}) => Promise<{
receivedAt: string;
sentAt: string;
transaction: {
from: {
pubKey: string;
};
inputData: string;
pow: {
tid: string;
nonce: string;
};
signature: {
algo: string;
value: string;
version: number;
};
version: number;
};
transactionHash: string;
}>;
}
interface Window {
vega: Vega;
}
}
/**
* Dummy injected connector that we may use when browser wallet is implemented
*/
export class InjectedConnector implements VegaConnector {
description = 'Connects using the Vega wallet browser extension';
async getChainId() {
return window.vega.getChainId();
}
connectWallet() {
return window.vega.connectWallet();
}
async connect() {
return [{ publicKey: '0x123', name: 'text key' }];
const res = await window.vega.listKeys();
setConfig({
connector: 'injected',
token: null, // no token required for injected
url: null, // no url for injected
});
return res.keys;
}
async disconnect() {
return;
disconnect() {
clearConfig();
return window.vega.disconnectWallet();
}
// @ts-ignore injected connector is not implemented
sendTx() {
throw new Error('Not implemented');
async sendTx(pubKey: string, transaction: Transaction) {
const result = await window.vega.sendTransaction({
publicKey: pubKey,
transaction,
sendingMode: 'TYPE_SYNC' as const,
});
return {
transactionHash: result.transactionHash,
receivedAt: result.receivedAt,
sentAt: result.sentAt,
signature: result.transaction.signature.value,
};
}
}
+5 -1
View File
@@ -47,6 +47,10 @@ export interface OrderSubmission {
expiresAt?: string;
postOnly?: boolean;
reduceOnly?: boolean;
icebergOpts?: {
peakSize: string;
minimumVisibleSize: string;
};
}
export interface OrderCancellation {
@@ -411,7 +415,7 @@ export interface PubKey {
}
export interface VegaConnector {
url: string | null;
url?: string | null;
/** Connect to wallet and return keys */
connect(): Promise<PubKey[] | null>;
-1
View File
@@ -106,7 +106,6 @@ export const VegaWalletProvider = ({ children }: VegaWalletProviderProps) => {
if (!connector.current) {
throw new Error('No connector');
}
return connector.current.sendTx(pubkey, transaction);
}, []);
+1 -1
View File
@@ -2,7 +2,7 @@ import { LocalStorage } from '@vegaprotocol/utils';
interface ConnectorConfig {
token: string | null;
connector: 'rest' | 'jsonRpc' | 'view';
connector: 'injected' | 'rest' | 'jsonRpc' | 'view';
url: string | null;
}
+39
View File
@@ -0,0 +1,39 @@
export function mockBrowserWallet(overrides?: Partial<Vega>) {
const vega: Vega = {
getChainId: jest.fn().mockReturnValue(Promise.resolve({ chainID: '1' })),
connectWallet: jest.fn().mockReturnValue(Promise.resolve(null)),
disconnectWallet: jest.fn().mockReturnValue(Promise.resolve()),
listKeys: jest
.fn()
.mockReturnValue({ keys: [{ name: 'test key', publicKey: '0x123' }] }),
sendTransaction: jest.fn().mockReturnValue({
code: 1,
data: '',
height: '1',
log: '',
success: true,
txHash: '0x123',
}),
...overrides,
};
// @ts-ignore globalThis has no index signature
globalThis.vega = vega;
return vega;
}
export function clearBrowserWallet() {
// @ts-ignore no index signature on globalThis
delete globalThis['vega'];
}
export function delayedResolve<T>(result: T, delay = 0): Promise<T> {
return new Promise((resolve) => {
setTimeout(() => resolve(result), delay);
});
}
export function delayedReject<T>(result: T, delay = 0): Promise<T> {
return new Promise((_, reject) => {
setTimeout(() => reject(result), delay);
});
}
+8 -1
View File
@@ -31,7 +31,14 @@ export function useEagerConnect(Connectors: {
return;
}
try {
await connect(Connectors[cfg.connector]);
if (cfg.connector === 'injected') {
const injectedInstance = Connectors[cfg.connector];
// @ts-ignore only injected wallet has connectWallet method
await injectedInstance.connectWallet();
await connect(injectedInstance);
} else {
await connect(Connectors[cfg.connector]);
}
} catch {
console.warn(`Failed to connect with connector: ${cfg.connector}`);
} finally {
@@ -0,0 +1,104 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import { Status, useInjectedConnector } from './use-injected-connector';
import type { ReactNode } from 'react';
import { VegaWalletProvider } from './provider';
import { InjectedConnector } from './connectors';
import { mockBrowserWallet } from './test-helpers';
import { useEnvironment } from '@vegaprotocol/environment';
import { Networks } from '@vegaprotocol/environment';
jest.mock('@vegaprotocol/environment');
const setup = (callback = jest.fn()) => {
const wrapper = ({ children }: { children: ReactNode }) => (
<VegaWalletProvider>{children}</VegaWalletProvider>
);
return renderHook(() => useInjectedConnector(callback), { wrapper });
};
const injected = new InjectedConnector();
describe('useInjectedConnector', () => {
beforeEach(() => {
// @ts-ignore useEnvironment has been mocked
useEnvironment.mockImplementation(() => ({ VEGA_ENV: Networks.TESTNET }));
});
it('attempts connection', async () => {
const { result } = setup();
expect(typeof result.current.connect).toBe('function');
expect(result.current.status).toBe(Status.Idle);
expect(result.current.error).toBe(null);
});
it('errors if vega not injected', async () => {
const { result } = setup();
await act(async () => {
result.current.connect(injected, '1');
});
expect(result.current.error?.message).toBe('window.vega not found');
expect(result.current.status).toBe(Status.Error);
});
it('errors if chain ids dont match', async () => {
mockBrowserWallet();
const { result } = setup();
await act(async () => {
result.current.connect(injected, '2'); // default mock chainId is '1'
});
expect(result.current.error?.message).toBe('Invalid chain');
expect(result.current.status).toBe(Status.Error);
});
it('errors if connection throws', async () => {
const callback = jest.fn();
mockBrowserWallet({
getChainId: () => Promise.reject('failed'),
});
const { result } = setup(callback);
await act(async () => {
result.current.connect(injected, '1'); // default mock chainId is '1'
});
expect(result.current.status).toBe(Status.Error);
expect(result.current.error?.message).toBe('injected connection failed');
});
it('connects', async () => {
const callback = jest.fn();
const vega = mockBrowserWallet();
const { result } = setup(callback);
act(() => {
result.current.connect(injected, '1'); // default mock chainId is '1'
});
expect(result.current.status).toBe(Status.GettingChainId);
await waitFor(() => {
expect(vega.connectWallet).toHaveBeenCalled();
expect(vega.listKeys).toHaveBeenCalled();
});
expect(result.current.status).toBe(Status.Connected);
expect(callback).toHaveBeenCalled();
});
it('connects when aknowledgement required', async () => {
const callback = jest.fn();
// @ts-ignore useEnvironment has been mocked
useEnvironment.mockImplementation(() => ({ VEGA_ENV: Networks.MAINNET }));
const vega = mockBrowserWallet();
const { result } = setup(callback);
act(() => {
result.current.connect(injected, '1'); // default mock chainId is '1'
});
await waitFor(() => {
expect(vega.listKeys).toHaveBeenCalled();
});
expect(result.current.status).toBe(Status.AcknowledgeNeeded);
expect(callback).not.toHaveBeenCalled();
});
});
+61
View File
@@ -0,0 +1,61 @@
import { useCallback, useState } from 'react';
import type { InjectedConnector } from './connectors';
import { useVegaWallet } from './use-vega-wallet';
export enum Status {
Idle = 'Idle',
GettingChainId = 'GettingChainId',
Connecting = 'Connecting',
Connected = 'Connected',
Error = 'Error',
AcknowledgeNeeded = 'AcknowledgeNeeded',
}
export const useInjectedConnector = (onConnect: () => void) => {
const { connect, acknowledgeNeeded } = useVegaWallet();
const [status, setStatus] = useState(Status.Idle);
const [error, setError] = useState<Error | null>(null);
const attemptConnect = useCallback(
async (connector: InjectedConnector, appChainId: string) => {
try {
if (!('vega' in window)) {
throw new Error('window.vega not found');
}
setStatus(Status.GettingChainId);
const { chainID } = await connector.getChainId();
if (chainID !== appChainId) {
throw new Error('Invalid chain');
}
setStatus(Status.Connecting);
await connector.connectWallet(); // authorize wallet
await connect(connector); // connect with keys
if (acknowledgeNeeded) {
setStatus(Status.AcknowledgeNeeded);
} else {
setStatus(Status.Connected);
onConnect();
}
} catch (err) {
if (err instanceof Error) {
setError(err);
} else {
setError(new Error('injected connection failed'));
}
setStatus(Status.Error);
}
},
[acknowledgeNeeded, connect, onConnect]
);
return {
status,
error,
connect: attemptConnect,
};
};
-1
View File
@@ -11,7 +11,6 @@ export enum Status {
GettingChainId = 'GettingChainId',
Connecting = 'Connecting',
GettingPerms = 'GettingPerms',
ListingKeys = 'ListingKeys',
Connected = 'Connected',
Error = 'Error',
AcknowledgeNeeded = 'AcknowledgeNeeded',
+110
View File
@@ -0,0 +1,110 @@
from os import environ
from subprocess import check_output
from argparse import ArgumentParser
import json
projects = []
projects_e2e = []
previews = {
'governance': 'not deployed',
'explorer': 'not deployed',
'trading': 'not deployed',
'tools': 'not deployed',
}
main_apps = ['governance', 'explorer', 'trading']
preview_governance="not deployed"
preview_trading="not deployed"
preview_explorer="not deployed"
preview_tools="not deployed"
# take input from the pipeline
parser = ArgumentParser()
# let's generate slug from bash spell for now
parser.add_argument('--branch-slug', help='slug of branch')
parser.add_argument('--github-ref', help='current github ref')
parser.add_argument('--event-name', help='name of event in CI')
args = parser.parse_args()
# run yarn affected command
affected=check_output(f'yarn nx print-affected --base={environ["NX_BASE"]} --head={environ["NX_HEAD"]} --select=projects'.split()).decode('utf-8')
# print useful information
print(">>>> debug")
print(f"NX_BASE: { environ['NX_BASE'] }")
print(f"NX_HEAD: { environ['NX_HEAD'] }")
print(f"Branch slug: {args.branch_slug}")
print(f"Current ref: {args.github_ref}")
print(">> Affected output")
print(affected)
print(">>>> eof debug")
# define affection actions -> add to projects arrays and generate preview link
def affect_app(app, preview_name=None):
print(f"{app} is affected")
projects.append(app)
if not preview_name:
preview_name=app
previews[app] = f'https://{preview_name}.{args.branch_slug}.vega.rocks'
# check appearance in the affected string for main apps
for app in main_apps:
if app in affected:
affect_app(app)
# if non of main apps is affected - test all of them
if not projects:
for app in main_apps:
affect_app(app)
# generate e2e targets
projects_e2e = [f'{app}-e2e' for app in projects]
# check affection for multisig-signer which is deployed only from develop and pull requests
if args.event_name == 'pull_request' or 'develop' in args.github_ref:
if 'multisig-signer' in affected:
affect_app('multisig-signer', 'tools')
# now parse apps that are deployed from develop but don't have previews
if 'develop' in args.github_ref:
for app in ['static', 'ui-toolkit']:
if app in affected:
projects.append(app)
# if ref is in format release/{env}-{app} then only {app} is deployed
if 'release' in args.github_ref:
for app in main_apps:
if f'{args.github_ref}'.endswith(app):
projects = [app]
projects_e2e = [f'{app}-e2e']
projects = json.dumps(projects)
projects_e2e = json.dumps(projects_e2e)
print(f'Projects: {projects}')
print(f'Projects E2E: {projects_e2e}')
print('>> Previews')
for preview, preview_value in previews.items():
print(f'{preview}: {preview_value}')
print('>> EOF Previews')
lines_to_write = [
f'PREVIEW_GOVERNANCE={previews["governance"]}',
f'PREVIEW_EXPLORER={previews["explorer"]}',
f'PREVIEW_TRADING={previews["trading"]}',
f'PREVIEW_TOOLS={previews["tools"]}',
f'PROJECTS={projects}',
f'PROJECTS_E2E={projects_e2e}',
]
env_file = environ['GITHUB_ENV']
print(f'Line to add to GITHUB_ENV file: {env_file}')
print(lines_to_write)
with open(env_file, 'a') as _f:
_f.write('\n'.join(lines_to_write))
+66
View File
@@ -0,0 +1,66 @@
from argparse import ArgumentParser
from os import environ
# take input from the pipeline
parser = ArgumentParser()
# let's generate slug from bash spell for now
parser.add_argument('--github-ref', help='current github ref')
parser.add_argument('--app', help='current app')
args = parser.parse_args()
env_name = ''
domain = 'vega.rocks'
bucket_name = ''
if 'release/' in args.github_ref:
if 'mainnet-mirror' in args.github_ref:
env_name = 'mainnet-mirror'
if 'validators-testnet' in args.github_ref:
env_name = 'validators-testnet'
else:
# remove prefixing release/ and take the first string limited by - which is supposed to be name of the environment for releasing (format: release/testnet-trading)
env_name = args.github_ref.replace('refs/heads/release/', '').split('-')[0]
elif 'develop' in args.github_ref:
env_name = 'stagnet1'
apps_deployed_from_develop_to_mainnet = {
'multisig-signer' :'tools.vega.xyz',
'static': 'static.vega.xyz',
'ui-toolkit' : 'ui.vega.rocks',
}
if args.app in apps_deployed_from_develop_to_mainnet:
env_name = 'mainnet'
bucket_name = apps_deployed_from_develop_to_mainnet[args.app]
# endswith to avoid confusion with mirror env
elif args.github_ref.endswith('mainnet'):
env_name = 'mainnet'
other_domains_to_deploy = {
'mainnet': 'vega.xyz',
'testnet': 'fairground.wtf',
}
if env_name in other_domains_to_deploy:
domain = other_domains_to_deploy[env_name]
if not bucket_name:
bucket_name = f'{args.app}.{domain}'
# testing envs on vega.rocks contain env_name in the url not like testnet / mainnet
if not bucket_name:
bucket_name = f'{args.app}.{env_name}.{domain}'
print(f'env name: {env_name}')
print(f'domain: {domain}')
print(f'bucket name: {bucket_name}')
lines_to_write = [
f'ENV_NAME={env_name}',
f'BUCKET_NAME={bucket_name}',
]
env_file = environ['GITHUB_ENV']
print(f'Line to add to GITHUB_ENV file: {env_file}')
print(lines_to_write)
with open(env_file, 'a') as _f:
_f.write('\n'.join(lines_to_write))