All files / app/utils/validators btc-address-validator.ts

0% Statements 0/21
0% Branches 0/10
0% Functions 0/2
0% Lines 0/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37                                                                         
import { SUPPORTED_BTC_ADDRESS_FORMATS } from '@constants/index';
import { isMainnet, isTestnet } from '@utils/network-utils';
import { validate, getAddressInfo } from 'bitcoin-address-validation';
import * as yup from 'yup';
 
export function btcAddressSchema() {
  return yup
    .string()
    .defined(`Enter the BTC address where you'd like to receive your rewards`)
    .test({
      name: 'valid address',
      message: `The BTC address you've entered is not valid`,
      test(value: unknown) {
        Iif (typeof value !== 'string') return false;
        const isValid = validate(value);
        Iif (!isValid) return this.createError({ message: 'Invalid BTC address' });
        const addressInfo = getAddressInfo(value);
        Iif (!addressInfo) return this.createError({ message: 'Invalid BTC address' });
        Iif (isMainnet() && addressInfo.network === 'testnet') {
          return this.createError({ message: 'Testnet addresses not supported on Mainnet' });
        }
        Iif (isTestnet() && addressInfo.network !== 'testnet') {
          return this.createError({ message: 'Mainnet addresses not supported on Testnet' });
        }
        // https://github.com/blockstack/stacks-blockchain/issues/1902
        // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
        Iif (!SUPPORTED_BTC_ADDRESS_FORMATS.includes(addressInfo.type as any)) {
          return this.createError({
            message:
              'Unsupported address type. Please use a legacy (P2PKH), pay to script hash (P2SH), native segwit (P2WPKH) or taproot (P2TR) address',
          });
        }
        return true;
      },
    });
}