forked from dfinity/agent-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
226 lines (203 loc) · 7.3 KB
/
index.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
214
215
216
217
218
219
220
221
222
223
224
225
226
/** @module CanisterStatus */
import { lebDecode, PipeArrayBuffer } from '@dfinity/candid';
import { Principal } from '@dfinity/principal';
import { HttpAgent, HttpAgentOptions, Cbor, Certificate, toHex } from '..';
/**
* Types of an entry on the canisterStatus map.
* An entry of null indicates that the request failed, due to lack of permissions or the result being missing.
*/
export type Status = string | ArrayBuffer | Date | ArrayBuffer[] | Principal[] | bigint | null;
/**
* Interface to define a custom path. Nested paths will be represented as individual buffers, and can be created from text using {@link TextEncoder}
*/
export interface CustomPath {
key: string;
path: ArrayBuffer[];
decodeStrategy: 'cbor' | 'hex' | 'leb128' | 'raw';
}
/**
* Interface to request metadata from the icp:public or icp:private sections.
* Similar to {@link CustomPath}, but accepts a simple string argument.
* Private metadata will require the ${@link Identity} used by the ${@link HttpAgent} will need to be requested using an identity that controlls the canister.
*/
export interface MetaData {
kind: 'medadata';
key: string;
path: string | ArrayBuffer;
decodeStrategy: 'cbor' | 'hex' | 'leb128' | 'raw';
}
/**
* Pre-configured fields for canister status paths
*/
export type Path =
| 'time'
| 'controllers'
| 'subnet'
| 'module_hash'
| 'candid'
| MetaData
| CustomPath;
export type StatusMap = Map<Path | string, Status>;
export type CanisterStatusOptions = {
canisterId: Principal;
agent: HttpAgent;
paths?: Path[] | Set<Path>;
};
/**
*
* @param {CanisterStatusOptions} options {@link CanisterStatusOptions}
* @param {CanisterStatusOptions['canisterId']} options.canisterId {@link Principal}
* @param {CanisterStatusOptions['agent']} options.agent {@link HttpAgent} optional authenticated agent to use to make the canister request. Useful for accessing private metadata under icp:private
* @param {CanisterStatusOptions['paths']} options.paths {@link Path[]}
* @returns {Status} object populated with data from the requested paths
* @example
* const status = await canisterStatus({
* paths: ['controllers', 'candid'],
* ...options
* });
*
* const controllers = status.get('controllers');
*/
export const request = async (options: {
canisterId: Principal;
agent: HttpAgent;
paths?: Path[] | Set<Path>;
}): Promise<StatusMap> => {
const { canisterId, agent, paths } = options;
const uniquePaths = [...new Set(paths)];
// Map path options to their correct formats
const encodedPaths = uniquePaths.map(path => {
return encodePath(path, canisterId);
});
const status = new Map<string | Path, Status>();
const promises = uniquePaths.map((path, index) => {
return (async () => {
try {
const response = await agent.readState(canisterId, {
paths: [encodedPaths[index]],
});
const cert = await Certificate.create(response.certificate, agent.rootKey, canisterId);
const data = cert.lookup(encodePath(uniquePaths[index], canisterId));
if (!data) {
// Typically, the cert lookup will throw
console.warn(`Expected to find result for path ${path}, but instead found nothing.`);
if (typeof path === 'string') {
status.set(path, null);
} else {
status.set(path.key, null);
}
} else {
switch (path) {
case 'time': {
status.set(path, decodeTime(data));
break;
}
case 'controllers': {
status.set(path, decodeControllers(data));
break;
}
case 'module_hash': {
status.set(path, decodeHex(data));
break;
}
case 'candid': {
status.set(path, new TextDecoder().decode(data));
break;
}
default: {
// Check for CustomPath signature
if (typeof path !== 'string' && 'key' in path && 'path' in path) {
switch (path.decodeStrategy) {
case 'raw':
status.set(path.key, data);
break;
case 'leb128': {
status.set(path.key, decodeLeb128(data));
break;
}
case 'cbor': {
status.set(path.key, decodeCbor(data));
break;
}
case 'hex': {
status.set(path.key, decodeHex(data));
break;
}
}
}
}
}
}
} catch (error) {
error;
if (typeof path !== 'string' && 'key' in path && 'path' in path) {
status.set(path.key, null);
} else {
status.set(path, null);
}
console.warn(`Expected to find result for path ${path}, but instead found nothing.`);
}
})();
});
// Fetch all values separately, as each option can fail
await Promise.all(promises);
return status;
};
export const encodePath = (path: Path, canisterId: Principal): ArrayBuffer[] => {
const encoder = new TextEncoder();
const encode = (arg: string): ArrayBuffer => {
return new DataView(encoder.encode(arg).buffer).buffer;
};
const canisterBuffer = new DataView(canisterId.toUint8Array().buffer).buffer;
switch (path) {
case 'time':
return [encode('time')];
case 'controllers':
return [encode('canister'), canisterBuffer, encode('controllers')];
case 'module_hash':
return [encode('canister'), canisterBuffer, encode('module_hash')];
case 'subnet':
return [encode('subnet')];
case 'candid':
return [encode('canister'), canisterBuffer, encode('metadata'), encode('candid:service')];
default: {
// Check for CustomPath signature
if ('key' in path && 'path' in path) {
// For simplified metadata queries
if (typeof path['path'] === 'string' || path['path'] instanceof ArrayBuffer) {
const metaPath = path.path;
const encoded = typeof metaPath === 'string' ? encode(metaPath) : metaPath;
return [encode('canister'), canisterBuffer, encode('metadata'), encoded];
// For non-metadata, return the provided custompath
} else {
return path['path'];
}
}
}
}
throw new Error(
`An unexpeected error was encountered while encoding your path for canister status. Please ensure that your path, ${path} was formatted correctly.`,
);
};
const decodeHex = (buf: ArrayBuffer): string => {
return toHex(buf);
};
const decodeLeb128 = (buf: ArrayBuffer): bigint => {
return lebDecode(new PipeArrayBuffer(buf));
};
const decodeCbor = (buf: ArrayBuffer): ArrayBuffer[] => {
return Cbor.decode(buf);
};
// time is a LEB128-encoded Nat
const decodeTime = (buf: ArrayBuffer): Date => {
const decoded = decodeLeb128(buf);
return new Date(Number(decoded / BigInt(1_000_000)));
};
// Controllers are CBOR-encoded buffers, starting with a Tag we don't need
const decodeControllers = (buf: ArrayBuffer): Principal[] => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [tag, ...controllersRaw] = decodeCbor(buf);
return controllersRaw.map((buf: ArrayBuffer) => {
return Principal.fromUint8Array(new Uint8Array(buf));
});
};