chore: Prettier refactor, update, add CI check (#4950)

* chore: remove redundant prettier, gitignore files

* fix: Fix missign html opening tag

* chore: upgrade prettier

* chore(ci): Add prettier check to CI

* chore(eslint): turn off prettier-eslint

* chore: fix formatting of translations

* chore: run prettier over whole codebase
This commit is contained in:
Daniel Suchý
2022-02-17 18:15:59 +01:00
committed by GitHub
parent 3ab45ba3df
commit 6253be3f9f
184 changed files with 14138 additions and 1424 deletions

View File

@@ -112,7 +112,8 @@ module.exports = {
'@typescript-eslint/explicit-member-accessibility': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'react/destructuring-assignment': 'off',
'prettier/prettier': 'error',
'prettier/prettier': 'off',
'func-names': 'off',
'react/require-default-props': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
// We use this syntax

View File

@@ -4,22 +4,23 @@ about: Something does not work as expected.
title: ''
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**Info:**
- Remembered Wallet: yes/no
- Suite Version: app/web, commit
- Browser: name, version
- OS: name, version
- Bridge: version
- Firmware Version: model, version/commit
- Remembered Wallet: yes/no
- Suite Version: app/web, commit
- Browser: name, version
- OS: name, version
- Bridge: version
- Firmware Version: model, version/commit
**How to reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'

View File

@@ -4,5 +4,4 @@ about: Issues related to refactoring, dependencies, code improvements etc.
title: ''
labels: code
assignees: ''
---

View File

@@ -4,7 +4,6 @@ about: New product feature ready for development.
title: ''
labels: product
assignees: ''
---
**Design:** [Figma](TODO)

View File

@@ -17,6 +17,8 @@ jobs:
run: npx yarn-deduplicate --list --fail
- name: install deps
run: yarn
- name: check code formatting
run: yarn format:verify
- name: build libs
run: yarn build:libs
- name: type check

View File

@@ -7,7 +7,7 @@
"trailingComma": "all",
"tabWidth": 4,
"useTabs": false,
"jsxBracketSameLine": false,
"bracketSameLine": false,
"overrides": [
{
"files": ["*.yml"],
@@ -15,6 +15,12 @@
"tabWidth": 2,
"singleQuote": false
}
},
{
"files": ["packages/suite-data/files/translations/*.json"],
"options": {
"tabWidth": 2
}
}
]
}

11
.vscode/launch.json vendored
View File

@@ -10,17 +10,12 @@
"args": [],
"cwd": "${workspaceRoot}/packages/suite-desktop/dist",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",
"runtimeArgs": [
"--enable-logging",
"--remote-debugging-port=9223"
],
"runtimeArgs": ["--enable-logging", "--remote-debugging-port=9223"],
"env": {},
"sourceMaps": true,
"outFiles": [
"${workspaceRoot}/packages/suite-desktop/dist/**/*.js"
],
"outFiles": ["${workspaceRoot}/packages/suite-desktop/dist/**/*.js"],
"preLaunchTask": "desktop:dev",
"postDebugTask": "end-tasks"
}
]
}
}

106
.vscode/tasks.json vendored
View File

@@ -1,54 +1,54 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "end-tasks",
"command": "echo ${input:terminate}",
"type": "shell",
"problemMatcher": []
},
{
"label": "desktop:dev",
"dependsOn": [ "desktop:dev:prepare", "desktop:dev:local" ]
},
{
"label": "desktop:dev:prepare",
"type": "npm",
"script": "dev:prepare",
"path": "packages/suite-desktop/",
"problemMatcher": []
},
{
"label": "desktop:dev:local",
"type": "npm",
"script": "dev:local",
"path": "packages/suite-desktop/",
"isBackground": true,
"problemMatcher": {
"owner": "node",
"fileLocation": "relative",
"pattern": {
"regexp": "^(err|warn|info) - (.*)$",
"file": 1,
"location": 2,
"severity": 3,
"code": 4,
"message": 5
},
"background": {
"activeOnStart": true,
"beginsPattern": "Project is running at",
"endsPattern": "Compiled successfully"
},
}
}
],
"inputs": [
{
"id": "terminate",
"type": "command",
"command": "workbench.action.tasks.terminate",
"args": "terminateAll"
}
]
}
"version": "2.0.0",
"tasks": [
{
"label": "end-tasks",
"command": "echo ${input:terminate}",
"type": "shell",
"problemMatcher": []
},
{
"label": "desktop:dev",
"dependsOn": ["desktop:dev:prepare", "desktop:dev:local"]
},
{
"label": "desktop:dev:prepare",
"type": "npm",
"script": "dev:prepare",
"path": "packages/suite-desktop/",
"problemMatcher": []
},
{
"label": "desktop:dev:local",
"type": "npm",
"script": "dev:local",
"path": "packages/suite-desktop/",
"isBackground": true,
"problemMatcher": {
"owner": "node",
"fileLocation": "relative",
"pattern": {
"regexp": "^(err|warn|info) - (.*)$",
"file": 1,
"location": 2,
"severity": 3,
"code": 4,
"message": 5
},
"background": {
"activeOnStart": true,
"beginsPattern": "Project is running at",
"endsPattern": "Compiled successfully"
}
}
}
],
"inputs": [
{
"id": "terminate",
"type": "command",
"command": "workbench.action.tasks.terminate",
"args": "terminateAll"
}
]
}

View File

