-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathdelegationStorage.ts
More file actions
213 lines (182 loc) · 6.1 KB
/
Copy pathdelegationStorage.ts
File metadata and controls
213 lines (182 loc) · 6.1 KB
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
import { type Hex, toHex } from 'viem';
import { getDelegationHashOffchain } from '../delegation';
import type { Delegation } from '../types';
type ErrorResponse = {
error: string;
data?: any;
};
export type APIStoreDelegationResponse = {
delegationHash: Hex;
};
/**
* Represents the allowed filters when querying the data store for delegations.
*/
export enum DelegationStoreFilter {
Given = 'GIVEN',
Received = 'RECEIVED',
All = 'ALL',
}
/**
* Public Delegation Storage Service environments. To be used in the
* DeleGationStorageService config.
*/
export const DelegationStorageEnvironment: {
[K in 'dev' | 'prod']: Environment;
} = {
dev: { apiUrl: 'https://passkeys.dev-api.cx.metamask.io' },
prod: { apiUrl: 'https://passkeys.api.cx.metamask.io' },
};
export type Environment = {
apiUrl: string;
};
export type DelegationStorageConfig = {
apiKey: string;
apiKeyId: string;
environment: Environment;
fetcher?: typeof fetch;
};
export class DelegationStorageClient {
#apiVersionPrefix = 'api/v0';
#config: DelegationStorageConfig;
#fetcher: typeof fetch;
#apiUrl: string;
constructor(config: DelegationStorageConfig) {
const { apiUrl } = config.environment;
if (apiUrl.endsWith(this.#apiVersionPrefix)) {
this.#apiUrl = apiUrl;
} else {
const separator = apiUrl.endsWith('/') ? '' : '/';
this.#apiUrl = `${apiUrl}${separator}${this.#apiVersionPrefix}`;
}
this.#fetcher = this.#initializeFetcher(config);
this.#config = config;
}
/**
* Initializes the fetch function for HTTP requests.
*
* - Uses `config.fetcher` if provided.
* - Falls back to global `fetch` if available.
* - Throws an error if no fetch function is available.
*
* @param config - Configuration object that may include a custom fetch function.
* @returns The fetch function to be used for HTTP requests.
* @throws Error if no fetch function is available in the environment.
*/
#initializeFetcher(config: DelegationStorageConfig): typeof fetch {
if (config.fetcher) {
return config.fetcher;
} else if (typeof globalThis?.fetch === 'function') {
return globalThis.fetch.bind(globalThis);
}
throw new Error(
'Fetch API is not available in this environment. Please provide a fetch function in the config.',
);
}
/**
* Fetches the delegation chain from the Delegation Storage Service, ending with
* the specified leaf delegation.
*
* @param leafDelegationOrDelegationHash - The leaf delegation, or the hash
* of the leaf delegation.
* @returns A promise that resolves to the delegation chain - empty array if the delegation
* is not found.
*/
async getDelegationChain(
leafDelegationOrDelegationHash: Hex | Delegation,
): Promise<Delegation[]> {
const leafDelegationHash =
typeof leafDelegationOrDelegationHash === 'string'
? leafDelegationOrDelegationHash
: getDelegationHashOffchain(leafDelegationOrDelegationHash);
const response = await this.#fetcher(
`${this.#apiUrl}/delegation/chain/${leafDelegationHash}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${this.#config.apiKey}`,
'x-api-key-id': this.#config.apiKeyId,
},
},
);
const responseData: Delegation[] | ErrorResponse = await response.json();
if ('error' in responseData) {
throw new Error(
`Failed to fetch delegation chain: ${responseData.error}`,
);
}
return responseData;
}
/**
* Fetches the delegations from the Delegation Storage Service, either `Received`
* by, or `Given` by, (or both: `All`) the specified deleGatorAddress. Defaults
* to `Received`.
*
* @param deleGatorAddress - The deleGatorAddress to retrieve the delegations for.
* @param filterMode - The DelegationStoreFilter mode - defaults to Received.
* @returns A promise that resolves to the list of delegations received by the deleGatorAddress,
* empty array if the delegations are not found.
*/
async fetchDelegations(
deleGatorAddress: Hex,
filterMode = DelegationStoreFilter.Received,
): Promise<Delegation[]> {
const response = await this.#fetcher(
`${this.#apiUrl}/delegation/accounts/${deleGatorAddress}?filter=${filterMode}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${this.#config.apiKey}`,
'x-api-key-id': this.#config.apiKeyId,
},
},
);
const responseData: Delegation[] | ErrorResponse = await response.json();
if ('error' in responseData) {
throw new Error(`Failed to fetch delegations: ${responseData.error}`);
}
return responseData;
}
/**
* Stores the specified delegation in the Delegation Storage Service.
*
* @param delegation - The delegation to store.
* @returns A promise that resolves to the delegation hash indicating successful storage.
*/
async storeDelegation(delegation: Delegation): Promise<Hex> {
if (!delegation.signature || delegation.signature === '0x') {
throw new Error('Delegation must be signed to be stored');
}
const delegationHash = getDelegationHashOffchain(delegation);
const body = JSON.stringify(
{
...delegation,
metadata: [],
},
(_, value: any) =>
typeof value === 'bigint' || typeof value === 'number'
? toHex(value)
: value,
2,
);
const response = await this.#fetcher(`${this.#apiUrl}/delegation/store`, {
method: 'POST',
headers: {
Authorization: `Bearer ${this.#config.apiKey}`,
'x-api-key-id': this.#config.apiKeyId,
'Content-Type': 'application/json',
},
body,
});
const responseData: APIStoreDelegationResponse | ErrorResponse =
await response.json();
if ('error' in responseData) {
throw new Error(responseData.error);
}
if (responseData.delegationHash !== delegationHash) {
throw Error(
'Failed to store the Delegation, the hash returned from the MM delegation storage API does not match the hash of the delegation',
);
}
return responseData.delegationHash;
}
}