@tetherto/wdk-provider-failover 1.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +176 -0
- package/README.md +156 -0
- package/index.js +1 -0
- package/package.json +29 -0
- package/src/utils.js +108 -0
- package/src/wdk-provider-failover.js +220 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# @tetherto/wdk-provider-failover
|
|
2
|
+
|
|
3
|
+
A resilient wrapper for WDK wallet instances that provides automatic failover across multiple provider configurations with configurable retry logic.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Automatic failover** - Cascades through multiple provider configurations when failures occur
|
|
8
|
+
- **Configurable retries** - Retry failed operations with exponential backoff and jitter
|
|
9
|
+
- **Lazy instantiation** - Wallet instances are created only when needed
|
|
10
|
+
- **Proxy-based** - Transparent wrapper that preserves the original wallet API
|
|
11
|
+
- **Lifecycle management** - Proper cleanup of resources via `dispose()`
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @tetherto/wdk-provider-failover
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
### Basic Example
|
|
22
|
+
|
|
23
|
+
```javascript
|
|
24
|
+
import { createFallbackWallet } from '@tetherto/wdk-provider-failover'
|
|
25
|
+
import { WalletAccountReadOnlyEvm } from '@tetherto/wdk-wallet-evm'
|
|
26
|
+
|
|
27
|
+
const wallet = createFallbackWallet(
|
|
28
|
+
WalletAccountReadOnlyEvm,
|
|
29
|
+
['0x742d35Cc6634C0532925a3b844Bc9e7595f...'], // constructor args
|
|
30
|
+
{
|
|
31
|
+
primary: { provider: 'https://mainnet.infura.io/v3/YOUR_KEY' },
|
|
32
|
+
fallbacks: [
|
|
33
|
+
{ provider: 'https://eth.llamarpc.com' },
|
|
34
|
+
{ provider: 'https://ethereum.publicnode.com' }
|
|
35
|
+
]
|
|
36
|
+
}
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
// Use the wallet as normal - failover is automatic
|
|
40
|
+
const balance = await wallet.getBalance()
|
|
41
|
+
|
|
42
|
+
// Clean up when done
|
|
43
|
+
await wallet.dispose()
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### With Custom Options
|
|
47
|
+
|
|
48
|
+
```javascript
|
|
49
|
+
const wallet = createFallbackWallet(
|
|
50
|
+
WalletAccountReadOnlyEvm,
|
|
51
|
+
[address],
|
|
52
|
+
{
|
|
53
|
+
primary: { provider: primaryRpcUrl },
|
|
54
|
+
fallbacks: [
|
|
55
|
+
{ provider: fallbackRpcUrl1 },
|
|
56
|
+
{ provider: fallbackRpcUrl2 }
|
|
57
|
+
],
|
|
58
|
+
fallbackOptions: {
|
|
59
|
+
timeout: 5000, // 5 second timeout per call
|
|
60
|
+
maxRetries: 3, // Retry current provider 3 times before switching
|
|
61
|
+
retryDelay: 1000, // Base delay between retries (ms)
|
|
62
|
+
exponentialBackoff: true, // Double delay on each retry
|
|
63
|
+
jitter: true, // Add randomness to prevent thundering herd
|
|
64
|
+
fallbackMethods: ['getBalance', 'getTransactions'], // Only wrap specific methods
|
|
65
|
+
logger: customLogger, // Custom logging function
|
|
66
|
+
onFallback: (index, config) => {
|
|
67
|
+
console.log(`Switching to provider ${index}`)
|
|
68
|
+
},
|
|
69
|
+
onConfigSwitch: (index, config) => {
|
|
70
|
+
console.log(`Successfully using provider ${index}`)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## API
|
|
78
|
+
|
|
79
|
+
### `createFallbackWallet(WalletClass, constructorArgs, config)`
|
|
80
|
+
|
|
81
|
+
Factory function that creates a failover-wrapped wallet instance.
|
|
82
|
+
|
|
83
|
+
**Parameters:**
|
|
84
|
+
|
|
85
|
+
| Parameter | Type | Description |
|
|
86
|
+
|-----------|------|-------------|
|
|
87
|
+
| `WalletClass` | `class` | The wallet class to instantiate |
|
|
88
|
+
| `constructorArgs` | `array` | Arguments passed to the wallet constructor (before config) |
|
|
89
|
+
| `config` | `object` | Configuration object (see below) |
|
|
90
|
+
|
|
91
|
+
**Config Object:**
|
|
92
|
+
|
|
93
|
+
| Property | Type | Description |
|
|
94
|
+
|----------|------|-------------|
|
|
95
|
+
| `primary` | `object` | Primary provider configuration |
|
|
96
|
+
| `fallbacks` | `array` | Array of fallback provider configurations |
|
|
97
|
+
| `fallbackOptions` | `object` | Options for failover behavior (see below) |
|
|
98
|
+
|
|
99
|
+
**Fallback Options:**
|
|
100
|
+
|
|
101
|
+
| Option | Type | Default | Description |
|
|
102
|
+
|--------|------|---------|-------------|
|
|
103
|
+
| `timeout` | `number` | `10000` | Timeout per method call (ms) |
|
|
104
|
+
| `maxRetries` | `number` | `3` | Retries per provider before switching |
|
|
105
|
+
| `retryDelay` | `number` | `1000` | Base delay between retries (ms) |
|
|
106
|
+
| `exponentialBackoff` | `boolean` | `true` | Double delay on each retry |
|
|
107
|
+
| `jitter` | `boolean` | `true` | Add ±15% randomness to delays |
|
|
108
|
+
| `fallbackMethods` | `string[]` | `[]` | Methods to wrap (empty = all methods) |
|
|
109
|
+
| `logger` | `function` | `console` | Custom logger function |
|
|
110
|
+
| `onFallback` | `function` | - | Called when switching to a fallback provider |
|
|
111
|
+
| `onConfigSwitch` | `function` | - | Called on successful operation after retries |
|
|
112
|
+
|
|
113
|
+
### Proxy Methods
|
|
114
|
+
|
|
115
|
+
The returned proxy exposes additional utility methods:
|
|
116
|
+
|
|
117
|
+
| Method | Returns | Description |
|
|
118
|
+
|--------|---------|-------------|
|
|
119
|
+
| `dispose()` | `Promise<void>` | Disposes all wallet instances |
|
|
120
|
+
| `getActiveIndex()` | `number` | Current active provider index |
|
|
121
|
+
| `getActiveConfig()` | `object` | Current active provider config |
|
|
122
|
+
| `getInstancesCount()` | `number` | Total number of configured providers |
|
|
123
|
+
| `switchTo(index)` | `number` | Manually switch to a specific provider |
|
|
124
|
+
| `getInstanceUnsafe()` | `object` | Get the current wallet instance directly |
|
|
125
|
+
|
|
126
|
+
## How It Works
|
|
127
|
+
|
|
128
|
+
1. When a method is called on the proxy, it attempts the operation on the current provider
|
|
129
|
+
2. If the call fails or times out, it retries up to `maxRetries` times with backoff
|
|
130
|
+
3. After exhausting retries, it switches to the next provider in the cascade
|
|
131
|
+
4. This continues until success or all providers have been exhausted
|
|
132
|
+
5. On success, callbacks are invoked to notify of the active configuration
|
|
133
|
+
|
|
134
|
+
```
|
|
135
|
+
┌─────────────┐ fail ┌─────────────┐ fail ┌─────────────┐
|
|
136
|
+
│ Primary │──── retry ───▶│ Fallback 1 │──── retry ───▶│ Fallback 2 │
|
|
137
|
+
│ Provider │ (3 times) │ Provider │ (3 times) │ Provider │
|
|
138
|
+
└─────────────┘ └─────────────┘ └─────────────┘
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## Custom Logger
|
|
142
|
+
|
|
143
|
+
The logger function receives structured log data:
|
|
144
|
+
|
|
145
|
+
```javascript
|
|
146
|
+
const logger = (level, message, meta) => {
|
|
147
|
+
// level: 'debug' | 'info' | 'warn' | 'error'
|
|
148
|
+
// message: string description
|
|
149
|
+
// meta: object with additional context
|
|
150
|
+
console.log(`[${level}] ${message}`, meta)
|
|
151
|
+
}
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
Apache-2.0
|
package/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createFallbackWallet, WdkProviderFailover } from './src/wdk-provider-failover.js'
|
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tetherto/wdk-provider-failover",
|
|
3
|
+
"version": "1.0.0-beta.1",
|
|
4
|
+
"description": "A simple package to initialize WDK wallet instances with failover capabilities.",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --detectOpenHandles --forceExit",
|
|
9
|
+
"build:types": "tsc",
|
|
10
|
+
"lint": "standard",
|
|
11
|
+
"lint:fix": "standard --fix"
|
|
12
|
+
},
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"@tetherto/wdk-wallet": "1.0.0-beta.6"
|
|
15
|
+
},
|
|
16
|
+
"devDependencies": {
|
|
17
|
+
"cross-env": "7.0.3",
|
|
18
|
+
"jest": "29.7.0",
|
|
19
|
+
"rimraf": "6.0.1",
|
|
20
|
+
"standard": "17.1.2",
|
|
21
|
+
"typescript": "5.8.3",
|
|
22
|
+
"@tetherto/wdk-wallet-evm": "1.0.0-beta.4"
|
|
23
|
+
},
|
|
24
|
+
"standard": {
|
|
25
|
+
"ignore": [
|
|
26
|
+
"tests/**/*.js"
|
|
27
|
+
]
|
|
28
|
+
}
|
|
29
|
+
}
|
package/src/utils.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// Copyright 2024 Tether Operations Limited
|
|
2
|
+
//
|
|
3
|
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
// you may not use this file except in compliance with the License.
|
|
5
|
+
// You may obtain a copy of the License at
|
|
6
|
+
//
|
|
7
|
+
// http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
//
|
|
9
|
+
// Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
// See the License for the specific language governing permissions and
|
|
13
|
+
// limitations under the License.
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Default console-backed logger used when no custom logger is provided.
|
|
17
|
+
* Prefixes messages to make them easier to filter during debugging.
|
|
18
|
+
* @param {'debug'|'info'|'warn'|'error'} level
|
|
19
|
+
* @param {string} message
|
|
20
|
+
* @param {Record<string, unknown>} [meta]
|
|
21
|
+
*/
|
|
22
|
+
const DEFAULT_LOGGER = (level, message, meta = {}) => {
|
|
23
|
+
const payload = Object.keys(meta).length ? ` ${JSON.stringify(meta)}` : ''
|
|
24
|
+
// eslint-disable-next-line no-console
|
|
25
|
+
console[level === 'debug' ? 'log' : level](`[wdk-fallback] ${message}${payload}`)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Creates a resilient logger wrapper around an optional custom logger.
|
|
30
|
+
* If the custom logger throws, falls back to the default logger.
|
|
31
|
+
* @param {(level: 'debug'|'info'|'warn'|'error', message: string, meta?: Record<string, unknown>) => void} [customLogger]
|
|
32
|
+
*/
|
|
33
|
+
export const createLogger = (customLogger) => {
|
|
34
|
+
if (!customLogger) return DEFAULT_LOGGER
|
|
35
|
+
return (level, message, meta) => {
|
|
36
|
+
try { customLogger(level, message, meta) } catch (_) { DEFAULT_LOGGER(level, message, meta) }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Resolves after `ms` milliseconds or rejects early on AbortSignal.
|
|
42
|
+
* @param {number} ms
|
|
43
|
+
* @param {AbortSignal} [resolveSignal]
|
|
44
|
+
*/
|
|
45
|
+
export const delay = (ms, resolveSignal) => new Promise((resolve, reject) => {
|
|
46
|
+
const timer = setTimeout(resolve, ms)
|
|
47
|
+
if (resolveSignal) {
|
|
48
|
+
if (resolveSignal.aborted) {
|
|
49
|
+
clearTimeout(timer)
|
|
50
|
+
reject(Object.assign(new Error('Aborted'), { name: 'AbortError' }))
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
const onAbort = () => {
|
|
54
|
+
clearTimeout(timer)
|
|
55
|
+
resolveSignal.removeEventListener('abort', onAbort)
|
|
56
|
+
reject(Object.assign(new Error('Aborted'), { name: 'AbortError' }))
|
|
57
|
+
}
|
|
58
|
+
resolveSignal.addEventListener('abort', onAbort)
|
|
59
|
+
}
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Races a promise against a timeout. Rejects with Error(reason) on timeout.
|
|
64
|
+
* @template T
|
|
65
|
+
* @param {Promise<T>} promise
|
|
66
|
+
* @param {number} ms
|
|
67
|
+
* @param {string} [reason='Timeout']
|
|
68
|
+
* @returns {Promise<T>}
|
|
69
|
+
*/
|
|
70
|
+
export const withTimeout = async (promise, ms, reason = 'Timeout') => {
|
|
71
|
+
if (!ms || ms <= 0) return promise
|
|
72
|
+
const controller = new AbortController()
|
|
73
|
+
const timeout = setTimeout(() => controller.abort(reason), ms)
|
|
74
|
+
try {
|
|
75
|
+
const result = await Promise.race([
|
|
76
|
+
promise,
|
|
77
|
+
new Promise((resolve, reject) => {
|
|
78
|
+
controller.signal.addEventListener('abort', () => reject(new Error(reason)))
|
|
79
|
+
})
|
|
80
|
+
])
|
|
81
|
+
return result
|
|
82
|
+
} finally {
|
|
83
|
+
clearTimeout(timeout)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Deep clones and redacts sensitive-like keys in a config object for logging.
|
|
89
|
+
* Keys containing: secret, seed, private, key
|
|
90
|
+
* @param {unknown} config
|
|
91
|
+
* @returns {unknown}
|
|
92
|
+
*/
|
|
93
|
+
// Removed by design: do not transform runtime configs; avoid logging sensitive data instead.
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Computes backoff delay given the attempt number and options.
|
|
97
|
+
* @param {number} attempt - 1-based attempt number
|
|
98
|
+
* @param {number} baseDelay
|
|
99
|
+
* @param {boolean} exponentialBackoff
|
|
100
|
+
* @param {boolean} jitter
|
|
101
|
+
* @returns {number}
|
|
102
|
+
*/
|
|
103
|
+
export const computeBackoffDelay = (attempt, baseDelay, exponentialBackoff, jitter) => {
|
|
104
|
+
const base = exponentialBackoff ? baseDelay * Math.pow(2, attempt) : baseDelay
|
|
105
|
+
if (!jitter) return base
|
|
106
|
+
const rand = Math.random() * base * 0.3
|
|
107
|
+
return base - base * 0.15 + rand
|
|
108
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// Copyright 2024 Tether Operations Limited
|
|
2
|
+
//
|
|
3
|
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
// you may not use this file except in compliance with the License.
|
|
5
|
+
// You may obtain a copy of the License at
|
|
6
|
+
//
|
|
7
|
+
// http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
//
|
|
9
|
+
// Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
// See the License for the specific language governing permissions and
|
|
13
|
+
// limitations under the License.
|
|
14
|
+
|
|
15
|
+
'use strict'
|
|
16
|
+
|
|
17
|
+
import { createLogger, delay, withTimeout, computeBackoffDelay } from './utils.js'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {import('@wdk/wallet').IWalletAccountReadOnly} IWalletAccountReadOnly
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Default behavior for the fallback mechanism.
|
|
25
|
+
* @type {import('../types/src/wdk-fallback-types.d.ts').FallbackOptions}
|
|
26
|
+
*/
|
|
27
|
+
const DEFAULT_OPTIONS = {
|
|
28
|
+
timeout: 10000,
|
|
29
|
+
maxRetries: 3,
|
|
30
|
+
retryDelay: 1000,
|
|
31
|
+
exponentialBackoff: true,
|
|
32
|
+
jitter: true,
|
|
33
|
+
fallbackMethods: []
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export class WdkProviderFailover {
|
|
37
|
+
constructor (WalletClass, constructorArgs = [], config) {
|
|
38
|
+
this._WalletClass = WalletClass
|
|
39
|
+
this._originalArgs = Array.isArray(constructorArgs) ? constructorArgs : [constructorArgs]
|
|
40
|
+
this._primary = config?.primary
|
|
41
|
+
this._fallbacks = Array.isArray(config?.fallbacks) ? config.fallbacks : []
|
|
42
|
+
this._options = { ...DEFAULT_OPTIONS, ...(config?.fallbackOptions || {}) }
|
|
43
|
+
this._logger = createLogger(this._options.logger)
|
|
44
|
+
this._configs = [this._primary, ...this._fallbacks].filter((c) => c != null)
|
|
45
|
+
this._instances = new Array(this._configs.length)
|
|
46
|
+
this._activeIndex = 0
|
|
47
|
+
this._disposed = false
|
|
48
|
+
|
|
49
|
+
const handler = {
|
|
50
|
+
get: (_target, prop, receiver) => {
|
|
51
|
+
// Utility controls exposed on the proxy object
|
|
52
|
+
if (prop === 'dispose') return this.dispose.bind(this)
|
|
53
|
+
if (prop === 'getActiveIndex') return () => this._activeIndex
|
|
54
|
+
if (prop === 'getActiveConfig') return () => this._configs[this._activeIndex]
|
|
55
|
+
if (prop === 'getInstanceUnsafe') return () => this._getOrCreateInstance(this._activeIndex)
|
|
56
|
+
if (prop === 'switchTo') return (index) => this._switchTo(index)
|
|
57
|
+
if (prop === 'getInstancesCount') return () => this._configs.length
|
|
58
|
+
|
|
59
|
+
// Defer instance creation until a property is accessed
|
|
60
|
+
const active = this._getOrCreateInstance(this._activeIndex)
|
|
61
|
+
const value = Reflect.get(active, prop, receiver)
|
|
62
|
+
|
|
63
|
+
if (typeof value !== 'function') return value
|
|
64
|
+
|
|
65
|
+
const methodName = String(prop)
|
|
66
|
+
const shouldWrap = this._shouldWrapMethod(methodName)
|
|
67
|
+
if (!shouldWrap) return value.bind(active)
|
|
68
|
+
|
|
69
|
+
return async (...args) => {
|
|
70
|
+
this._ensureNotDisposed()
|
|
71
|
+
const maxRetries = Math.max(0, this._options.maxRetries ?? 0)
|
|
72
|
+
const hasMultipleConfigs = this._configs.length > 1
|
|
73
|
+
let lastError
|
|
74
|
+
const configsTried = new Set()
|
|
75
|
+
let currentConfigAttempt = 0
|
|
76
|
+
|
|
77
|
+
// try each config, with retries per config
|
|
78
|
+
while (true) {
|
|
79
|
+
const currentIndex = this._activeIndex
|
|
80
|
+
const instance = this._getOrCreateInstance(currentIndex)
|
|
81
|
+
const config = this._configs[currentIndex]
|
|
82
|
+
|
|
83
|
+
try {
|
|
84
|
+
const call = value.apply(instance, args)
|
|
85
|
+
const result = await withTimeout(Promise.resolve(call), this._options.timeout)
|
|
86
|
+
// Notify if we switched configs (not on first attempt of first config)
|
|
87
|
+
if (configsTried.size > 0 || currentConfigAttempt > 0) {
|
|
88
|
+
this._options.onConfigSwitch?.(currentIndex, config)
|
|
89
|
+
}
|
|
90
|
+
return result
|
|
91
|
+
} catch (error) {
|
|
92
|
+
lastError = error
|
|
93
|
+
configsTried.add(currentIndex)
|
|
94
|
+
// Avoid logging raw configs to prevent leaking sensitive data
|
|
95
|
+
this._logger('warn', `${methodName} failed on index=${currentIndex}`, { error: String(error) })
|
|
96
|
+
|
|
97
|
+
// Decide: retry current config or switch to next provider
|
|
98
|
+
const shouldRetryCurrentConfig = currentConfigAttempt < maxRetries
|
|
99
|
+
const shouldTryNextProvider = hasMultipleConfigs && configsTried.size < this._configs.length
|
|
100
|
+
|
|
101
|
+
if (shouldRetryCurrentConfig) {
|
|
102
|
+
// Retry the current config
|
|
103
|
+
currentConfigAttempt++
|
|
104
|
+
const waitMs = computeBackoffDelay(currentConfigAttempt, this._options.retryDelay, this._options.exponentialBackoff, this._options.jitter)
|
|
105
|
+
await delay(waitMs)
|
|
106
|
+
continue
|
|
107
|
+
} else if (shouldTryNextProvider) {
|
|
108
|
+
// Switch to next provider
|
|
109
|
+
const nextIndex = this._chooseNextIndex(currentIndex)
|
|
110
|
+
if (nextIndex !== currentIndex && !configsTried.has(nextIndex)) {
|
|
111
|
+
this._options.onFallback?.(nextIndex, this._configs[nextIndex])
|
|
112
|
+
this._switchTo(nextIndex)
|
|
113
|
+
currentConfigAttempt = 0 // Reset retry counter for new config
|
|
114
|
+
// Small delay before trying next provider
|
|
115
|
+
await delay(this._options.retryDelay)
|
|
116
|
+
continue
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// No more retries and no more providers to try
|
|
121
|
+
break
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
throw lastError || new Error('Unknown error')
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const instance = new Proxy({}, handler)
|
|
131
|
+
return instance
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Ensures the proxy has not been disposed. */
|
|
135
|
+
_ensureNotDisposed () {
|
|
136
|
+
if (this._disposed) throw new Error('WdkProviderFailover disposed')
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Determines whether a method should be wrapped with the failover logic.
|
|
141
|
+
* When `fallbackMethods` is provided, only those methods are wrapped.
|
|
142
|
+
* @param {string} methodName
|
|
143
|
+
* @returns {boolean}
|
|
144
|
+
*/
|
|
145
|
+
_shouldWrapMethod (methodName) {
|
|
146
|
+
const { fallbackMethods } = this._options
|
|
147
|
+
if (fallbackMethods && fallbackMethods.length > 0) return fallbackMethods.includes(methodName)
|
|
148
|
+
return true
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Lazily creates or returns the wallet instance for a given configuration index.
|
|
153
|
+
* Uses the original constructor arguments as-is, without cloning.
|
|
154
|
+
* @param {number} index
|
|
155
|
+
* @returns {IWalletAccountReadOnly}
|
|
156
|
+
*/
|
|
157
|
+
_getOrCreateInstance (index) {
|
|
158
|
+
this._ensureNotDisposed()
|
|
159
|
+
if (!this._instances[index]) {
|
|
160
|
+
const cfg = this._configs[index]
|
|
161
|
+
// Avoid logging raw configs to prevent leaking sensitive data
|
|
162
|
+
this._logger('info', 'Instantiating wallet', { index })
|
|
163
|
+
this._instances[index] = new this._WalletClass(...this._originalArgs, cfg)
|
|
164
|
+
}
|
|
165
|
+
return this._instances[index]
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Chooses the next config index to try. Default strategy is round-robin.
|
|
170
|
+
* @param {number} currentIndex
|
|
171
|
+
* @returns {number}
|
|
172
|
+
*/
|
|
173
|
+
_chooseNextIndex (currentIndex) {
|
|
174
|
+
if (this._configs.length <= 1) return currentIndex
|
|
175
|
+
return (currentIndex + 1) % this._configs.length
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Switches the active configuration index.
|
|
180
|
+
* @param {number} index
|
|
181
|
+
* @returns {number} The new active index
|
|
182
|
+
*/
|
|
183
|
+
_switchTo (index) {
|
|
184
|
+
if (index < 0 || index >= this._configs.length) return this._activeIndex
|
|
185
|
+
this._activeIndex = index
|
|
186
|
+
return this._activeIndex
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Disposes all lazily created instances (best-effort), clears references,
|
|
191
|
+
* and turns the internal logger into a no-op. Safe to call multiple times.
|
|
192
|
+
* @returns {Promise<void>}
|
|
193
|
+
*/
|
|
194
|
+
async dispose () {
|
|
195
|
+
if (this._disposed) return
|
|
196
|
+
this._disposed = true
|
|
197
|
+
// Dispose each instantiated wallet (best-effort) and clear the slot to release references
|
|
198
|
+
for (let i = 0; i < this._instances.length; i++) {
|
|
199
|
+
const inst = this._instances[i]
|
|
200
|
+
if (inst && typeof inst.dispose === 'function') {
|
|
201
|
+
try { await inst.dispose() } catch (_) {}
|
|
202
|
+
}
|
|
203
|
+
this._instances[i] = undefined
|
|
204
|
+
}
|
|
205
|
+
// Clear references to help GC and prevent accidental reuse after disposal
|
|
206
|
+
this._instances = []
|
|
207
|
+
this._configs = []
|
|
208
|
+
this._primary = undefined
|
|
209
|
+
this._fallbacks = []
|
|
210
|
+
this._originalArgs = []
|
|
211
|
+
this._WalletClass = undefined
|
|
212
|
+
this._activeIndex = 0
|
|
213
|
+
// Replace logger with no-op
|
|
214
|
+
this._logger = () => {}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export const createFallbackWallet = (WalletClass, constructorArgs = [], config) => {
|
|
219
|
+
return new WdkProviderFailover(WalletClass, constructorArgs, config)
|
|
220
|
+
}
|