@@ -1,2 +1,3 @@
# Changelog
As of version 21.5.1 we do not write a technical Changelog for Suite. Please see our [Github releases](https://github.com/trezor/trezor-suite/releases) for a brief overview or [Github projects](https://github.com/orgs/trezor/projects) for detailed one.

View File

@@ -47,4 +47,4 @@ Licensor gives no express warranties, guarantees or conditions. You may have
additional consumer rights under your local laws which this license cannot
change. To the extent permitted under your local laws, the Licensor excludes
the implied warranties of merchantability, fitness for a particular purpose and
non-infringement.
non-infringement.

View File

@@ -4,13 +4,13 @@
## Packages
| Name | Packages |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| suite | [core](./packages/suite), [web](./packages/suite-web), [desktop](./packages/suite-desktop), [native](./packages/suite-native), [data](./packages/suite-data), [storage](./packages/suite-storage) |
| components | [components](./packages/components), [storybook native](./packages/components-storybook-native) |
| rollout | [rollout](./packages/rollout) |
| blockchain-link | [blockchain-link](./packages/blockchain-link) |
| integration-tests | [integration-tests](./packages/integration-tests) |
| Name | Packages |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| suite | [core](./packages/suite), [web](./packages/suite-web), [desktop](./packages/suite-desktop), [native](./packages/suite-native), [data](./packages/suite-data), [storage](./packages/suite-storage) |
| components | [components](./packages/components), [storybook native](./packages/components-storybook-native) |
| rollout | [rollout](./packages/rollout) |
| blockchain-link | [blockchain-link](./packages/blockchain-link) |
| integration-tests | [integration-tests](./packages/integration-tests) |
## Development

View File

@@ -1,3 +1,9 @@
code format lint:
stage: validation
script:
- yarn install --frozen-lockfile --cache-folder .yarn --prefer-offline
- yarn format:verify
lint:
stage: validation
script:

View File

@@ -3,34 +3,35 @@
## Main differences between suite-web and suite-desktop builds
### trezor-connect API
- suite-web
`trezor-connect` is hosted at `[url]/build/static/connect` and injected as an iframe into DOM.
`iframe.postMessage/iframe.onmessage` interface is used as communication channel between suite and connect API.
- suite-web
- suite-desktop
`trezor-connect` is hosted at `[url]/build/static/connect` and injected as an iframe into DOM.
`trezor-connect` is installed as regular node_module in electron main process and works in nodejs environment.
`iframe.postMessage/iframe.onmessage` interface is used as communication channel between suite and connect API.
`trezor-connect` files are __not__ hosted on the electron renderer side, there is no iframe or /build/static/connect dir.
- suite-desktop
`Electron.IpcRenderer.send/Electron.IpcRenderer.on` interface is used as communication channel between suite (electron renderer) and connect API (electron main). see @trezor/suite-desktop/src-electron/trezor-connect-preload.ts
`trezor-connect` is installed as regular node_module in electron main process and works in nodejs environment.
`trezor-connect` files are **not** hosted on the electron renderer side, there is no iframe or /build/static/connect dir.
`Electron.IpcRenderer.send/Electron.IpcRenderer.on` interface is used as communication channel between suite (electron renderer) and connect API (electron main). see @trezor/suite-desktop/src-electron/trezor-connect-preload.ts
### Firmware binaries
- suite-web
newest firmware binaries are hosted at `[url]/build/static/connect/data/firmware` and they are downloaded using regular `fetch` API.
- suite-web
- suite-desktop
newest firmware binaries are hosted at `[url]/build/static/connect/data/firmware` and they are downloaded using regular `fetch` API.
firmware binaries are bundled as application resources in `bin` directory, full path depends on OS but it could be found on the as level as `app.asar` file, and they are downloaded using `fs.readFile` API. see @trezor/rollout/src/utils/fetch
- suite-desktop
firmware binaries are bundled as application resources in `bin` directory, full path depends on OS but it could be found on the as level as `app.asar` file, and they are downloaded using `fs.readFile` API. see @trezor/rollout/src/utils/fetch
### Trezor Bridge (trezord)
### Tor
## Debugging (VS Code)
Using VS Code configuration files (inside `.vscode`), Suite Desktop can be built and run with a debugger attached to it. Running the `Suite-Desktop: App` task (F5) will execute all required scripts (Webpack development server + Electron build) and launch the Electron app. VS Code will be set in debugging mode, allowing you, for example, to set breakpoints and inspect variables inside the `electron-src` folder (as well as other dependencies). For more on Debugging, please refer to [the VS Code documentation](https://code.visualstudio.com/docs/editor/debugging).
@@ -90,22 +91,29 @@ The auto-updater has been mocked to simulate similar behavior to the actual libr
## Debugging build
#### Linux
`./Trezor-Suite-20.10.1.AppImage --log-level=debug`
#### MacOS
`./Trezor\ Suite.app/Contents/MacOS/Trezor\ Suite --log-level=debug`
#### NixOS
`appimage-run ./Trezor-Suite.AppImage --log-level=debug`
## Extract application
#### MacOS
`npx asar extract ./Trezor\ Suite.app/Contents/Resources/app.asar ./decompiled`
#### NixOS
Run application to get mount-id like:
```
Trezor-Suite.AppImage installed in ~/.cache/appimage-run/e4f67ae8624c4079527c669d8a3c4bbc1dd00b83b2e1d15807a5863b11bd4f38
```
`npx asar extract ~/.cache/appimage-run/[mount-id]/resources/app.asar ./decompiled`
`npx asar extract ~/.cache/appimage-run/[mount-id]/resources/app.asar ./decompiled`

View File

@@ -29,9 +29,8 @@ If you want to publish to npm as `beta` (from any branch) do the following:
1. Commit your changes as `release: @trezor/<PACKAGE-NAME> X.X.X-beta.X`.
1. Use `beta <PACKAGE-NAME> deploy npm` job.
### Release new trezor-connect with updated package.
1. Upgrade the version of the package in `devDependencies` and `extendedDependencies` of `trezor-connect`.
1. Create [new beta release of trezor-connect](https://github.com/trezor/connect/blob/83af30f73f4cfa7c099c55b2b0f8a103abc299c8/docs/deployment/index.md#beta).
1. Use new trezor-connect in Suite. Upgrade `trezor-connect` dependency in `packages/*/package.json`
1. Use new trezor-connect in Suite. Upgrade `trezor-connect` dependency in `packages/*/package.json`

View File

@@ -1,8 +1,6 @@
{
"packages": [
"packages/*"
],
"npmClient": "yarn",
"useWorkspaces": true,
"version": "independent"
}
"packages": ["packages/*"],
"npmClient": "yarn",
"useWorkspaces": true,
"version": "independent"
}

View File

@@ -33,7 +33,9 @@
"lint:js": "eslint --cache --ignore-path .gitignore --ext .js,.ts,.tsx ./",
"lint": "yarn lerna run lint:styles && yarn lint:js",
"lint-staged": "npx lint-staged",
"deduplicate": "yarn-deduplicate && yarn"
"deduplicate": "yarn-deduplicate && yarn",
"format": "yarn prettier --write --ignore-path .gitignore \"**/*.{js,ts,tsx,mdx,md,html,json}\"",
"format:verify": "yarn prettier --check --ignore-path .gitignore \"**/*.{js,ts,tsx,mdx,md,html,json}\""
},
"lint-staged": {
"packages/**/*.{ts,tsx}": [
@@ -80,7 +82,7 @@
"npm-run-all": "^4.1.5",
"patch-package": "^6.2.1",
"postinstall-postinstall": "^2.0.0",
"prettier": "2.3.2",
"prettier": "2.5.1",
"prettier-eslint": "^13.0.0",
"rimraf": "^3.0.2",
"ts-jest": "^26.5.4",

View File

@@ -1,6 +0,0 @@
lib
build
coverage
**/_old/*
node_modules
src/ui/**

View File

@@ -1,10 +0,0 @@
{
"printWidth": 100,
"tabWidth": 4,
"singleQuote": true,
"trailingComma": "es5",
"arrowParens": "avoid",
"bracketSpacing": true,
"semi": true,
"useTabs": false
}

View File

@@ -1,49 +1,57 @@
# 2.1.1
#### changes
- Proxy agent in Ripple worker is set based on `RippleAPI._ALLOW_AGENT` flag, in order not to fail in standalone `trezor-connect` implementation (#4942)
- Proxy agent in Ripple worker is set based on `RippleAPI._ALLOW_AGENT` flag, in order not to fail in standalone `trezor-connect` implementation (#4942)
# 2.1.0
#### changes
- Added `proxy` param allowing workers to initialize SocksProxyAgent and use it for proxying communication
- Added support for `Electrum` backend
- Using common utilities from new `@trezor/utils` package
- Updated dependencies
- Added `proxy` param allowing workers to initialize SocksProxyAgent and use it for proxying communication
- Added support for `Electrum` backend
- Using common utilities from new `@trezor/utils` package
- Updated dependencies
# 2.0.0
#### changes
- Refactored architecture of workers. They may now be used as commonjs module in main context or in WebWorker context like before.
- Updated library build targets to es2017 reducing polyfills from typescript transpilation.
- Removed `build` directory from npm registry.
- Updated dependencies.
- Refactored architecture of workers. They may now be used as commonjs module in main context or in WebWorker context like before.
- Updated library build targets to es2017 reducing polyfills from typescript transpilation.
- Removed `build` directory from npm registry.
- Updated dependencies.
# 1.1.0
#### changes
- lower default XRP reserve
- set XRP reserve after `getInfo` call (get server info)
- added support for `Cardano` using `Blockfrost` backend
- fix blockbook transaction target when tx is sent to change address
- fix blockbook (ETH) transaction target when swapping ETH <> ERC20
- lower default XRP reserve
- set XRP reserve after `getInfo` call (get server info)
- added support for `Cardano` using `Blockfrost` backend
- fix blockbook transaction target when tx is sent to change address
- fix blockbook (ETH) transaction target when swapping ETH <> ERC20
# 1.0.17
#### changes
- Fixed tx.amount for btc-like sent txs
- Added tx.totalSpent
- Added tx.details.locktime
- Fixed tx.amount for btc-like sent txs
- Added tx.totalSpent
- Added tx.details.locktime
# 1.0.16
#### changes
- Fixed an issue where account with non-zero balance could be marked as empty (eth)
- Pending ETH transaction fee calculated from `ethereumSpecific` field
- Added missing types (data) to `ethereumSpecific` field
- Fixed an issue where account with non-zero balance could be marked as empty (eth)
- Pending ETH transaction fee calculated from `ethereumSpecific` field
- Added missing types (data) to `ethereumSpecific` field
# 1.0.15
#### changes
- Added `details` to `Transaction` object (vin, vout, size)
- Fixed types in `BlockchainLink` event listeners
- Move "workersDepenedecies" to regular "dependencies" in package.json

View File

@@ -30,14 +30,13 @@ const link = new BlockchainLink({
try {
const resp = link.getInfo();
} catch(error) {
}
} catch (error) {}
```
For complete API see the methods of `BlockchainLink` class in [index.ts](./src/index.ts).
## Workers
Each `src/workers/*/index` file can be used in WebWorker thread.
Built from source using webpack `worker-loader`:
@@ -53,12 +52,13 @@ Run UI with webworkers support
```shell
yarn workspace @trezor/blockchain-link dev
```
or without webworkes support (workers are compiled into a bundle)
```shell
yarn workspace @trezor/blockchain-link dev:module
```
### Tests
```
@@ -68,7 +68,9 @@ yarn workspace @trezor/blockchain-link test:unit
```
### Integration tests
Testing `lib` and `build` outputs:
```
yarn workspace @trezor/blockchain-link build:lib
yarn workspace @trezor/blockchain-link build:workers

View File

@@ -34,7 +34,7 @@ packageJSON.main = 'lib/index.js';
fs.writeFileSync(
path.resolve(npm, 'package.json'),
JSON.stringify(packageJSON, null, ' '),
'utf-8'
'utf-8',
);
fs.copySync(path.resolve(npm, '../README.md'), path.resolve(npm, 'README.md'));

View File

@@ -112,7 +112,7 @@ class BlockchainLink extends EventEmitter {
/** Get hash of a block of given height. */
getBlockHash(
payload: MessageTypes.GetBlockHash['payload']
payload: MessageTypes.GetBlockHash['payload'],
): Promise<ResponseTypes.GetBlockHash['payload']> {
return this.sendMessage({
type: MESSAGES.GET_BLOCK_HASH,
@@ -122,7 +122,7 @@ class BlockchainLink extends EventEmitter {
/** Get info about an account, eg. derived addresses, balance, transaction history etc. */
getAccountInfo(
payload: MessageTypes.GetAccountInfo['payload']
payload: MessageTypes.GetAccountInfo['payload'],
): Promise<ResponseTypes.GetAccountInfo['payload']> {
return this.sendMessage({
type: MESSAGES.GET_ACCOUNT_INFO,
@@ -132,7 +132,7 @@ class BlockchainLink extends EventEmitter {
/** Get unspent inputs for given account. Works only for bitcoin(like) networks. */
getAccountUtxo(
payload: MessageTypes.GetAccountUtxo['payload']
payload: MessageTypes.GetAccountUtxo['payload'],
): Promise<ResponseTypes.GetAccountUtxo['payload']> {
return this.sendMessage({
type: MESSAGES.GET_ACCOUNT_UTXO,
@@ -146,7 +146,7 @@ class BlockchainLink extends EventEmitter {
* this method exposes raw response from the BE.
*/
getTransaction(
payload: MessageTypes.GetTransaction['payload']
payload: MessageTypes.GetTransaction['payload'],
): Promise<ResponseTypes.GetTransaction['payload']> {
return this.sendMessage({
type: MESSAGES.GET_TRANSACTION,
@@ -159,7 +159,7 @@ class BlockchainLink extends EventEmitter {
* Used for rendering a graph in Suite's dashboard.
*/
getAccountBalanceHistory(
payload: MessageTypes.GetAccountBalanceHistory['payload']
payload: MessageTypes.GetAccountBalanceHistory['payload'],
): Promise<ResponseTypes.GetAccountBalanceHistory['payload']> {
return this.sendMessage({
type: MESSAGES.GET_ACCOUNT_BALANCE_HISTORY,
@@ -168,7 +168,7 @@ class BlockchainLink extends EventEmitter {
}
getCurrentFiatRates(
payload: MessageTypes.GetCurrentFiatRates['payload']
payload: MessageTypes.GetCurrentFiatRates['payload'],
): Promise<ResponseTypes.GetCurrentFiatRates['payload']> {
return this.sendMessage({
type: MESSAGES.GET_CURRENT_FIAT_RATES,
@@ -178,7 +178,7 @@ class BlockchainLink extends EventEmitter {
/** Get historical fiat rates. Only some backends support this. */
getFiatRatesForTimestamps(
payload: MessageTypes.GetFiatRatesForTimestamps['payload']
payload: MessageTypes.GetFiatRatesForTimestamps['payload'],
): Promise<ResponseTypes.GetFiatRatesForTimestamps['payload']> {
return this.sendMessage({
type: MESSAGES.GET_FIAT_RATES_FOR_TIMESTAMPS,
@@ -188,7 +188,7 @@ class BlockchainLink extends EventEmitter {
/** Get fiat currencies for which rates are available. */
getFiatRatesTickersList(
payload: MessageTypes.GetFiatRatesTickersList['payload']
payload: MessageTypes.GetFiatRatesTickersList['payload'],
): Promise<ResponseTypes.GetFiatRatesTickersList['payload']> {
return this.sendMessage({
type: MESSAGES.GET_FIAT_RATES_TICKERS_LIST,
@@ -198,7 +198,7 @@ class BlockchainLink extends EventEmitter {
/** Get recommended fee value inferred from current traffic in the network. */
estimateFee(
payload: MessageTypes.EstimateFee['payload']
payload: MessageTypes.EstimateFee['payload'],
): Promise<ResponseTypes.EstimateFee['payload']> {
return this.sendMessage({
type: MESSAGES.ESTIMATE_FEE,
@@ -216,7 +216,7 @@ class BlockchainLink extends EventEmitter {
* Handling subscription state is left to the user. Hence the purpose of CONNECT and DISCONNECT notifications.
*/
subscribe(
payload: MessageTypes.Subscribe['payload']
payload: MessageTypes.Subscribe['payload'],
): Promise<ResponseTypes.Subscribe['payload']> {
return this.sendMessage({
type: MESSAGES.SUBSCRIBE,
@@ -226,7 +226,7 @@ class BlockchainLink extends EventEmitter {
/** Discard a subscription. */
unsubscribe(
payload: MessageTypes.Unsubscribe['payload']
payload: MessageTypes.Unsubscribe['payload'],
): Promise<ResponseTypes.Unsubscribe['payload']> {
return this.sendMessage({
type: MESSAGES.UNSUBSCRIBE,
@@ -236,7 +236,7 @@ class BlockchainLink extends EventEmitter {
/** Broadcast a transaction to the network. */
pushTransaction(
payload: MessageTypes.PushTransaction['payload']
payload: MessageTypes.PushTransaction['payload'],
): Promise<ResponseTypes.PushTransaction['payload']> {
return this.sendMessage({
type: MESSAGES.PUSH_TRANSACTION,

View File

@@ -170,31 +170,31 @@ declare function FSend(method: 'getTransaction', params: { txid: string }): Prom
declare function FSend(method: 'sendTransaction', params: { hex: string }): Promise<Push>;
declare function FSend(
method: 'getBalanceHistory',
params: AccountBalanceHistoryParams
params: AccountBalanceHistoryParams,
): Promise<AccountBalanceHistory[]>;
declare function FSend(
method: 'getCurrentFiatRates',
params: GetCurrentFiatRatesParams
params: GetCurrentFiatRatesParams,
): Promise<TimestampedFiatRates>;
declare function FSend(
method: 'getFiatRatesTickersList',
params: GetFiatRatesTickersListParams
params: GetFiatRatesTickersListParams,
): Promise<AvailableCurrencies>;
declare function FSend(
method: 'getFiatRatesForTimestamps',
params: GetFiatRatesForTimestampsParams
params: GetFiatRatesForTimestampsParams,
): Promise<FiatRatesForTimestamp>;
declare function FSend(method: 'estimateFee', params: EstimateFeeParams): Promise<Fee>;
declare function FSend(
method: 'subscribeAddresses',
params: { addresses: string[] }
params: { addresses: string[] },
): Promise<Subscribe>;
declare function FSend(method: 'unsubscribeAddresses'): Promise<Subscribe>;
declare function FSend(method: 'subscribeNewBlock'): Promise<Subscribe>;
declare function FSend(method: 'unsubscribeNewBlock'): Promise<Subscribe>;
declare function FSend(
method: 'subscribeFiatRates',
params: { currency?: string }
params: { currency?: string },
): Promise<Subscribe>;
declare function FSend(method: 'unsubscribeFiatRates'): Promise<Subscribe>;
export type Send = typeof FSend;

View File

@@ -247,31 +247,31 @@ export interface BlockfrostUtxos {
declare function FSend(method: 'GET_SERVER_INFO'): Promise<ServerInfo>;
declare function FSend(
method: 'GET_BLOCK',
params: { hashOrNumber: number | string }
params: { hashOrNumber: number | string },
): Promise<BlockContent>;
declare function FSend(
method: 'GET_ACCOUNT_INFO',
params: AccountInfoParams
params: AccountInfoParams,
): Promise<BlockfrostAccountInfo>;
declare function FSend(
method: 'GET_ACCOUNT_UTXO',
params: AccountUtxoParams
params: AccountUtxoParams,
): Promise<BlockfrostUtxos[]>;
declare function FSend(
method: 'GET_TRANSACTION',
params: { txId: string }
params: { txId: string },
): Promise<BlockfrostTransaction>;
declare function FSend(method: 'PUSH_TRANSACTION', params: { txData: string }): Promise<string>;
declare function FSend(method: 'SUBSCRIBE_BLOCK'): Promise<Subscribe>;
declare function FSend(method: 'UNSUBSCRIBE_BLOCK'): Promise<Subscribe>;
declare function FSend(
method: 'SUBSCRIBE_ADDRESS',
params: { addresses: string[] }
params: { addresses: string[] },
): Promise<Subscribe>;
declare function FSend(method: 'UNSUBSCRIBE_ADDRESS'): Promise<Subscribe>;
declare function FSend(
method: 'GET_BALANCE_HISTORY',
params: AccountBalanceHistoryParams
params: AccountBalanceHistoryParams,
): Promise<AccountBalanceHistory[]>;
declare function FSend(method: 'ESTIMATE_FEE', params: EstimateFeeParams): Promise<Fee>;
export type Send = typeof FSend;

View File

@@ -106,7 +106,7 @@ export interface ElectrumAPI {
request(
method: 'server.version',
client_name: string,
protocol_version: string | [string, string]
protocol_version: string | [string, string],
): Promise<Version>;
request(method: 'server.banner'): Promise<string>;
request(method: 'server.ping'): Promise<null>;
@@ -124,7 +124,7 @@ export interface ElectrumAPI {
method: 'blockchain.block.headers',
start_height: number,
count: number,
cp_height?: number
cp_height?: number,
): Promise<BlockHeaders>;
request(method: 'blockchain.estimatefee', number: number): Promise<number>;
request(method: 'blockchain.headers.subscribe'): Promise<BlockHeader>;
@@ -133,24 +133,24 @@ export interface ElectrumAPI {
request(
method: 'blockchain.transaction.get',
tx_hash: string,
verbose?: false
verbose?: false,
): Promise<string>;
request(
method: 'blockchain.transaction.get',
tx_hash: string,
verbose: true
verbose: true,
): Promise<TransactionVerbose>;
request(
method: 'blockchain.transaction.get_merkle',
tx_hash: string,
height: number
height: number,
): Promise<unknown>;
request(method: 'mempool.get_fee_histogram'): Promise<unknown>;
/** @deprecated 1.1 */
request(
method: 'blockchain.utxo.get_address',
tx_hash: string,
index: unknown
index: unknown,
): Promise<unknown>;
/** @deprecated 1.1 */
request(method: 'blockchain.numblocks.subscribe'): Promise<unknown>;

View File

@@ -199,4 +199,4 @@
(function(){var script=document.createElement('script');script.onload=function(){var stats=new Stats();document.body.appendChild(stats.dom);requestAnimationFrame(function loop(){stats.update();requestAnimationFrame(loop)});};script.src='//mrdoob.github.io/stats.js/build/stats.min.js';document.head.appendChild(script);})();
</script> -->
</body>
</html>
</html>

View File

@@ -208,7 +208,7 @@ const handleClick = (event: MouseEvent) => {
.getFiatRatesTickersList({
timestamp: parseInt(
getInputValue('get-fiat-rates-ticker-list-timestamp'),
10
10,
),
})
.then(onResponse)
@@ -283,7 +283,7 @@ const handleConnectionEvent = (blockchain: BlockchainLink, status: boolean) => {
blockchain: blockchain.settings.name,
connected: status,
},
!status
!status,
);
};

View File

@@ -56,7 +56,7 @@ const getAccountUtxo = async (request: Request<MessageTypes.GetAccountUtxo>) =>
};
const getAccountBalanceHistory = async (
request: Request<MessageTypes.GetAccountBalanceHistory>
request: Request<MessageTypes.GetAccountBalanceHistory>,
) => {
const { payload } = request;
const api = await request.connect();
@@ -78,7 +78,7 @@ const getCurrentFiatRates = async (request: Request<MessageTypes.GetCurrentFiatR
};
const getFiatRatesForTimestamps = async (
request: Request<MessageTypes.GetFiatRatesForTimestamps>
request: Request<MessageTypes.GetFiatRatesForTimestamps>,
) => {
const { payload } = request;
const api = await request.connect();
@@ -244,7 +244,7 @@ const subscribe = async (request: Request<MessageTypes.Subscribe>) => {
const unsubscribeAccounts = async (
{ state, connect }: Context,
accounts?: SubscriptionAccountInfo[]
accounts?: SubscriptionAccountInfo[],
) => {
state.removeAccounts(accounts || state.getAccounts());

View File

@@ -29,7 +29,7 @@ export const transformServerInfo = (payload: ServerInfo) => ({
export const filterTokenTransfers = (
addresses: Addresses,
transfers: BlockbookTransaction['tokenTransfers']
transfers: BlockbookTransaction['tokenTransfers'],
): TokenTransfer[] => {
if (typeof addresses === 'string') {
addresses = [addresses];
@@ -81,7 +81,7 @@ export const filterTokenTransfers = (
export const transformTransaction = (
descriptor: string,
addresses: AccountAddresses | undefined,
tx: BlockbookTransaction
tx: BlockbookTransaction,
): Transaction => {
// combine all addresses into array
const myAddresses = addresses
@@ -196,7 +196,7 @@ export const transformTransaction = (
};
export const transformTokenInfo = (
tokens: BlockbookAccountInfo['tokens']
tokens: BlockbookAccountInfo['tokens'],
): TokenInfo[] | undefined => {
if (!tokens || !Array.isArray(tokens)) return undefined;
const info = tokens.reduce((arr, t) => {
@@ -216,7 +216,7 @@ export const transformTokenInfo = (
};
export const transformAddresses = (
tokens: BlockbookAccountInfo['tokens']
tokens: BlockbookAccountInfo['tokens'],
): AccountAddresses | undefined => {
if (!tokens || !Array.isArray(tokens)) return undefined;
const addresses = tokens.reduce((arr, t) => {

View File

@@ -67,7 +67,7 @@ export class BlockbookAPI extends EventEmitter {
this.clearConnectionTimeout();
this.connectionTimeout = setTimeout(
this.onTimeout.bind(this),
this.options.timeout || DEFAULT_TIMEOUT
this.options.timeout || DEFAULT_TIMEOUT,
);
}
@@ -84,7 +84,7 @@ export class BlockbookAPI extends EventEmitter {
}
this.pingTimeout = setTimeout(
this.onPing.bind(this),
this.options.pingTimeout || DEFAULT_PING_TIMEOUT
this.options.pingTimeout || DEFAULT_PING_TIMEOUT,
);
}

View File

@@ -33,7 +33,7 @@ const getBlockHash = async (request: Request<MessageTypes.GetBlockHash>) => {
};
const getAccountBalanceHistory = async (
request: Request<MessageTypes.GetAccountBalanceHistory>
request: Request<MessageTypes.GetAccountBalanceHistory>,
) => {
const socket = await request.connect();
const history = await socket.getAccountBalanceHistory(request.payload);
@@ -188,7 +188,7 @@ const unsubscribeBlock = async ({ state, connect }: Context) => {
const unsubscribeAccounts = async (
{ state, connect }: Context,
accounts?: SubscriptionAccountInfo[]
accounts?: SubscriptionAccountInfo[],
) => {
state.removeAccounts(accounts || state.getAccounts());

View File

@@ -32,7 +32,7 @@ export const transformUtxos = (utxos: BlockfrostUtxos[]): Utxo[] => {
unit: u.unit,
},
});
})
}),
);
return result;
};
@@ -82,7 +82,7 @@ export const parseAsset = (hex: string): ParseAssetResult => {
};
export const transformTokenInfo = (
tokens: BlockfrostAccountInfo['tokens']
tokens: BlockfrostAccountInfo['tokens'],
): TokenInfo[] | undefined => {
if (!tokens || !Array.isArray(tokens)) return undefined;
const info = tokens.map(t => {
@@ -102,7 +102,7 @@ export const transformTokenInfo = (
export const transformInputOutput = (
data: BlockfrostTransaction['txUtxos']['inputs'] | BlockfrostTransaction['txUtxos']['outputs'],
asset = 'lovelace'
asset = 'lovelace',
): VinVout[] =>
data.map(utxo => ({
n: utxo.output_index,
@@ -114,7 +114,7 @@ export const transformInputOutput = (
export const filterTokenTransfers = (
accountAddress: AccountAddresses,
tx: BlockfrostTransaction,
type: Transaction['type']
type: Transaction['type'],
): TokenTransfer[] => {
const transfers: TokenTransfer[] = [];
const myNonChangeAddresses = accountAddress.used.concat(accountAddress.unused);
@@ -134,7 +134,7 @@ export const filterTokenTransfers = (
const incomingForOutput = filterTargets(
myNonChangeAddresses,
transformInputOutput([output], token)
transformInputOutput([output], token),
);
let amount = '0';
@@ -173,7 +173,7 @@ export const filterTokenTransfers = (
export const transformTransaction = (
descriptor: string,
accountAddress: AccountAddresses | undefined,
blockfrostTxData: BlockfrostTransaction
blockfrostTxData: BlockfrostTransaction,
): Transaction => {
const myAddresses = accountAddress
? accountAddress.change.concat(accountAddress.used, accountAddress.unused)
@@ -272,7 +272,7 @@ export const transformAccountInfo = (info: BlockfrostAccountInfo): AccountInfo =
transactions: !blockfrostTxs
? []
: blockfrostTxs?.map(tx =>
transformTransaction(info.descriptor, info.addresses, tx)
transformTransaction(info.descriptor, info.addresses, tx),
),
},
};

View File

@@ -56,7 +56,7 @@ export class BlockfrostAPI extends EventEmitter {
this.clearConnectionTimeout();
this.connectionTimeout = setTimeout(
this.onTimeout.bind(this),
this.options.timeout || DEFAULT_TIMEOUT
this.options.timeout || DEFAULT_TIMEOUT,
);
}
@@ -74,7 +74,7 @@ export class BlockfrostAPI extends EventEmitter {
this.pingTimeout = setTimeout(
this.onPing.bind(this),
this.options.pingTimeout || DEFAULT_PING_TIMEOUT
this.options.pingTimeout || DEFAULT_PING_TIMEOUT,
);
}

View File

@@ -47,7 +47,7 @@ export class ElectrumClient extends BatchingJsonRpcClient implements ElectrumAPI
this.version = await (this as ElectrumAPI).request(
'server.version',
name,
protocolVersion
protocolVersion,
);
(this as ElectrumAPI).on('blockchain.headers.subscribe', this.onBlock);
this.lastBlock = await (this as ElectrumAPI).request('blockchain.headers.subscribe');

View File

@@ -42,7 +42,7 @@ type ResponseType<T extends MessageType> = T extends typeof MESSAGES.GET_INFO
type Reply<T extends MessageType> = Without<Extract<Response, { type: ResponseType<T> }>, 'id'>;
const onRequest = async <T extends Message>(
request: Request<T>
request: Request<T>,
): Promise<Reply<typeof request.type>> => {
const client = await request.connect();
switch (request.type) {

View File

@@ -20,7 +20,7 @@ export const blockListener = (worker: BaseWorker<ElectrumAPI>) => {
blockHash: blockheaderToBlockhash(hex),
},
},
})
}),
);
};

View File

@@ -61,8 +61,8 @@ export const txListener = (worker: BaseWorker<ElectrumAPI>) => {
await Promise.all(
shToSubscribe.map(scripthash =>
api().request('blockchain.scripthash.subscribe', scripthash)
)
api().request('blockchain.scripthash.subscribe', scripthash),
),
);
return { subscribed: true };
};
@@ -82,8 +82,8 @@ export const txListener = (worker: BaseWorker<ElectrumAPI>) => {
await Promise.all(
shToUnsubscribe.map(scripthash =>
api().request('blockchain.scripthash.unsubscribe', scripthash)
)
api().request('blockchain.scripthash.unsubscribe', scripthash),
),
);
return { subscribed: false };
};

View File

@@ -7,8 +7,8 @@ const estimateFee: Api<Req, Res> = (client, payload) =>
(payload.blocks || []).map(num =>
client
.request('blockchain.estimatefee', num)
.then(btc => ({ feePerUnit: btcToSat(btc) }))
)
.then(btc => ({ feePerUnit: btcToSat(btc) })),
),
);
export default estimateFee;

View File

@@ -51,7 +51,7 @@ const aggregateTransactions = (txs: (Transaction & { blockTime: number })[], gro
const getAccountBalanceHistory: Api<Req, Res> = async (
client,
{ descriptor, from, to, groupBy }
{ descriptor, from, to, groupBy },
) => {
let history: HistoryTx[];
let addresses: AccountAddresses | undefined;
@@ -80,10 +80,10 @@ const getAccountBalanceHistory: Api<Req, Res> = async (
txs
.filter(
({ blockTime }) =>
(from || 0) <= blockTime && blockTime <= (to || Number.MAX_SAFE_INTEGER)
(from || 0) <= blockTime && blockTime <= (to || Number.MAX_SAFE_INTEGER),
)
.sort((a, b) => a.blockTime - b.blockTime)
.map(tx => ({ blockTime: -1, ...transformTransaction(descriptor, addresses, tx) }))
.map(tx => ({ blockTime: -1, ...transformTransaction(descriptor, addresses, tx) })),
);
return aggregateTransactions(txs, groupBy);

View File

@@ -34,7 +34,7 @@ const getBalances =
confirmed,
unconfirmed,
};
})
}),
);
const getAccountInfo: Api<Req, Res> = async (client, payload) => {
@@ -56,7 +56,7 @@ const getAccountInfo: Api<Req, Res> = async (client, payload) => {
const transactions =
details === 'txs'
? await getTransactions(client, history).then(txs =>
txs.map(tx => transformTransaction(descriptor, undefined, tx))
txs.map(tx => transformTransaction(descriptor, undefined, tx)),
)
: undefined;
@@ -84,15 +84,15 @@ const getAccountInfo: Api<Req, Res> = async (client, payload) => {
}
const discover = discoverAddress(client);
const receive = await discovery(discover, descriptor, 'receive', network).then(
getBalances(client)
getBalances(client),
);
const change = await discovery(discover, descriptor, 'change', network).then(
getBalances(client)
getBalances(client),
);
const batch = receive.concat(change);
const [confirmed, unconfirmed] = batch.reduce(
([c, u], { confirmed, unconfirmed }) => [c + confirmed, u + unconfirmed],
[0, 0]
[0, 0],
);
const history = batch.flatMap(({ history }) => history);
const historyUnconfirmed = history.filter(r => r.height <= 0).length;
@@ -112,19 +112,19 @@ const getAccountInfo: Api<Req, Res> = async (client, payload) => {
const transactions = ['tokenBalances', 'txids', 'txs'].includes(details)
? await getTransactions(client, history).then(txs =>
txs.map(tx => transformTransaction(descriptor, addresses, tx))
txs.map(tx => transformTransaction(descriptor, addresses, tx)),
)
: [];
const sumAddressValues = (
address: string,
getVinVouts: (tr: ReturnType<typeof transformTransaction>) => VinVout[]
getVinVouts: (tr: ReturnType<typeof transformTransaction>) => VinVout[],
) =>
transactions
.flatMap(tx =>
getVinVouts(tx)
.filter(({ addresses }) => addresses?.includes(address))
.map(({ value }) => (value ? Number.parseFloat(value) : 0))
.map(({ value }) => (value ? Number.parseFloat(value) : 0)),
)
.reduce((a, b) => a + b, 0);

View File

@@ -48,8 +48,8 @@ const getAccountUtxo: Api<Req, Res> = async (client, descriptor) => {
.map(({ address, path, scripthash }) =>
client
.request('blockchain.scripthash.listunspent', scripthash)
.then(utxos => utxos.map(transformUtxo(height, { address, path })))
)
.then(utxos => utxos.map(transformUtxo(height, { address, path }))),
),
).then(res => res.flat());
return result;
};

View File

@@ -10,7 +10,7 @@ const addressesFromAccounts = (array: (AccountAddresses | undefined)[]) =>
array
.filter(isNotUndefined)
.flatMap(({ change, used, unused }) =>
change.concat(used, unused).map(({ address }) => address)
change.concat(used, unused).map(({ address }) => address),
);
export const createAddressManager = (network?: Network) => {
@@ -25,7 +25,7 @@ export const createAddressManager = (network?: Network) => {
...dic,
[addr]: addressToScripthash(addr, network),
}),
subscribedAddrs
subscribedAddrs,
);
return toAdd.map(addr => subscribedAddrs[addr]);
@@ -49,7 +49,7 @@ export const createAddressManager = (network?: Network) => {
...dic,
[acc.descriptor]: acc.addresses || { change: [], used: [], unused: [] },
}),
subscribedAccs
subscribedAccs,
);
const addresses = addressesFromAccounts(toAdd.map(acc => acc.addresses));
@@ -61,7 +61,7 @@ export const createAddressManager = (network?: Network) => {
const [toRemove, toPreserve] = accounts
? objectPartition(
subscribedAccs,
accounts.map(({ descriptor }) => descriptor)
accounts.map(({ descriptor }) => descriptor),
)
: [subscribedAccs, {}];
@@ -81,7 +81,7 @@ export const createAddressManager = (network?: Network) => {
const [account, addresses] =
Object.entries(subscribedAccs).find(
([_acc, { change, unused, used }]) =>
!!change.concat(used, unused).find(ad => ad.address === address)
!!change.concat(used, unused).find(ad => ad.address === address),
) || [];
return {
descriptor: account || address,

View File

@@ -76,7 +76,7 @@ const formatTransaction =
export const getTransactions = async (
client: ElectrumAPI,
history: HistoryTx[]
history: HistoryTx[],
): Promise<BlockbookTransaction[]> => {
const txids = history.map(({ tx_hash }) => tx_hash).filter(arrayDistinct);
@@ -84,7 +84,7 @@ export const getTransactions = async (
// binary data locally instead. Then the transaction could be cached indefinitely.
const origTxs = await Promise.all(
txids.map(txid => client.request('blockchain.transaction.get', txid, true))
txids.map(txid => client.request('blockchain.transaction.get', txid, true)),
).then(txs => arrayToDictionary(txs, ({ txid }) => txid));
const prevTxs = await Promise.all(
@@ -92,7 +92,7 @@ export const getTransactions = async (
.flatMap(({ vin }) => vin.filter(isNotCoinbase).map(({ txid }) => txid))
.filter(arrayDistinct)
.filter(txid => !origTxs[txid])
.map(txid => client.request('blockchain.transaction.get', txid, true))
.map(txid => client.request('blockchain.transaction.get', txid, true)),
).then(txs => arrayToDictionary(txs, ({ txid }) => txid));
/* TODO

View File

@@ -21,7 +21,7 @@ export const blockheaderToBlockhash = (header: string) => {
export const tryGetScripthash = (
address: string,
network?: Network
network?: Network,
): { valid: true; scripthash: string } | { valid: false } => {
try {
return {

View File

@@ -148,7 +148,7 @@ const getAccountInfo = async (request: Request<MessageTypes.GetAccountInfo>) =>
const api = await request.connect();
const transactionsData: RawTxData = await api.request('account_tx', requestOptions);
account.history.transactions = transactionsData.transactions.map(raw =>
utils.transformTransaction(payload.descriptor, raw.tx)
utils.transformTransaction(payload.descriptor, raw.tx),
);
return {
@@ -503,7 +503,7 @@ class RippleWorker extends BaseWorker<RippleAPI> {
}
this.pingTimeout = setTimeout(
() => this.onPing(),
this.settings.pingTimeout || DEFAULT_PING_TIMEOUT
this.settings.pingTimeout || DEFAULT_PING_TIMEOUT,
);
}

View File

@@ -65,7 +65,7 @@ export class WorkerState {
this.accounts = others.concat(valid);
const addresses = this.accounts.reduce(
(addr, a) => addr.concat(this.getAccountAddresses(a)),
[] as string[]
[] as string[],
);
this.addAddresses(addresses);
return valid;
@@ -91,11 +91,11 @@ export class WorkerState {
removeAccounts(acc: SubscriptionAccountInfo[]): SubscriptionAccountInfo[] {
const valid = this.validateAccounts(acc);
const accountsToRemove = this.accounts.filter(a =>
valid.find(b => b.descriptor === a.descriptor)
valid.find(b => b.descriptor === a.descriptor),
);
const addressesToRemove = accountsToRemove.reduce(
(addr, acc) => addr.concat(this.getAccountAddresses(acc)),
[] as string[]
[] as string[],
);
this.accounts = this.accounts.filter(a => accountsToRemove.indexOf(a) < 0);
this.removeAddresses(addressesToRemove);

View File

@@ -28,7 +28,7 @@ export const filterTargets = (addresses: Addresses, targets: VinVout[]): VinVout
export const sumVinVout = (
vinVout: VinVout[],
initialValue = '0',
operation: 'sum' | 'reduce' = 'sum'
operation: 'sum' | 'reduce' = 'sum',
) => {
const sum = vinVout.reduce((bn, v) => {
if (typeof v.value !== 'string') return bn;

View File

@@ -48,7 +48,7 @@ describe('blockfrost/utils', () => {
it(f.description, () => {
// @ts-expect-error incorrect params
expect(transformTransaction(f.descriptor, f.accountAddress, f.data)).toMatchObject(
f.result
f.result,
);
});
});

View File

@@ -1,68 +1,68 @@
{
"getInfo": {
"data": {
"name": "Test",
"shortcut": "test",
"decimals": 9,
"bestHeight": 1
}
"data": {
"name": "Test",
"shortcut": "test",
"decimals": 9,
"bestHeight": 1
}
},
"getBlockHash": {
"data": {
"hash": "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048"
}
"data": {
"hash": "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048"
}
},
"subscribeNewBlock": {
"data": {
"subscribed": true
}
"data": {
"subscribed": true
}
},
"unsubscribeNewBlock": {
"data": {
"subscribed": false
}
"data": {
"subscribed": false
}
},
"subscribeAddresses": {
"data": {
"subscribed": true
}
"data": {
"subscribed": true
}
},
"unsubscribeAddresses": {
"data": {
"subscribed": false
}
"data": {
"subscribed": false
}
},
"getAccountInfo": {
"data": {
"address": "0",
"balance": "0",
"txs": 0,
"unconfirmedBalance": 0,
"unconfirmedTxs": 0,
"nonce": "0",
"totalReceived": "0",
"totalSent": "0",
"usedTokens": 0
}
"data": {
"address": "0",
"balance": "0",
"txs": 0,
"unconfirmedBalance": 0,
"unconfirmedTxs": 0,
"nonce": "0",
"totalReceived": "0",
"totalSent": "0",
"usedTokens": 0
}
},
"getAccountUtxo": {
"data": []
"data": []
},
"sendTransaction": {
"data": {
"error": {
"message": "-22: TX decode failed"
}
}
"data": {
"error": {
"message": "-22: TX decode failed"
}
}
},
"estimateFee": {
"data": []
"data": []
},
"getTransaction": {
"data": {
"error": {
"message": "Transaction not found"
}
}
"data": {
"error": {
"message": "Transaction not found"
}
}
}
}
}

View File

@@ -66,4 +66,4 @@
"error_code": 29,
"error_message": "Transaction not found."
}
}
}

View File

@@ -221,7 +221,7 @@ const createServer = async (type: keyof typeof DEFAULT_RESPONSES) => {
}
if (Array.isArray(request.accounts_proposed)) {
server.addresses = server.addresses.filter(
a => request.accounts_proposed.indexOf(a) < 0
a => request.accounts_proposed.indexOf(a) < 0,
);
if (server.addresses.length === 0) server.addresses = undefined;
}

View File

@@ -5,4 +5,4 @@
},
"include": ["./src/**/*.ts", "./tests/**/*.ts"],
"exclude": ["node_modules"]
}
}

View File

@@ -17,4 +17,4 @@
},
"include": ["./src/index.ts", "./src/utils/ws.ts", "./src/utils/socks-proxy-agent.ts"],
"exclude": ["node_modules"]
}
}

View File

@@ -1,97 +0,0 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.vscode
docs
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
#DynamoDB Local files
.dynamodb/
# dev mess
src/.old_components
# npm module
npm
lib
.DS_Store
__diff_output__
test/screenshots
test/screenshots
test/videos

View File

@@ -1,18 +0,0 @@
src
docs
.babel-config
.storybook
.eslintignore
.eslintrc
.gitignore
node_modules
.snyk
.stylelintrc
babel.config.js
yarn.lock
public
scripts
test
.*
cypress.json

View File

@@ -1,10 +0,0 @@
public
build
coverage
cache/**
node_modules
src/flowtype/npm
scripts/solidity/.*
**/_old/*
docs
lib

View File

@@ -1,11 +0,0 @@
{
"printWidth": 100,
"tabWidth": 4,
"singleQuote": true,
"trailingComma": "es5",
"arrowParens": "avoid",
"bracketSpacing": true,
"semi": true,
"useTabs": false,
"jsxBracketSameLine": false
}

View File

@@ -1,2 +1,2 @@
<link media="all" rel="stylesheet" href="./fonts/fonts.css" />
<link media="all" rel="stylesheet" href="./fonts/style.css" />
<link media="all" rel="stylesheet" href="./fonts/style.css" />

View File

@@ -1,2 +1,2 @@
<link media="all" rel="stylesheet" href="./fonts/fonts.css" />
<link media="all" rel="stylesheet" href="./fonts/style.css" />
<link media="all" rel="stylesheet" href="./fonts/style.css" />

View File

@@ -1,7 +1,13 @@
import React from 'react';
import { StoryWrapper } from '../src/support/Story';
export const decorators = [(Story) => <StoryWrapper><Story/></StoryWrapper>];
export const decorators = [
Story => (
<StoryWrapper>
<Story />
</StoryWrapper>
),
];
export const parameters = {
options: {
showPanel: true,
@@ -11,4 +17,4 @@ export const parameters = {
theme: {
base: 'light',
},
};
};

View File

@@ -3,4 +3,3 @@
[![npm version](https://badge.fury.io/js/trezor-ui-components.svg)](https://badge.fury.io/js/trezor-ui-components)
This repository contains UI components that are intended to be used accross related Trezor frontend projects.

View File

@@ -12,7 +12,7 @@ storiesOf('Dropdown', module).add('Dropdown', () => {
left: 'left',
right: 'right',
},
null
null,
);
const isDisabled = boolean('isDisabled', false);
const offset = number('offset', 10);

View File

@@ -279,7 +279,7 @@ const Dropdown = forwardRef(
masterLink,
...rest
}: Props,
ref
ref,
) => {
const theme = useTheme();
const [toggled, setToggledState] = useState(false);
@@ -300,7 +300,7 @@ const Dropdown = forwardRef(
if (onToggle) onToggle(isToggled);
setToggledState(isToggled);
},
[onToggle]
[onToggle],
);
useLayoutEffect(() => {
@@ -471,7 +471,7 @@ const Dropdown = forwardRef(
{toggled && portalMenu}
</Wrapper>
);
}
},
);
Dropdown.displayName = 'Dropdown';

View File

@@ -43,7 +43,7 @@ export const Fade: React.FC<FadeProps> = ({
}
});
},
{ threshold }
{ threshold },
);
observer.observe(div);
return () => observer.unobserve(div);

View File

@@ -53,5 +53,5 @@ storiesOf('Flags', module).add(
options: {
showPanel: false,
},
}
},
);

View File

@@ -33,7 +33,7 @@ const Wrapper = styled.div<{ size?: string; isHoverable?: boolean }>`
background-color: ${props =>
transparentize(
props.theme.HOVER_TRANSPARENTIZE_FILTER,
props.theme.HOVER_PRIMER_COLOR
props.theme.HOVER_PRIMER_COLOR,
)};
${props.size === 'tiny'
? css`

View File

@@ -46,5 +46,5 @@ storiesOf('Icons', module).add(
options: {
showPanel: false,
},
}
},
);

View File

@@ -100,7 +100,7 @@ const Icon = React.forwardRef(
onFocus,
...rest
}: Props,
ref?: React.Ref<HTMLDivElement>
ref?: React.Ref<HTMLDivElement>,
) => {
const theme = useTheme();
const defaultColor = color ?? theme.TYPE_LIGHT_GREY;
@@ -131,7 +131,7 @@ const Icon = React.forwardRef(
/>
</SvgWrapper>
);
}
},
);
export { Icon, Props as IconProps };

View File

@@ -16,7 +16,7 @@ storiesOf('Modals', module)
const description = text('description', 'Description');
const children = text(
'children',
'Ave Maria, gratia plena, Dominus tecum. Benedicta tu in mulieribus, et benedictus fructus ventris tui, Iesus.'
'Ave Maria, gratia plena, Dominus tecum. Benedicta tu in mulieribus, et benedictus fructus ventris tui, Iesus.',
);
const cancelable = boolean('cancelable', true);
const bottomBar = boolean('bottomBar', false);
@@ -54,7 +54,7 @@ storiesOf('Modals', module)
const description = text('description', 'Description');
const children = text(
'children',
'Ave Maria, gratia plena, Dominus tecum. Benedicta tu in mulieribus, et benedictus fructus ventris tui, Iesus.'
'Ave Maria, gratia plena, Dominus tecum. Benedicta tu in mulieribus, et benedictus fructus ventris tui, Iesus.',
);
const cancelable = boolean('cancelable', true);
const useFixedWidth = boolean('useFixedWidth', false);

View File

@@ -36,5 +36,5 @@ storiesOf('Timerange', module).add(
},
{
argTypes: { onChange: { action: 'onChange' } },
}
},
);

View File

@@ -73,5 +73,5 @@ storiesOf('Tooltip', module).add(
options: {
showPanel: false,
},
}
},
);

View File

@@ -22,7 +22,7 @@ storiesOf('Tooltip', module).add('Tooltip', () => {
Left: 'left',
Right: 'right',
},
'bottom'
'bottom',
);
return (

View File

@@ -14,7 +14,7 @@ storiesOf('Buttons', module).add('Button', () => {
Tertiary: 'tertiary',
Danger: 'danger',
},
null
null,
);
const size: any = select(
'Size',
@@ -22,7 +22,7 @@ storiesOf('Buttons', module).add('Button', () => {
'Default (large)': null,
Small: 'small',
},
null
null,
);
const iconOptions: any = {
@@ -39,7 +39,7 @@ storiesOf('Buttons', module).add('Button', () => {
'Default (left)': 'left',
Right: 'right',
},
'left'
'left',
)
: null;

View File

@@ -229,7 +229,7 @@ const Button = React.forwardRef(
onChange,
...rest
}: Props,
ref?: React.Ref<HTMLButtonElement>
ref?: React.Ref<HTMLButtonElement>,
) => {
const theme = useTheme();
const hasLabel = !!children;
@@ -267,7 +267,7 @@ const Button = React.forwardRef(
{isLoading && alignIcon === 'right' && Loader}
</Wrapper>
);
}
},
);
export { Button, Props as ButtonProps };

View File

@@ -76,5 +76,5 @@ storiesOf('Buttons', module).add(
options: {
showPanel: false,
},
}
},
);

View File

@@ -52,7 +52,7 @@ const Label = styled.div<IconWrapperProps>`
interface Props extends React.HTMLAttributes<HTMLDivElement> {
onClick: (
event: React.KeyboardEvent<HTMLElement> | React.MouseEvent<HTMLElement> | null
event: React.KeyboardEvent<HTMLElement> | React.MouseEvent<HTMLElement> | null,
) => any;
isChecked?: boolean;
}

View File

@@ -53,7 +53,7 @@ const Label = styled.div`
interface Props extends React.HTMLAttributes<HTMLDivElement> {
onClick: (
event: React.KeyboardEvent<HTMLElement> | React.MouseEvent<HTMLElement> | null
event: React.KeyboardEvent<HTMLElement> | React.MouseEvent<HTMLElement> | null,
) => any;
isChecked?: boolean;
}

View File

@@ -20,7 +20,7 @@ const selectStyle = (
borderRadius: number,
borderWidth: number,
theme: SuiteThemeColors,
selectState?: InputState
selectState?: InputState,
) => ({
singleValue: (base: Record<string, any>) => ({
...base,
@@ -41,7 +41,7 @@ const selectStyle = (
}),
control: (
base: Record<string, any>,
{ isDisabled, isFocused }: { isDisabled: boolean; isFocused: boolean }
{ isDisabled, isFocused }: { isDisabled: boolean; isFocused: boolean },
) => {
let height = variant === 'small' ? '36px' : '48px';
const borderColor = selectState ? getStateColor(selectState, theme) : theme.STROKE_GREY;
@@ -193,7 +193,7 @@ interface Option {
/** Custom Type Guards to check if options are grouped or not */
const isOptionGrouped = (
x: OptionsType<Option> | GroupedOptionsType<Option>
x: OptionsType<Option> | GroupedOptionsType<Option>,
): x is GroupedOptionsType<Option> => (x as GroupedOptionsType<Option>)[0]?.options !== undefined;
interface CommonProps extends Omit<SelectProps, 'components' | 'isSearchable'> {
@@ -364,7 +364,7 @@ const Select = ({
// Find the option
const optionToFocusOn = findOption(
optionsToSearchThrough,
searchedTerm.current
searchedTerm.current,
);
// Also get the last option, so I can scroll to it later
@@ -411,7 +411,7 @@ const Select = ({
borderRadius,
borderWidth,
theme,
state
state,
)}
isSearchable={isSearchable}
{...props}

View File

@@ -39,5 +39,5 @@ storiesOf('Loaders', module).add(
options: {
showPanel: false,
},
}
},
);

View File

@@ -17,7 +17,7 @@ storiesOf('Logos', module).add('Trezor', () => {
vertical: 'vertical',
symbol: 'symbol',
},
'horizontal'
'horizontal',
) as LogoType;
return <TrezorLogo type={type} {...(width ? { width } : {})} {...(height ? { height } : {})} />;

View File

@@ -82,5 +82,5 @@ storiesOf('Logos', module).add(
options: {
showPanel: false,
},
}
},
);

View File

@@ -13,7 +13,7 @@ const Wrapper = styled.div<{ paddingSize: string }>`
const getPaddingSize = (
largePadding?: boolean,
noPadding?: boolean,
noVerticalPadding?: boolean
noVerticalPadding?: boolean,
) => {
if (noPadding) return '0px';
if (noVerticalPadding) {

View File

@@ -89,5 +89,5 @@ storiesOf('Prompts', module).add(
options: {
showPanel: false,
},
}
},
);

View File

@@ -14,7 +14,7 @@ storiesOf('Typography', module).add('Heading', () => {
H1: 'H1',
H2: 'H2',
},
'H1'
'H1',
);
const textAlign: any = select(
'Align',
@@ -23,7 +23,7 @@ storiesOf('Typography', module).add('Heading', () => {
Right: 'right',
Center: 'center',
},
'left'
'left',
);
if (size === 'H1') {

View File

@@ -13,7 +13,7 @@ storiesOf('Typography', module).add('Link', () => {
Parent: '_parent',
Top: '_top',
},
null
null,
);
const href = text('URL', 'https://trezor.io');
const linkText = text('Text', 'This is a link.');

View File

@@ -12,7 +12,7 @@ storiesOf('Typography', module).add('Paragraph', () => {
Right: 'right',
Center: 'center',
},
'left'
'left',
);
const size: any = select(
'Size',
@@ -21,7 +21,7 @@ storiesOf('Typography', module).add('Paragraph', () => {
Small: 'small',
Tiny: 'tiny',
},
'normal'
'normal',
);
const weight: any = select(
'Weight',
@@ -29,7 +29,7 @@ storiesOf('Typography', module).add('Paragraph', () => {
Normal: 'normal',
Bold: 'bold',
},
'normal'
'normal',
);
return (

View File

@@ -63,5 +63,5 @@ storiesOf('Typography', module).add(
options: {
showPanel: false,
},
}
},
);

View File

@@ -40,7 +40,7 @@ export const useKeyPress = (targetKey: string) => {
export const useOnClickOutside = (
elementRefs: React.MutableRefObject<HTMLElement | null>[],
callback: (event: MouseEvent | TouchEvent) => void
callback: (event: MouseEvent | TouchEvent) => void,
) => {
useEffect(() => {
if (!elementRefs?.length) return;

View File

@@ -1,21 +0,0 @@
build
lib
# Dependency directory
node_modules
# OSX
.DS_Store
# Editors
.idea
.vscode
*.sublime-project
*.sublime-workspace
# Logs
logs
*.log
.yarnclean
coverage

View File

@@ -2,4 +2,4 @@
### Added
- 1.10.5 FW
- 1.10.5 FW

View File

@@ -1,41 +1,41 @@
[
{
"version": [2, 0, 27],
"directory": "bridge/{version}/",
"packages": [
{
"platform": ["deb64"],
"name": "Linux 64-bit (deb)",
"url": "trezor-bridge_{version}_amd64.deb"
},
{
"platform": ["rpm64"],
"name": "Linux 64-bit (rpm)",
"url": "trezor-bridge-{version}-1.x86_64.rpm"
},
{
"platform": ["deb32"],
"name": "Linux 32-bit (deb)",
"url": "trezor-bridge_{version}_i386.deb"
},
{
"platform": ["rpm32"],
"name": "Linux 32-bit (rpm)",
"url": "trezor-bridge-{version}-1.i386.rpm"
},
{
"platform": ["mac"],
"name": "macOS",
"url": "trezor-bridge-{version}.pkg",
"signature": "trezor-bridge-{version}.pkg.asc"
},
{
"platform": ["win32", "win64"],
"name": "Windows",
"url": "trezor-bridge-{version}-win32-install.exe",
"signature": "trezor-bridge-{version}-win32-install.exe.asc"
}
],
"changelog": "* Fix Certificate issue on Windows"
}
{
"version": [2, 0, 27],
"directory": "bridge/{version}/",
"packages": [
{
"platform": ["deb64"],
"name": "Linux 64-bit (deb)",
"url": "trezor-bridge_{version}_amd64.deb"
},
{
"platform": ["rpm64"],
"name": "Linux 64-bit (rpm)",
"url": "trezor-bridge-{version}-1.x86_64.rpm"
},
{
"platform": ["deb32"],
"name": "Linux 32-bit (deb)",
"url": "trezor-bridge_{version}_i386.deb"
},
{
"platform": ["rpm32"],
"name": "Linux 32-bit (rpm)",
"url": "trezor-bridge-{version}-1.i386.rpm"
},
{
"platform": ["mac"],
"name": "macOS",
"url": "trezor-bridge-{version}.pkg",
"signature": "trezor-bridge-{version}.pkg.asc"
},
{
"platform": ["win32", "win64"],
"name": "Windows",
"url": "trezor-bridge-{version}-win32-install.exe",
"signature": "trezor-bridge-{version}-win32-install.exe.asc"
}
],
"changelog": "* Fix Certificate issue on Windows"
}
]

View File

@@ -1,20 +0,0 @@
build
_old
coverage
# Dependency directory
node_modules
# OSX
.DS_Store
# Editors
.idea
.vscode
*.sublime-project
*.sublime-workspace
# Logs
logs
*.log
.yarnclean

View File

@@ -3,6 +3,7 @@
Bundle and build `trezor-connect` iframe.
### Usage
This build will be used by `suite-web` and `suite-desktop` packages.
Build files are copied into `suite-*/build/static` directory.

View File

@@ -1,31 +1,33 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>TrezorConnect | Trezor</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="Trezor info@trezor.io" />
<meta name="robots" content="index, follow" />
<meta name="title" content="TrezorConnect | Trezor" />
<meta http-equiv="Cache-control" content="no-cache" />
<meta http-equiv="pragma" content="no-cache" />
</head>
<body>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>TrezorConnect | Trezor</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="Trezor info@trezor.io" />
<meta name="robots" content="index, follow" />
<meta name="title" content="TrezorConnect | Trezor" />
<meta http-equiv="Cache-control" content="no-cache" />
<meta http-equiv="pragma" content="no-cache" />
</head>
<body>
<script type="text/javascript">
window.parent.postMessage(
{
event: 'UI_EVENT',
type: 'iframe-bootstrap',
},
'*',
);
<script type="text/javascript">
window.parent.postMessage({
event: 'UI_EVENT',
type: 'iframe-bootstrap',
}, '*');
const iframeScript = document.createElement('script');
iframeScript.setAttribute('type', 'text/javascript');
iframeScript.setAttribute('src', '<%= htmlWebpackPlugin.files.js[0] %>');
iframeScript.setAttribute('async', 'false');
document.body.appendChild(iframeScript);
</script>
</body>
const iframeScript = document.createElement('script');
iframeScript.setAttribute('type', 'text/javascript');
iframeScript.setAttribute('src', '<%= htmlWebpackPlugin.files.js[0] %>');
iframeScript.setAttribute('async', 'false');
document.body.appendChild(iframeScript);
</script>
</body>
</html>

View File

@@ -2,7 +2,7 @@
"extends": "../../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"lib": ["dom", "es2019"],
"lib": ["dom", "es2019"]
},
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["test/**/*.*"]

View File

@@ -1,2 +0,0 @@
node_modules
build

View File

@@ -1,10 +0,0 @@
{
"printWidth": 100,
"tabWidth": 4,
"singleQuote": true,
"trailingComma": "es5",
"arrowParens": "avoid",
"bracketSpacing": true,
"semi": true,
"useTabs": false
}

View File

@@ -1,27 +1,35 @@
# 1.3.0
- Added @trezor/utils dependency.
- Add possibility to fetch binary from local filesystem (in nodejs env)
- Added @trezor/utils dependency.
- Add possibility to fetch binary from local filesystem (in nodejs env)
# 1.2.1
- cross-fetch updated to 3.0.6
- cross-fetch updated to 3.0.6
# 1.2.0
- added condition for stripping firmware binary header based on `trezorlib` (python-trezor).
- exposed `modifyFirmware` function for this binary modification.
- removed unused `baseUrlBeta` params from `getBinary` function.
- added condition for stripping firmware binary header based on `trezorlib` (python-trezor).
- exposed `modifyFirmware` function for this binary modification.
- removed unused `baseUrlBeta` params from `getBinary` function.
# 1.1.0
- always provide latest release together with safe release
- always provide latest release together with safe release
# 1.0.8
- bump intermediary fw
- bump intermediary fw
# 1.0.7
- intermediary fw
- intermediary fw
# 1.0.5
- refactored types declarations (general cleanup).
- fix: types properly exported from the library.
- refactored types declarations (general cleanup).
- fix: types properly exported from the library.
# 1.0.0
- first release
- first release

View File

@@ -1,17 +1,17 @@
@trezor/rollout
=========
# @trezor/rollout
[![npm version](https://badge.fury.io/js/%40trezor%2Frollout.svg)](https://badge.fury.io/js/%40trezor%2Frollout)
Tldr: For historical reasons, Trezor devices firmware updates are not always straightforward.
Tldr: For historical reasons, Trezor devices firmware updates are not always straightforward.
__Incremental update__: not every firmware update can be applied on any installed firmware. This currently applies only for T1 devices. Releases definitions (see below), contain `min_bootloader_version` and `min_firmware_version`. Depending on whether the device is in bootloader mode or not, respective field (`min_bootloader_version` or `min_firmware_version`) should be observed and next firmware to apply should be evaulated againts them.
**Incremental update**: not every firmware update can be applied on any installed firmware. This currently applies only for T1 devices. Releases definitions (see below), contain `min_bootloader_version` and `min_firmware_version`. Depending on whether the device is in bootloader mode or not, respective field (`min_bootloader_version` or `min_firmware_version`) should be observed and next firmware to apply should be evaulated againts them.
__Incremental downgrade__: it is not possible to downgrade to lower version of bootloader. __Rollout module does not solve this__. Problem is, device will not tell you bootloader version if it is not in bootloader mode.
**Incremental downgrade**: it is not possible to downgrade to lower version of bootloader. **Rollout module does not solve this**. Problem is, device will not tell you bootloader version if it is not in bootloader mode.
__Rollout update__: sometimes we might want to offer firmware only to small portion of users. This behaviour is defined by `rollout` field and handled by this lib.
**Rollout update**: sometimes we might want to offer firmware only to small portion of users. This behaviour is defined by `rollout` field and handled by this lib.
**Firmware headers**: any firmware that is applied on firmware with bootloader >= 1.8.0 has old firmware header of 256 bytes, that should be removed before installing. This should be only temporary state and will be solved in future by introducing special intermediate firmwares for updating.
__Firmware headers__: any firmware that is applied on firmware with bootloader >= 1.8.0 has old firmware header of 256 bytes, that should be removed before installing. This should be only temporary state and will be solved in future by introducing special intermediate firmwares for updating.
### Publishing
[Follow instructions](../../docs/releases/npm-packages.md) how to publish @trezor package to npm registry.

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