@metamask/snaps-rpc-methods
Version:
MetaMask Snaps JSON-RPC method implementations
83 lines • 3.03 kB
JavaScript
import { PermissionType, SubjectType } from "@metamask/permission-controller";
import { rpcErrors } from "@metamask/rpc-errors";
import { assertIsRpcOrigins, SnapCaveatType } from "@metamask/snaps-utils";
import { hasProperty, isPlainObject, assert } from "@metamask/utils";
import { createGenericPermissionValidator } from "./caveats/index.mjs";
import { SnapEndowments } from "./enum.mjs";
const targetName = SnapEndowments.Rpc;
/**
* The specification builder for the JSON-RPC endowment permission.
*
* @param _builderOptions - Optional specification builder options.
* @returns The specification for the JSON-RPC endowment permission.
*/
const specificationBuilder = (_builderOptions) => {
return {
permissionType: PermissionType.Endowment,
targetName,
allowedCaveats: [SnapCaveatType.RpcOrigin, SnapCaveatType.MaxRequestTime],
endowmentGetter: (_getterOptions) => null,
validator: createGenericPermissionValidator([
{ type: SnapCaveatType.RpcOrigin },
{ type: SnapCaveatType.MaxRequestTime, optional: true },
]),
subjectTypes: [SubjectType.Snap],
};
};
export const rpcEndowmentBuilder = Object.freeze({
targetName,
specificationBuilder,
});
/**
* Validate the value of a caveat. This does not validate the type of the
* caveat itself, only the value of the caveat.
*
* @param caveat - The caveat to validate.
* @throws If the caveat value is invalid.
*/
function validateCaveatOrigins(caveat) {
if (!hasProperty(caveat, 'value') || !isPlainObject(caveat.value)) {
throw rpcErrors.invalidParams({
message: 'Invalid JSON-RPC origins: Expected a plain object.',
});
}
const { value } = caveat;
assertIsRpcOrigins(value, rpcErrors.invalidParams);
}
/**
* Map a raw value from the `initialPermissions` to a caveat specification.
* Note that this function does not do any validation, that's handled by the
* PermissionsController when the permission is requested.
*
* @param value - The raw value from the `initialPermissions`.
* @returns The caveat specification.
*/
export function getRpcCaveatMapper(value) {
return {
caveats: [
{
type: SnapCaveatType.RpcOrigin,
value,
},
],
};
}
/**
* Getter function to get the {@link RpcOrigins} caveat value from a permission.
*
* @param permission - The permission to get the caveat value from.
* @returns The caveat value.
* @throws If the permission does not have a valid {@link RpcOrigins} caveat.
*/
export function getRpcCaveatOrigins(permission) {
const caveat = permission?.caveats?.find((permCaveat) => permCaveat.type === SnapCaveatType.RpcOrigin);
assert(caveat);
return caveat.value;
}
export const rpcCaveatSpecifications = {
[SnapCaveatType.RpcOrigin]: Object.freeze({
type: SnapCaveatType.RpcOrigin,
validator: (caveat) => validateCaveatOrigins(caveat),
}),
};
//# sourceMappingURL=rpc.mjs.map