-
Notifications
You must be signed in to change notification settings - Fork 652
/
utils.ts
448 lines (404 loc) · 13.1 KB
/
utils.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import {
builder,
getObjectType,
isValidSuiAddress as isValidFullSuiAddress,
JsonRpcProvider,
normalizeSuiAddress,
PaginatedObjectsResponse,
RawSigner,
SuiObjectResponse,
SuiTransactionBlockResponse,
TransactionBlock,
} from "@mysten/sui.js";
import { DynamicFieldPage } from "@mysten/sui.js/dist/types/dynamic_fields";
import { ensureHexPrefix } from "../utils";
import { SuiRpcValidationError } from "./error";
import { SuiError } from "./types";
const MAX_PURE_ARGUMENT_SIZE = 16 * 1024;
const UPGRADE_CAP_TYPE = "0x2::package::UpgradeCap";
export const uint8ArrayToBCS = (arr: Uint8Array) =>
builder.ser("vector<u8>", arr, { maxSize: MAX_PURE_ARGUMENT_SIZE }).toBytes();
export const executeTransactionBlock = async (
signer: RawSigner,
transactionBlock: TransactionBlock
): Promise<SuiTransactionBlockResponse> => {
// Let caller handle parsing and logging info
transactionBlock.setGasBudget(100000000);
return signer.signAndExecuteTransactionBlock({
transactionBlock,
options: {
showInput: true,
showEffects: true,
showEvents: true,
showObjectChanges: true,
},
});
};
// TODO: can we pass in the latest core bridge package Id after an upgrade?
// or do we have to use the first one?
// this is the same type that the guardian will look for
export const getEmitterAddressAndSequenceFromResponseSui = (
originalCoreBridgePackageId: string,
response: SuiTransactionBlockResponse
): { emitterAddress: string; sequence: string } => {
const wormholeMessageEventType = `${originalCoreBridgePackageId}::publish_message::WormholeMessage`;
const event = response.events?.find((e) =>
isSameType(e.type, wormholeMessageEventType)
);
if (event === undefined) {
throw new Error(`${wormholeMessageEventType} event type not found`);
}
const { sender, sequence } = event.parsedJson || {};
if (sender === undefined || sequence === undefined) {
throw new Error("Can't find sender or sequence");
}
return { emitterAddress: sender.substring(2), sequence };
};
export const getFieldsFromObjectResponse = (object: SuiObjectResponse) => {
const content = object.data?.content;
return content && content.dataType === "moveObject" ? content.fields : null;
};
export const getInnerType = (type: string): string | null => {
if (!type) return null;
const match = type.match(/<(.*)>/);
if (!match || !isValidSuiType(match[1])) {
return null;
}
return match[1];
};
export const getObjectFields = async (
provider: JsonRpcProvider,
objectId: string
): Promise<Record<string, any> | null> => {
if (!isValidSuiAddress(objectId)) {
throw new Error(`Invalid object ID: ${objectId}`);
}
const res = await provider.getObject({
id: objectId,
options: {
showContent: true,
},
});
return getFieldsFromObjectResponse(res);
};
export const getOriginalPackageId = async (
provider: JsonRpcProvider,
stateObjectId: string
) => {
return getObjectType(
await provider.getObject({
id: stateObjectId,
options: { showContent: true },
})
)?.split("::")[0];
};
export const getOwnedObjectId = async (
provider: JsonRpcProvider,
owner: string,
type: string
): Promise<string | null> => {
// Upgrade caps are a special case
if (isSameType(type, UPGRADE_CAP_TYPE)) {
throw new Error(
"`getOwnedObjectId` should not be used to get the object ID of an `UpgradeCap`. Use `getUpgradeCapObjectId` instead."
);
}
try {
const res = await provider.getOwnedObjects({
owner,
filter: { StructType: type },
options: {
showContent: true,
},
});
if (!res || !res.data) {
throw new SuiRpcValidationError(res);
}
const objects = res.data.filter((o) => o.data?.objectId);
if (objects.length === 1) {
return objects[0].data?.objectId ?? null;
} else if (objects.length > 1) {
const objectsStr = JSON.stringify(objects, null, 2);
throw new Error(
`Found multiple objects owned by ${owner} of type ${type}. This may mean that we've received an unexpected response from the Sui RPC and \`worm\` logic needs to be updated to handle this. Objects: ${objectsStr}`
);
} else {
return null;
}
} catch (error) {
// Handle 504 error by using findOwnedObjectByType method
const is504HttpError = `${error}`.includes("504 Gateway Time-out");
if (error && is504HttpError) {
return getOwnedObjectIdPaginated(provider, owner, type);
} else {
throw error;
}
}
};
export const getOwnedObjectIdPaginated = async (
provider: JsonRpcProvider,
owner: string,
type: string,
cursor?: string
): Promise<string | null> => {
const res: PaginatedObjectsResponse = await provider.getOwnedObjects({
owner,
filter: undefined, // Filter must be undefined to avoid 504 responses
cursor: cursor || undefined,
options: {
showType: true,
},
});
if (!res || !res.data) {
throw new SuiRpcValidationError(res);
}
const object = res.data.find((d) => isSameType(d.data?.type || "", type));
if (!object && res.hasNextPage) {
return getOwnedObjectIdPaginated(
provider,
owner,
type,
res.nextCursor as string
);
} else if (!object && !res.hasNextPage) {
return null;
} else {
return object?.data?.objectId ?? null;
}
};
/**
* @param provider
* @param objectId Core or token bridge state object ID
* @returns The latest package ID for the provided state object
*/
export async function getPackageId(
provider: JsonRpcProvider,
objectId: string
): Promise<string> {
let currentPackage;
let nextCursor;
do {
const dynamicFields: DynamicFieldPage = await provider.getDynamicFields({
parentId: objectId,
cursor: nextCursor,
});
currentPackage = dynamicFields.data.find((field) =>
field.name.type.endsWith("CurrentPackage")
);
nextCursor = dynamicFields.hasNextPage ? dynamicFields.nextCursor : null;
} while (nextCursor && !currentPackage);
if (!currentPackage) {
throw new Error("CurrentPackage not found");
}
const fields = await getObjectFields(provider, currentPackage.objectId);
const packageId = fields?.value?.fields?.package;
if (!packageId) {
throw new Error("Unable to get current package");
}
return packageId;
}
export const getPackageIdFromType = (type: string): string | null => {
if (!isValidSuiType(type)) return null;
const packageId = type.split("::")[0];
if (!isValidSuiAddress(packageId)) return null;
return packageId;
};
export const getTableKeyType = (tableType: string): string | null => {
if (!tableType) return null;
const match = trimSuiType(tableType).match(/0x2::table::Table<(.*)>/);
if (!match) return null;
const [keyType] = match[1].split(",");
if (!isValidSuiType(keyType)) return null;
return keyType;
};
export const getTokenCoinType = async (
provider: JsonRpcProvider,
tokenBridgeStateObjectId: string,
tokenAddress: Uint8Array,
tokenChain: number
): Promise<string | null> => {
const tokenBridgeStateFields = await getObjectFields(
provider,
tokenBridgeStateObjectId
);
if (!tokenBridgeStateFields) {
throw new Error("Unable to fetch object fields from token bridge state");
}
const coinTypes = tokenBridgeStateFields?.token_registry?.fields?.coin_types;
const coinTypesObjectId = coinTypes?.fields?.id?.id;
if (!coinTypesObjectId) {
throw new Error("Unable to fetch coin types");
}
const keyType = getTableKeyType(coinTypes?.type);
if (!keyType) {
throw new Error("Unable to get key type");
}
const response = await provider.getDynamicFieldObject({
parentId: coinTypesObjectId,
name: {
type: keyType,
value: {
addr: [...tokenAddress],
chain: tokenChain,
},
},
});
if (response.error) {
if (response.error.code === "dynamicFieldNotFound") {
return null;
}
throw new Error(
`Unexpected getDynamicFieldObject response ${response.error}`
);
}
const fields = getFieldsFromObjectResponse(response);
return fields?.value ? trimSuiType(ensureHexPrefix(fields.value)) : null;
};
export const getTokenFromTokenRegistry = async (
provider: JsonRpcProvider,
tokenBridgeStateObjectId: string,
tokenType: string
): Promise<SuiObjectResponse> => {
if (!isValidSuiType(tokenType)) {
throw new Error(`Invalid Sui type: ${tokenType}`);
}
const tokenBridgeStateFields = await getObjectFields(
provider,
tokenBridgeStateObjectId
);
if (!tokenBridgeStateFields) {
throw new Error(
`Unable to fetch object fields from token bridge state. Object ID: ${tokenBridgeStateObjectId}`
);
}
const tokenRegistryObjectId =
tokenBridgeStateFields.token_registry?.fields?.id?.id;
if (!tokenRegistryObjectId) {
throw new Error("Unable to fetch token registry object ID");
}
const tokenRegistryPackageId = getPackageIdFromType(
tokenBridgeStateFields.token_registry?.type
);
if (!tokenRegistryObjectId) {
throw new Error("Unable to fetch token registry package ID");
}
return provider.getDynamicFieldObject({
parentId: tokenRegistryObjectId,
name: {
type: `${tokenRegistryPackageId}::token_registry::Key<${tokenType}>`,
value: {
dummy_field: false,
},
},
});
};
/**
* This function returns the object ID of the `UpgradeCap` that belongs to the
* given package and owner if it exists.
*
* Structs created by the Sui framework such as `UpgradeCap`s all have the same
* type (e.g. `0x2::package::UpgradeCap`) and have a special field, `package`,
* we can use to differentiate them.
* @param provider Sui RPC provider
* @param owner Address of the current owner of the `UpgradeCap`
* @param packageId ID of the package that the `UpgradeCap` was created for
* @returns The object ID of the `UpgradeCap` if it exists, otherwise `null`
*/
export const getUpgradeCapObjectId = async (
provider: JsonRpcProvider,
owner: string,
packageId: string
): Promise<string | null> => {
const res = await provider.getOwnedObjects({
owner,
filter: { StructType: padSuiType(UPGRADE_CAP_TYPE) },
options: {
showContent: true,
},
});
if (!res || !res.data) {
throw new SuiRpcValidationError(res);
}
const objects = res.data.filter(
(o) =>
o.data?.objectId &&
o.data?.content?.dataType === "moveObject" &&
normalizeSuiAddress(o.data?.content?.fields?.package) ===
normalizeSuiAddress(packageId)
);
if (objects.length === 1) {
// We've found the object we're looking for
return objects[0].data?.objectId ?? null;
} else if (objects.length > 1) {
const objectsStr = JSON.stringify(objects, null, 2);
throw new Error(
`Found multiple upgrade capabilities owned by ${owner} from package ${packageId}. Objects: ${objectsStr}`
);
} else {
return null;
}
};
/**
* Get the fully qualified type of a wrapped asset published to the given
* package ID.
*
* All wrapped assets that are registered with the token bridge must satisfy
* the requirement that module name is `coin` (source: https://github.com/wormhole-foundation/wormhole/blob/a1b3773ee42507122c3c4c3494898fbf515d0712/sui/token_bridge/sources/create_wrapped.move#L88).
* As a result, all wrapped assets share the same module name and struct name,
* since the struct name is necessarily `COIN` since it is a OTW.
* @param coinPackageId packageId of the wrapped asset
* @returns Fully qualified type of the wrapped asset
*/
export const getWrappedCoinType = (coinPackageId: string): string => {
if (!isValidSuiAddress(coinPackageId)) {
throw new Error(`Invalid package ID: ${coinPackageId}`);
}
return `${coinPackageId}::coin::COIN`;
};
export const isSameType = (a: string, b: string) => {
try {
return trimSuiType(a) === trimSuiType(b);
} catch (e) {
return false;
}
};
export const isSuiError = (error: any): error is SuiError => {
return (
error && typeof error === "object" && "code" in error && "message" in error
);
};
/**
* This method validates any Sui address, even if it's not 32 bytes long, i.e.
* "0x2". This differs from Mysten's implementation, which requires that the
* given address is 32 bytes long.
* @param address Address to check
* @returns If given address is a valid Sui address or not
*/
export const isValidSuiAddress = (address: string): boolean =>
isValidFullSuiAddress(normalizeSuiAddress(address));
export const isValidSuiType = (type: string): boolean => {
const tokens = type.split("::");
if (tokens.length !== 3) {
return false;
}
return isValidSuiAddress(tokens[0]) && !!tokens[1] && !!tokens[2];
};
/**
* Unlike `trimSuiType`, this method does not modify nested types, it just pads
* the top-level type.
* @param type
* @returns
*/
export const padSuiType = (type: string): string => {
const tokens = type.split("::");
if (tokens.length < 3 || !isValidSuiAddress(tokens[0])) {
throw new Error(`Invalid Sui type: ${type}`);
}
return [normalizeSuiAddress(tokens[0]), ...tokens.slice(1)].join("::");
};
/**
* This method removes leading zeroes for types in order to normalize them
* since some types returned from the RPC have leading zeroes and others don't.
*/
export const trimSuiType = (type: string): string =>
type.replace(/(0x)(0*)/g, "0x");