-
Notifications
You must be signed in to change notification settings - Fork 59
/
Node.ts
213 lines (197 loc) · 7.92 KB
/
Node.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// eslint-disable-next-line max-classes-per-file
import BigNumber from 'bignumber.js';
import { OperationArguments, OperationOptions, OperationSpec } from '@azure/core-client';
import { userAgentPolicyName, setClientRequestIdPolicyName } from '@azure/core-rest-pipeline';
import {
genRequestQueuesPolicy, genCombineGetRequestsPolicy, genErrorFormatterPolicy,
genVersionCheckPolicy, genRetryOnFailurePolicy,
} from './utils/autorest';
import { Node as NodeApi, NodeOptionalParams, ErrorModel } from './apis/node';
import { mapObject } from './utils/other';
import { UnsupportedVersionError } from './utils/errors';
import { Encoded } from './utils/encoder';
import { ConsensusProtocolVersion } from './tx/builder/constants';
const bigIntPropertyNames = [
'balance', 'queryFee', 'fee', 'amount', 'nameFee', 'channelAmount',
'initiatorAmount', 'responderAmount', 'channelReserve', 'initiatorAmountFinal',
'responderAmountFinal', 'gasPrice', 'minGasPrice', 'deposit',
] as const;
const numberPropertyNames = [
'time', 'gas', 'gasUsed', 'nameSalt',
'nonce', 'nextNonce', 'height', 'blockHeight', 'topBlockHeight',
'ttl', 'nameTtl', 'clientTtl',
'inbound', 'outbound', 'peerCount', 'pendingTransactionsCount', 'effectiveAtHeight',
'version', 'solutions', 'round', 'minutes', 'utilization', 'difficulty', 'hashrate',
] as const;
class NodeTransformed extends NodeApi {
override async sendOperationRequest(
operationArguments: OperationArguments,
operationSpec: OperationSpec,
): Promise<any> {
const args = mapObject(
operationArguments,
([key, value]) => [key, this.#encodeArg(value)],
) as OperationArguments;
return this.#decodeRes(await super.sendOperationRequest(args, operationSpec));
}
#mapData(data: any, transform: {
bigInt: (v: any) => any;
number: (v: any) => any;
}): unknown {
if (Array.isArray(data)) return data.map((d) => this.#mapData(d, transform));
if (data != null && typeof data === 'object') {
return mapObject(data, ([key, value]) => {
if (value == null) return [key, value];
if (bigIntPropertyNames.some((k) => k === key)) return [key, transform.bigInt(value)];
if (numberPropertyNames.some((k) => k === key)) return [key, transform.number(value)];
return [key, this.#mapData(value, transform)];
});
}
return data;
}
#encodeArg(data: any): any {
return this.#mapData(data, {
bigInt: (value) => {
if (value instanceof BigNumber) return value.toFixed();
return value.toString();
},
number: (value) => value.toString(),
});
}
#decodeRes(data: any): any {
return this.#mapData(data, {
bigInt: (value) => BigInt(value),
number: (value) => +value,
});
}
}
type BigIntPropertyNames = typeof bigIntPropertyNames[number];
type NumberPropertyNames = typeof numberPropertyNames[number];
type PreserveOptional<NewType, OrigType> =
OrigType extends undefined ? NewType | undefined : NewType;
export type TransformNodeType<Type> =
Type extends (...args: infer Args) => infer Ret
? (...args: TransformNodeType<Args>) => TransformNodeType<Ret>
: Type extends [infer Item, ...infer Rest]
? [TransformNodeType<Item>, ...TransformNodeType<Rest>]
: Type extends Array<infer Item>
? Array<TransformNodeType<Item>>
: Type extends Promise<infer T>
? Promise<TransformNodeType<T>>
: Type extends { [P in any]: any }
? {
[Property in keyof Type]:
Property extends BigIntPropertyNames
? PreserveOptional<bigint, Type[Property]>
: Property extends NumberPropertyNames
? PreserveOptional<number, Type[Property]>
: Property extends 'txHash'
? PreserveOptional<Encoded.TxHash, Type[Property]>
: Property extends 'bytecode'
? PreserveOptional<Encoded.ContractBytearray, Type[Property]>
: TransformNodeType<Type[Property]>
}
: Type;
type NodeTransformedApi = new (...args: ConstructorParameters<typeof NodeApi>) => {
[Name in keyof InstanceType<typeof NodeApi>]:
Name extends 'pipeline' | 'sendRequest' | 'sendOperationRequest'
? NodeApi[Name] : TransformNodeType<NodeApi[Name]>
};
interface NodeInfo {
url: string;
nodeNetworkId: string;
version: string;
consensusProtocolVersion: ConsensusProtocolVersion;
}
export default class Node extends (NodeTransformed as unknown as NodeTransformedApi) {
/**
* @param url - Url for node API
* @param options - Options
* @param options.ignoreVersion - Don't ensure that the node is supported
* @param options.retryCount - Amount of extra requests to do in case of failure
* @param options.retryOverallDelay - Time in ms to wait between all retries
*/
constructor(
url: string,
{
ignoreVersion = false, retryCount = 3, retryOverallDelay = 800, ...options
}: NodeOptionalParams & {
ignoreVersion?: boolean;
retryCount?: number;
retryOverallDelay?: number;
} = {},
) {
const getVersion = async (opts: OperationOptions): Promise<string> => (
(await this._getCachedStatus(opts)).nodeVersion
);
// eslint-disable-next-line constructor-super
super(url, {
allowInsecureConnection: true,
additionalPolicies: [
...ignoreVersion ? [] : [genVersionCheckPolicy('node', getVersion, '6.2.0', '8.0.0')],
genRequestQueuesPolicy(),
genCombineGetRequestsPolicy(),
genRetryOnFailurePolicy(retryCount, retryOverallDelay),
genErrorFormatterPolicy((body: ErrorModel) => [
' ', body.reason, body.errorCode == null ? '' : ` (${body.errorCode})`,
].join('')),
],
...options,
});
this.pipeline.removePolicy({ name: userAgentPolicyName });
this.pipeline.removePolicy({ name: setClientRequestIdPolicyName });
// TODO: use instead our retry policy
this.pipeline.removePolicy({ name: 'defaultRetryPolicy' });
this.intAsString = true;
}
#cachedStatusPromise?: ReturnType<Node['getStatus']>;
async _getCachedStatus(options?: OperationOptions): ReturnType<Node['getStatus']> {
if (this.#cachedStatusPromise != null) return this.#cachedStatusPromise;
return this.getStatus(options);
}
// eslint-disable-next-line rulesdir/tsdoc-syntax
/** @ts-expect-error use code generation to create node class? */
override async getStatus(
...args: Parameters<InstanceType<NodeTransformedApi>['getStatus']>
): ReturnType<InstanceType<NodeTransformedApi>['getStatus']> {
const promise = super.getStatus(...args);
promise.then(() => { this.#cachedStatusPromise = promise; }, () => {});
return promise;
}
/**
* Returns network ID provided by node.
* This method won't do extra requests on subsequent calls.
*/
async getNetworkId(): Promise<string> {
return (await this._getCachedStatus()).networkId;
}
async getNodeInfo(): Promise<NodeInfo> {
const {
nodeVersion,
networkId: nodeNetworkId,
protocols,
topBlockHeight,
} = await this.getStatus();
const consensusProtocolVersion = protocols
.filter(({ effectiveAtHeight }) => topBlockHeight >= effectiveAtHeight)
.reduce(
(acc, p) => (p.effectiveAtHeight > acc.effectiveAtHeight ? p : acc),
{ effectiveAtHeight: -1, version: 0 },
)
.version;
if (ConsensusProtocolVersion[consensusProtocolVersion] == null) {
const version = consensusProtocolVersion.toString();
const versions = Object.values(ConsensusProtocolVersion)
.filter((el) => typeof el === 'number').map((el) => +el);
const geVersion = Math.min(...versions).toString();
const ltVersion = (Math.max(...versions) + 1).toString();
throw new UnsupportedVersionError('consensus protocol', version, geVersion, ltVersion);
}
return {
url: this.$host,
nodeNetworkId,
version: nodeVersion,
consensusProtocolVersion,
};
}
}