name: Starknet contract
on:
  pull_request:
    paths:
      - target_chains/starknet/contracts/**
  push:
    branches:
      - main
jobs:
  check:
    name: Starknet Foundry tests
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: target_chains/starknet/contracts/
    steps:
      - uses: actions/checkout@v3
      - name: Install Scarb
        uses: software-mansion/setup-scarb@v1
        with:
          tool-versions: target_chains/starknet/contracts/.tool-versions
      - name: Install Starknet Foundry
        uses: foundry-rs/setup-snfoundry@v3
        with:
          tool-versions: target_chains/starknet/contracts/.tool-versions
      - name: Install Starkli
        run: curl https://get.starkli.sh | sh && . ~/.config/.starkli/env && starkliup -v $(awk '/starkli/{print $2}' .tool-versions)
      - uses: actions-rust-lang/setup-rust-toolchain@v1
      - name: Install Devnet
        # it doesn't build with more recent Rust versions
        run: cargo +1.85.0 install starknet-devnet --version $(awk '/starknet-devnet/{print $2}' .tool-versions)
      - name: Check formatting
        run: scarb fmt --check
      - name: Run tests
        run: snforge test
      - name: Build contracts
        run: scarb build
      - name: Check ABI files
        run: |
          cat target/dev/pyth_pyth.contract_class.json | jq .abi > /tmp/pyth.json
          cat target/dev/pyth_ERC20Upgradeable.contract_class.json | jq .abi > /tmp/erc20.json
          if ! cmp --silent /tmp/pyth.json ../sdk/js/src/abi/pyth.json ; then
            >&2 echo ABI file mismatch for sdk/js/src/abi/pyth.json
            exit 1
          fi
          if ! cmp --silent /tmp/erc20.json ../sdk/js/src/abi/erc20.json ; then
            >&2 echo ABI file mismatch for sdk/js/src/abi/erc20.json
            exit 1
          fi
      - name: Test local deployment script
        run: bash -c 'starknet-devnet --seed 0 --account-class cairo1 & . ~/.config/.starkli/env && deploy/deploy.sh'
      - name: Verify version
        run: |
          version1=$(grep version Scarb.toml | cut -d '"' -f 2)
          version2=$(grep -A1 "fn version" src/pyth.cairo | grep "'" | cut -d "'" -f 2)
          if [ "${version1}" != "${version2}" ]; then
            >&2 echo Version mismatch in Scarb.toml and src/pyth.cairo
            exit 1
          fi
