Socket
Socket
Sign inDemoInstall

@metamask/snaps-utils

Package Overview
Dependencies
Maintainers
12
Versions
71
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@metamask/snaps-utils - npm Package Compare versions

Comparing version 5.2.0 to 6.0.0

21

CHANGELOG.md

@@ -9,2 +9,16 @@ # Changelog

## [6.0.0]
### Added
- Add support for dynamic user interfaces ([#1465](https://github.com/MetaMask/snaps/pull/1465), [#2126](https://github.com/MetaMask/snaps/pull/2126))
- Add support for snap defined execution timeouts ([#2098](https://github.com/MetaMask/snaps/pull/2098))
### Changed
- **BREAKING:** Update name lookup type validation ([#2113](https://github.com/MetaMask/snaps/pull/2113))
- The return value and the permission format has changed, see [SIP-12](https://metamask.github.io/SIPs/SIPS/sip-12) for more details.
- Speed up eval-worker for improved CLI performance ([#2147](https://github.com/MetaMask/snaps/pull/2147))
- Update MetaMask dependencies ([#2132](https://github.com/MetaMask/snaps/pull/2132), [#2142](https://github.com/MetaMask/snaps/pull/2142))
### Fixed
- Fix initial permissions types ([#2111](https://github.com/MetaMask/snaps/pull/2111))
## [5.2.0]

@@ -138,4 +152,4 @@ ### Added

- Update transaction insights response and add severity level enum ([#1653](https://github.com/MetaMask/snaps/pull/1653))
- Snaps are now able to specify a `severity` for alongside their insights.
- See [SIP-11](https://metamask.github.io/SIPs/SIPS/sip-11) for more information.
- Snaps are now able to specify a `severity` for alongside their insights.
- See [SIP-11](https://metamask.github.io/SIPs/SIPS/sip-11) for more information.

@@ -156,3 +170,4 @@ ## [0.38.0-flask.1]

[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.2.0...HEAD
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@6.0.0...HEAD
[6.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.2.0...@metamask/snaps-utils@6.0.0
[5.2.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.1.2...@metamask/snaps-utils@5.2.0

@@ -159,0 +174,0 @@ [5.1.2]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.1.1...@metamask/snaps-utils@5.1.2

@@ -40,4 +40,10 @@ "use strict";

*/ "ChainIds"] = 'chainIds';
SnapCaveatType[/**
* Caveat specifying the input that a name lookup snap can service, currently limited to `endowment:name-lookup`.
*/ "LookupMatchers"] = 'lookupMatchers';
SnapCaveatType[/**
* Caveat specifying the max request time for a handler endowment.
*/ "MaxRequestTime"] = 'maxRequestTime';
})(SnapCaveatType || (SnapCaveatType = {}));
//# sourceMappingURL=caveats.js.map

4

dist/cjs/eval-worker.js

@@ -40,4 +40,6 @@ // eslint-disable-next-line import/no-unassigned-import

}
setTimeout(()=>process.exit(0), 1000); // Hack to ensure worker exits
// To ensure the worker exits we explicitly call exit here
// If we didn't the eval would wait for timers set during Compartment eval
process.exit(0);
//# sourceMappingURL=eval-worker.js.map

@@ -30,2 +30,3 @@ "use strict";

HandlerType["OnHomePage"] = 'onHomePage';
HandlerType["OnUserInput"] = 'onUserInput';
})(HandlerType || (HandlerType = {}));

@@ -32,0 +33,0 @@ const SNAP_EXPORT_NAMES = Object.values(HandlerType);

@@ -15,2 +15,11 @@ "use strict";

},
OnTransactionSeverityResponseStruct: function() {
return OnTransactionSeverityResponseStruct;
},
OnTransactionResponseWithIdStruct: function() {
return OnTransactionResponseWithIdStruct;
},
OnTransactionResponseWithContentStruct: function() {
return OnTransactionResponseWithContentStruct;
},
OnTransactionResponseStruct: function() {

@@ -22,4 +31,25 @@ return OnTransactionResponseStruct;

},
OnHomePageResponseWithContentStruct: function() {
return OnHomePageResponseWithContentStruct;
},
OnHomePageResponseWithIdStruct: function() {
return OnHomePageResponseWithIdStruct;
},
OnHomePageResponseStruct: function() {
return OnHomePageResponseStruct;
},
AddressResolutionStruct: function() {
return AddressResolutionStruct;
},
DomainResolutionStruct: function() {
return DomainResolutionStruct;
},
AddressResolutionResponseStruct: function() {
return AddressResolutionResponseStruct;
},
DomainResolutionResponseStruct: function() {
return DomainResolutionResponseStruct;
},
OnNameLookupResponseStruct: function() {
return OnNameLookupResponseStruct;
}

@@ -93,13 +123,54 @@ });

}
},
[_handlertypes.HandlerType.OnUserInput]: {
type: _handlertypes.HandlerType.OnUserInput,
required: true,
validator: (snapExport)=>{
return typeof snapExport === 'function';
}
}
};
const OnTransactionResponseStruct = (0, _superstruct.nullable)((0, _superstruct.object)({
content: _snapssdk.ComponentStruct,
const OnTransactionSeverityResponseStruct = (0, _superstruct.object)({
severity: (0, _superstruct.optional)((0, _superstruct.literal)(_snapssdk.SeverityLevel.Critical))
});
const OnTransactionResponseWithIdStruct = (0, _superstruct.assign)(OnTransactionSeverityResponseStruct, (0, _superstruct.object)({
id: (0, _superstruct.string)()
}));
const OnTransactionResponseWithContentStruct = (0, _superstruct.assign)(OnTransactionSeverityResponseStruct, (0, _superstruct.object)({
content: _snapssdk.ComponentStruct
}));
const OnTransactionResponseStruct = (0, _superstruct.nullable)((0, _superstruct.union)([
OnTransactionResponseWithContentStruct,
OnTransactionResponseWithIdStruct
]));
const OnSignatureResponseStruct = OnTransactionResponseStruct;
const OnHomePageResponseStruct = (0, _superstruct.object)({
const OnHomePageResponseWithContentStruct = (0, _superstruct.object)({
content: _snapssdk.ComponentStruct
});
const OnHomePageResponseWithIdStruct = (0, _superstruct.object)({
id: (0, _superstruct.string)()
});
const OnHomePageResponseStruct = (0, _superstruct.union)([
OnHomePageResponseWithContentStruct,
OnHomePageResponseWithIdStruct
]);
const AddressResolutionStruct = (0, _superstruct.object)({
protocol: (0, _superstruct.string)(),
resolvedDomain: (0, _superstruct.string)()
});
const DomainResolutionStruct = (0, _superstruct.object)({
protocol: (0, _superstruct.string)(),
resolvedAddress: (0, _superstruct.string)()
});
const AddressResolutionResponseStruct = (0, _superstruct.object)({
resolvedDomains: (0, _superstruct.size)((0, _superstruct.array)(AddressResolutionStruct), 1, Infinity)
});
const DomainResolutionResponseStruct = (0, _superstruct.object)({
resolvedAddresses: (0, _superstruct.size)((0, _superstruct.array)(DomainResolutionStruct), 1, Infinity)
});
const OnNameLookupResponseStruct = (0, _superstruct.nullable)((0, _superstruct.union)([
AddressResolutionResponseStruct,
DomainResolutionResponseStruct
]));
//# sourceMappingURL=handlers.js.map

@@ -36,2 +36,17 @@ "use strict";

},
LookupMatchersStruct: function() {
return LookupMatchersStruct;
},
MINIMUM_REQUEST_TIMEOUT: function() {
return MINIMUM_REQUEST_TIMEOUT;
},
MAXIMUM_REQUEST_TIMEOUT: function() {
return MAXIMUM_REQUEST_TIMEOUT;
},
MaxRequestTimeStruct: function() {
return MaxRequestTimeStruct;
},
HandlerCaveatsStruct: function() {
return HandlerCaveatsStruct;
},
PermissionsStruct: function() {

@@ -132,22 +147,43 @@ return PermissionsStruct;

});
const ChainIdsStruct = (0, _superstruct.array)(_namespace.ChainIdStruct);
const ChainIdsStruct = (0, _superstruct.size)((0, _superstruct.array)(_namespace.ChainIdStruct), 1, Infinity);
const LookupMatchersStruct = (0, _superstruct.union)([
(0, _superstruct.object)({
tlds: (0, _superstruct.size)((0, _superstruct.array)((0, _superstruct.string)()), 1, Infinity)
}),
(0, _superstruct.object)({
schemes: (0, _superstruct.size)((0, _superstruct.array)((0, _superstruct.string)()), 1, Infinity)
}),
(0, _superstruct.object)({
tlds: (0, _superstruct.size)((0, _superstruct.array)((0, _superstruct.string)()), 1, Infinity),
schemes: (0, _superstruct.size)((0, _superstruct.array)((0, _superstruct.string)()), 1, Infinity)
})
]);
const MINIMUM_REQUEST_TIMEOUT = (0, _utils.inMilliseconds)(5, _utils.Duration.Second);
const MAXIMUM_REQUEST_TIMEOUT = (0, _utils.inMilliseconds)(3, _utils.Duration.Minute);
const MaxRequestTimeStruct = (0, _superstruct.size)((0, _superstruct.integer)(), MINIMUM_REQUEST_TIMEOUT, MAXIMUM_REQUEST_TIMEOUT);
const HandlerCaveatsStruct = (0, _superstruct.object)({
maxRequestTime: (0, _superstruct.optional)(MaxRequestTimeStruct)
});
const PermissionsStruct = (0, _superstruct.type)({
'endowment:cronjob': (0, _superstruct.optional)((0, _superstruct.assign)(HandlerCaveatsStruct, (0, _superstruct.object)({
jobs: _cronjob.CronjobSpecificationArrayStruct
}))),
'endowment:ethereum-provider': (0, _superstruct.optional)((0, _superstruct.object)({})),
'endowment:keyring': (0, _superstruct.optional)((0, _superstruct.assign)(HandlerCaveatsStruct, _jsonrpc.KeyringOriginsStruct)),
'endowment:lifecycle-hooks': (0, _superstruct.optional)(HandlerCaveatsStruct),
'endowment:name-lookup': (0, _superstruct.optional)((0, _superstruct.assign)(HandlerCaveatsStruct, (0, _superstruct.object)({
chains: (0, _superstruct.optional)(ChainIdsStruct),
matchers: (0, _superstruct.optional)(LookupMatchersStruct)
}))),
'endowment:network-access': (0, _superstruct.optional)((0, _superstruct.object)({})),
'endowment:webassembly': (0, _superstruct.optional)((0, _superstruct.object)({})),
'endowment:signature-insight': (0, _superstruct.optional)((0, _superstruct.object)({
'endowment:page-home': (0, _superstruct.optional)(HandlerCaveatsStruct),
'endowment:rpc': (0, _superstruct.optional)(_jsonrpc.RpcOriginsStruct),
'endowment:signature-insight': (0, _superstruct.optional)((0, _superstruct.assign)(HandlerCaveatsStruct, (0, _superstruct.object)({
allowSignatureOrigin: (0, _superstruct.optional)((0, _superstruct.boolean)())
})),
'endowment:transaction-insight': (0, _superstruct.optional)((0, _superstruct.object)({
}))),
'endowment:transaction-insight': (0, _superstruct.optional)((0, _superstruct.assign)(HandlerCaveatsStruct, (0, _superstruct.object)({
allowTransactionOrigin: (0, _superstruct.optional)((0, _superstruct.boolean)())
})),
'endowment:cronjob': (0, _superstruct.optional)((0, _superstruct.object)({
jobs: _cronjob.CronjobSpecificationArrayStruct
})),
'endowment:rpc': (0, _superstruct.optional)(_jsonrpc.RpcOriginsStruct),
'endowment:name-lookup': (0, _superstruct.optional)(ChainIdsStruct),
'endowment:keyring': (0, _superstruct.optional)(_jsonrpc.KeyringOriginsStruct),
}))),
'endowment:webassembly': (0, _superstruct.optional)((0, _superstruct.object)({})),
snap_dialog: (0, _superstruct.optional)((0, _superstruct.object)({})),
// TODO: Remove
snap_confirm: (0, _superstruct.optional)((0, _superstruct.object)({})),
snap_manageState: (0, _superstruct.optional)((0, _superstruct.object)({})),

@@ -154,0 +190,0 @@ snap_manageAccounts: (0, _superstruct.optional)((0, _superstruct.object)({})),

@@ -44,4 +44,11 @@ "use strict";

return getStructErrorMessage;
},
validateUnion: function() {
return validateUnion;
},
createUnion: function() {
return createUnion;
}
});
const _snapssdk = require("@metamask/snaps-sdk");
const _utils = require("@metamask/utils");

@@ -52,2 +59,18 @@ const _chalk = require("chalk");

const _strings = require("./strings");
/**
* Colorize a value with a color function. This is useful for colorizing values
* in error messages. If colorization is disabled, the original value is
* returned.
*
* @param value - The value to colorize.
* @param colorFunction - The color function to use.
* @param enabled - Whether to colorize the value.
* @returns The colorized value, or the original value if colorization is
* disabled.
*/ function color(value, colorFunction, enabled) {
if (enabled) {
return colorFunction(value);
}
return value;
}
function file() {

@@ -65,3 +88,3 @@ return (0, _superstruct.coerce)((0, _superstruct.string)(), (0, _superstruct.string)(), (value)=>{

class SnapsStructError extends _superstruct.StructError {
constructor(struct, prefix, suffix, failure, failures){
constructor(struct, prefix, suffix, failure, failures, colorize = true){
super(failure, failures);

@@ -71,3 +94,3 @@ this.name = 'SnapsStructError';

...failures()
])}${suffix ? `\n\n${suffix}` : ''}`;
], colorize)}${suffix ? `\n\n${suffix}` : ''}`;
}

@@ -80,4 +103,4 @@ }

}
function getError({ struct, prefix, suffix = '', error }) {
return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()));
function getError({ struct, prefix, suffix = '', error, colorize }) {
return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()), colorize);
}

@@ -107,20 +130,20 @@ function createFromStruct(value, struct, prefix, suffix = '') {

}
function getUnionStructNames(struct) {
function getUnionStructNames(struct, colorize = true) {
if (Array.isArray(struct.schema)) {
return struct.schema.map(({ type })=>(0, _chalk.green)(type));
return struct.schema.map(({ type })=>color(type, _chalk.green, colorize));
}
return null;
}
function getStructErrorPrefix(failure) {
function getStructErrorPrefix(failure, colorize = true) {
if (failure.type === 'never' || failure.path.length === 0) {
return '';
}
return `At path: ${(0, _chalk.bold)(failure.path.join('.'))} — `;
return `At path: ${color(failure.path.join('.'), _chalk.bold, colorize)} — `;
}
function getStructFailureMessage(struct, failure) {
const received = (0, _chalk.red)(JSON.stringify(failure.value));
const prefix = getStructErrorPrefix(failure);
function getStructFailureMessage(struct, failure, colorize = true) {
const received = color(JSON.stringify(failure.value), _chalk.red, colorize);
const prefix = getStructErrorPrefix(failure, colorize);
if (failure.type === 'union') {
const childStruct = getStructFromPath(struct, failure.path);
const unionNames = getUnionStructNames(childStruct);
const unionNames = getUnionStructNames(childStruct, colorize);
if (unionNames) {

@@ -134,15 +157,61 @@ return `${prefix}Expected the value to be one of: ${unionNames.join(', ')}, but received: ${received}.`;

// value was expected, so we need to parse the message to get the literal.
const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${(0, _chalk.green)('$1')}\`,`).replace(/, but received: (.+)/u, `, but received: ${(0, _chalk.red)('$1')}`);
const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${color('$1', _chalk.green, colorize)}\`,`).replace(/, but received: (.+)/u, `, but received: ${color('$1', _chalk.red, colorize)}`);
return `${prefix}${message}.`;
}
if (failure.type === 'never') {
return `Unknown key: ${(0, _chalk.bold)(failure.path.join('.'))}, received: ${received}.`;
return `Unknown key: ${color(failure.path.join('.'), _chalk.bold, colorize)}, received: ${received}.`;
}
return `${prefix}Expected a value of type ${(0, _chalk.green)(failure.type)}, but received: ${received}.`;
if (failure.refinement === 'size') {
const message = failure.message.replace(/length between `(\d+)` and `(\d+)`/u, `length between ${color('$1', _chalk.green, colorize)} and ${color('$2', _chalk.green, colorize)},`).replace(/length of `(\d+)`/u, `length of ${color('$1', _chalk.red, colorize)}`).replace(/a array/u, 'an array');
return `${prefix}${message}.`;
}
return `${prefix}Expected a value of type ${color(failure.type, _chalk.green, colorize)}, but received: ${received}.`;
}
function getStructErrorMessage(struct, failures) {
const formattedFailures = failures.map((failure)=>(0, _strings.indent)(`• ${getStructFailureMessage(struct, failure)}`));
function getStructErrorMessage(struct, failures, colorize = true) {
const formattedFailures = failures.map((failure)=>(0, _strings.indent)(`• ${getStructFailureMessage(struct, failure, colorize)}`));
return formattedFailures.join('\n');
}
function validateUnion(value, struct, structKey, coerce = false) {
(0, _utils.assert)(struct.schema, 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.');
(0, _utils.assert)(struct.schema.length > 0, 'Expected a non-empty array of structs.');
const keyUnion = struct.schema.map((innerStruct)=>innerStruct.schema[structKey]);
const key = (0, _superstruct.type)({
[structKey]: (0, _snapssdk.union)(keyUnion)
});
const [keyError] = (0, _superstruct.validate)(value, key, {
coerce
});
if (keyError) {
throw new Error(getStructFailureMessage(key, keyError.failures()[0], false));
}
// At this point it's guaranteed that the value is an object, so we can safely
// cast it to a Record.
const objectValue = value;
const objectStructs = struct.schema.filter((innerStruct)=>(0, _superstruct.is)(objectValue[structKey], innerStruct.schema[structKey]));
(0, _utils.assert)(objectStructs.length > 0, 'Expected a struct to match the value.');
// We need to validate the value against all the object structs that match the
// struct key, and return the first validated value.
const validationResults = objectStructs.map((objectStruct)=>(0, _superstruct.validate)(objectValue, objectStruct, {
coerce
}));
const validatedValue = validationResults.find(([error])=>!error);
if (validatedValue) {
return validatedValue[1];
}
(0, _utils.assert)(validationResults[0][0], 'Expected at least one error.');
// If there is no validated value, we need to find the error with the least
// number of failures (with the assumption that it's the most specific error).
const validationError = validationResults.reduce((error, [innerError])=>{
(0, _utils.assert)(innerError, 'Expected an error.');
if (innerError.failures().length < error.failures().length) {
return innerError;
}
return error;
}, validationResults[0][0]);
throw new Error(getStructFailureMessage(struct, validationError.failures()[0], false));
}
function createUnion(value, struct, structKey) {
return validateUnion(value, struct, structKey, true);
}
//# sourceMappingURL=structs.js.map

@@ -30,4 +30,10 @@ export var SnapCaveatType;

*/ "ChainIds"] = 'chainIds';
SnapCaveatType[/**
* Caveat specifying the input that a name lookup snap can service, currently limited to `endowment:name-lookup`.
*/ "LookupMatchers"] = 'lookupMatchers';
SnapCaveatType[/**
* Caveat specifying the max request time for a handler endowment.
*/ "MaxRequestTime"] = 'maxRequestTime';
})(SnapCaveatType || (SnapCaveatType = {}));
//# sourceMappingURL=caveats.js.map

@@ -36,4 +36,6 @@ // eslint-disable-next-line import/no-unassigned-import

}
setTimeout(()=>process.exit(0), 1000); // Hack to ensure worker exits
// To ensure the worker exits we explicitly call exit here
// If we didn't the eval would wait for timers set during Compartment eval
process.exit(0);
//# sourceMappingURL=eval-worker.js.map

@@ -12,2 +12,3 @@ export var HandlerType;

HandlerType["OnHomePage"] = 'onHomePage';
HandlerType["OnUserInput"] = 'onUserInput';
})(HandlerType || (HandlerType = {}));

@@ -14,0 +15,0 @@ export const SNAP_EXPORT_NAMES = Object.values(HandlerType);

import { SeverityLevel, ComponentStruct } from '@metamask/snaps-sdk';
import { literal, nullable, object, optional } from 'superstruct';
import { assign, literal, nullable, object, optional, string, array, size, union } from 'superstruct';
import { HandlerType } from './handler-types';

@@ -67,13 +67,54 @@ export const SNAP_EXPORTS = {

}
},
[HandlerType.OnUserInput]: {
type: HandlerType.OnUserInput,
required: true,
validator: (snapExport)=>{
return typeof snapExport === 'function';
}
}
};
export const OnTransactionResponseStruct = nullable(object({
content: ComponentStruct,
export const OnTransactionSeverityResponseStruct = object({
severity: optional(literal(SeverityLevel.Critical))
});
export const OnTransactionResponseWithIdStruct = assign(OnTransactionSeverityResponseStruct, object({
id: string()
}));
export const OnTransactionResponseWithContentStruct = assign(OnTransactionSeverityResponseStruct, object({
content: ComponentStruct
}));
export const OnTransactionResponseStruct = nullable(union([
OnTransactionResponseWithContentStruct,
OnTransactionResponseWithIdStruct
]));
export const OnSignatureResponseStruct = OnTransactionResponseStruct;
export const OnHomePageResponseStruct = object({
export const OnHomePageResponseWithContentStruct = object({
content: ComponentStruct
});
export const OnHomePageResponseWithIdStruct = object({
id: string()
});
export const OnHomePageResponseStruct = union([
OnHomePageResponseWithContentStruct,
OnHomePageResponseWithIdStruct
]);
export const AddressResolutionStruct = object({
protocol: string(),
resolvedDomain: string()
});
export const DomainResolutionStruct = object({
protocol: string(),
resolvedAddress: string()
});
export const AddressResolutionResponseStruct = object({
resolvedDomains: size(array(AddressResolutionStruct), 1, Infinity)
});
export const DomainResolutionResponseStruct = object({
resolvedAddresses: size(array(DomainResolutionStruct), 1, Infinity)
});
export const OnNameLookupResponseStruct = nullable(union([
AddressResolutionResponseStruct,
DomainResolutionResponseStruct
]));
//# sourceMappingURL=handlers.js.map
import { isValidBIP32PathSegment } from '@metamask/key-tree';
import { assertStruct, ChecksumStruct, VersionStruct, isValidSemVerRange } from '@metamask/utils';
import { array, boolean, create, enums, integer, is, literal, object, optional, refine, record, size, string, type, union, intersection } from 'superstruct';
import { assertStruct, ChecksumStruct, VersionStruct, isValidSemVerRange, inMilliseconds, Duration } from '@metamask/utils';
import { array, boolean, create, enums, integer, is, literal, object, optional, refine, record, size, string, type, union, intersection, assign } from 'superstruct';
import { isEqual } from '../array';

@@ -75,22 +75,44 @@ import { CronjobSpecificationArrayStruct } from '../cronjob';

});
export const ChainIdsStruct = array(ChainIdStruct);
export const ChainIdsStruct = size(array(ChainIdStruct), 1, Infinity);
export const LookupMatchersStruct = union([
object({
tlds: size(array(string()), 1, Infinity)
}),
object({
schemes: size(array(string()), 1, Infinity)
}),
object({
tlds: size(array(string()), 1, Infinity),
schemes: size(array(string()), 1, Infinity)
})
]);
export const MINIMUM_REQUEST_TIMEOUT = inMilliseconds(5, Duration.Second);
export const MAXIMUM_REQUEST_TIMEOUT = inMilliseconds(3, Duration.Minute);
export const MaxRequestTimeStruct = size(integer(), MINIMUM_REQUEST_TIMEOUT, MAXIMUM_REQUEST_TIMEOUT);
// Utility type to union with for all handler structs
export const HandlerCaveatsStruct = object({
maxRequestTime: optional(MaxRequestTimeStruct)
});
/* eslint-disable @typescript-eslint/naming-convention */ export const PermissionsStruct = type({
'endowment:cronjob': optional(assign(HandlerCaveatsStruct, object({
jobs: CronjobSpecificationArrayStruct
}))),
'endowment:ethereum-provider': optional(object({})),
'endowment:keyring': optional(assign(HandlerCaveatsStruct, KeyringOriginsStruct)),
'endowment:lifecycle-hooks': optional(HandlerCaveatsStruct),
'endowment:name-lookup': optional(assign(HandlerCaveatsStruct, object({
chains: optional(ChainIdsStruct),
matchers: optional(LookupMatchersStruct)
}))),
'endowment:network-access': optional(object({})),
'endowment:webassembly': optional(object({})),
'endowment:signature-insight': optional(object({
'endowment:page-home': optional(HandlerCaveatsStruct),
'endowment:rpc': optional(RpcOriginsStruct),
'endowment:signature-insight': optional(assign(HandlerCaveatsStruct, object({
allowSignatureOrigin: optional(boolean())
})),
'endowment:transaction-insight': optional(object({
}))),
'endowment:transaction-insight': optional(assign(HandlerCaveatsStruct, object({
allowTransactionOrigin: optional(boolean())
})),
'endowment:cronjob': optional(object({
jobs: CronjobSpecificationArrayStruct
})),
'endowment:rpc': optional(RpcOriginsStruct),
'endowment:name-lookup': optional(ChainIdsStruct),
'endowment:keyring': optional(KeyringOriginsStruct),
}))),
'endowment:webassembly': optional(object({})),
snap_dialog: optional(object({})),
// TODO: Remove
snap_confirm: optional(object({})),
snap_manageState: optional(object({})),

@@ -97,0 +119,0 @@ snap_manageAccounts: optional(object({})),

@@ -1,7 +0,24 @@

import { isObject } from '@metamask/utils';
import { union } from '@metamask/snaps-sdk';
import { assert, isObject } from '@metamask/utils';
import { bold, green, red } from 'chalk';
import { resolve } from 'path';
import { Struct, StructError, create, string, coerce } from 'superstruct';
import { is, validate, type as superstructType, Struct, StructError, create, string, coerce as superstructCoerce } from 'superstruct';
import { indent } from './strings';
/**
* Colorize a value with a color function. This is useful for colorizing values
* in error messages. If colorization is disabled, the original value is
* returned.
*
* @param value - The value to colorize.
* @param colorFunction - The color function to use.
* @param enabled - Whether to colorize the value.
* @returns The colorized value, or the original value if colorization is
* disabled.
*/ function color(value, colorFunction, enabled) {
if (enabled) {
return colorFunction(value);
}
return value;
}
/**
* A wrapper of `superstruct`'s `string` struct that coerces a value to a string

@@ -25,3 +42,3 @@ * and resolves it relative to the current working directory. This is useful

*/ export function file() {
return coerce(string(), string(), (value)=>{
return superstructCoerce(string(), string(), (value)=>{
return resolve(process.cwd(), value);

@@ -45,3 +62,3 @@ });

export class SnapsStructError extends StructError {
constructor(struct, prefix, suffix, failure, failures){
constructor(struct, prefix, suffix, failure, failures, colorize = true){
super(failure, failures);

@@ -51,3 +68,3 @@ this.name = 'SnapsStructError';

...failures()
])}${suffix ? `\n\n${suffix}` : ''}`;
], colorize)}${suffix ? `\n\n${suffix}` : ''}`;
}

@@ -76,5 +93,6 @@ }

* @param options.error - The `superstruct` error to wrap.
* @param options.colorize - Whether to colorize the value. Defaults to `true`.
* @returns The `SnapsStructError`.
*/ export function getError({ struct, prefix, suffix = '', error }) {
return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()));
*/ export function getError({ struct, prefix, suffix = '', error, colorize }) {
return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()), colorize);
}

@@ -125,7 +143,8 @@ /**

* @param struct - The struct.
* @param colorize - Whether to colorize the value. Defaults to `true`.
* @returns The union struct names, or `null` if the struct is not a union
* struct.
*/ export function getUnionStructNames(struct) {
*/ export function getUnionStructNames(struct, colorize = true) {
if (Array.isArray(struct.schema)) {
return struct.schema.map(({ type })=>green(type));
return struct.schema.map(({ type })=>color(type, green, colorize));
}

@@ -135,12 +154,13 @@ return null;

/**
* Get a error prefix from a `superstruct` failure. This is useful for
* Get an error prefix from a `superstruct` failure. This is useful for
* formatting the error message returned by `superstruct`.
*
* @param failure - The `superstruct` failure.
* @param colorize - Whether to colorize the value. Defaults to `true`.
* @returns The error prefix.
*/ export function getStructErrorPrefix(failure) {
*/ export function getStructErrorPrefix(failure, colorize = true) {
if (failure.type === 'never' || failure.path.length === 0) {
return '';
}
return `At path: ${bold(failure.path.join('.'))} — `;
return `At path: ${color(failure.path.join('.'), bold, colorize)} — `;
}

@@ -154,9 +174,10 @@ /**

* @param failure - The `superstruct` failure.
* @param colorize - Whether to colorize the value. Defaults to `true`.
* @returns A string describing the failure.
*/ export function getStructFailureMessage(struct, failure) {
const received = red(JSON.stringify(failure.value));
const prefix = getStructErrorPrefix(failure);
*/ export function getStructFailureMessage(struct, failure, colorize = true) {
const received = color(JSON.stringify(failure.value), red, colorize);
const prefix = getStructErrorPrefix(failure, colorize);
if (failure.type === 'union') {
const childStruct = getStructFromPath(struct, failure.path);
const unionNames = getUnionStructNames(childStruct);
const unionNames = getUnionStructNames(childStruct, colorize);
if (unionNames) {

@@ -170,9 +191,13 @@ return `${prefix}Expected the value to be one of: ${unionNames.join(', ')}, but received: ${received}.`;

// value was expected, so we need to parse the message to get the literal.
const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${green('$1')}\`,`).replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);
const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${color('$1', green, colorize)}\`,`).replace(/, but received: (.+)/u, `, but received: ${color('$1', red, colorize)}`);
return `${prefix}${message}.`;
}
if (failure.type === 'never') {
return `Unknown key: ${bold(failure.path.join('.'))}, received: ${received}.`;
return `Unknown key: ${color(failure.path.join('.'), bold, colorize)}, received: ${received}.`;
}
return `${prefix}Expected a value of type ${green(failure.type)}, but received: ${received}.`;
if (failure.refinement === 'size') {
const message = failure.message.replace(/length between `(\d+)` and `(\d+)`/u, `length between ${color('$1', green, colorize)} and ${color('$2', green, colorize)},`).replace(/length of `(\d+)`/u, `length of ${color('$1', red, colorize)}`).replace(/a array/u, 'an array');
return `${prefix}${message}.`;
}
return `${prefix}Expected a value of type ${color(failure.type, green, colorize)}, but received: ${received}.`;
}

@@ -185,8 +210,95 @@ /**

* @param failures - The `superstruct` failures.
* @param colorize - Whether to colorize the value. Defaults to `true`.
* @returns A string describing the errors.
*/ export function getStructErrorMessage(struct, failures) {
const formattedFailures = failures.map((failure)=>indent(`• ${getStructFailureMessage(struct, failure)}`));
*/ export function getStructErrorMessage(struct, failures, colorize = true) {
const formattedFailures = failures.map((failure)=>indent(`• ${getStructFailureMessage(struct, failure, colorize)}`));
return formattedFailures.join('\n');
}
/**
* Validate a union struct, and throw readable errors if the value does not
* satisfy the struct. This is useful for improving the error messages returned
* by `superstruct`.
*
* @param value - The value to validate.
* @param struct - The `superstruct` union struct to validate the value against.
* This struct must be a union of object structs, and must have at least one
* shared key to validate against.
* @param structKey - The key to validate against. This key must be present in
* all the object structs in the union struct, and is expected to be a literal
* value.
* @param coerce - Whether to coerce the value to satisfy the struct. Defaults
* to `false`.
* @returns The validated value.
* @throws If the value does not satisfy the struct.
* @example
* const struct = union([
* object({ type: literal('a'), value: string() }),
* object({ type: literal('b'), value: number() }),
* object({ type: literal('c'), value: boolean() }),
* // ...
* ]);
*
* // At path: type — Expected the value to be one of: "a", "b", "c", but received: "d".
* validateUnion({ type: 'd', value: 'foo' }, struct, 'type');
*
* // At path: value — Expected a value of type string, but received: 42.
* validateUnion({ type: 'a', value: 42 }, struct, 'value');
*/ export function validateUnion(value, struct, structKey, coerce = false) {
assert(struct.schema, 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.');
assert(struct.schema.length > 0, 'Expected a non-empty array of structs.');
const keyUnion = struct.schema.map((innerStruct)=>innerStruct.schema[structKey]);
const key = superstructType({
[structKey]: union(keyUnion)
});
const [keyError] = validate(value, key, {
coerce
});
if (keyError) {
throw new Error(getStructFailureMessage(key, keyError.failures()[0], false));
}
// At this point it's guaranteed that the value is an object, so we can safely
// cast it to a Record.
const objectValue = value;
const objectStructs = struct.schema.filter((innerStruct)=>is(objectValue[structKey], innerStruct.schema[structKey]));
assert(objectStructs.length > 0, 'Expected a struct to match the value.');
// We need to validate the value against all the object structs that match the
// struct key, and return the first validated value.
const validationResults = objectStructs.map((objectStruct)=>validate(objectValue, objectStruct, {
coerce
}));
const validatedValue = validationResults.find(([error])=>!error);
if (validatedValue) {
return validatedValue[1];
}
assert(validationResults[0][0], 'Expected at least one error.');
// If there is no validated value, we need to find the error with the least
// number of failures (with the assumption that it's the most specific error).
const validationError = validationResults.reduce((error, [innerError])=>{
assert(innerError, 'Expected an error.');
if (innerError.failures().length < error.failures().length) {
return innerError;
}
return error;
}, validationResults[0][0]);
throw new Error(getStructFailureMessage(struct, validationError.failures()[0], false));
}
/**
* Create a value with the coercion logic of a union struct, and throw readable
* errors if the value does not satisfy the struct. This is useful for improving
* the error messages returned by `superstruct`.
*
* @param value - The value to validate.
* @param struct - The `superstruct` union struct to validate the value against.
* This struct must be a union of object structs, and must have at least one
* shared key to validate against.
* @param structKey - The key to validate against. This key must be present in
* all the object structs in the union struct, and is expected to be a literal
* value.
* @returns The validated value.
* @throws If the value does not satisfy the struct.
* @see validateUnion
*/ export function createUnion(value, struct, structKey) {
return validateUnion(value, struct, structKey, true);
}
//# sourceMappingURL=structs.js.map

@@ -37,3 +37,11 @@ export declare enum SnapCaveatType {

*/
ChainIds = "chainIds"
ChainIds = "chainIds",
/**
* Caveat specifying the input that a name lookup snap can service, currently limited to `endowment:name-lookup`.
*/
LookupMatchers = "lookupMatchers",
/**
* Caveat specifying the max request time for a handler endowment.
*/
MaxRequestTime = "maxRequestTime"
}

@@ -10,3 +10,4 @@ export declare enum HandlerType {

OnKeyringRequest = "onKeyringRequest",
OnHomePage = "onHomePage"
OnHomePage = "onHomePage",
OnUserInput = "onUserInput"
}

@@ -13,0 +14,0 @@ export declare type SnapHandler = {

@@ -1,2 +0,2 @@

import type { OnCronjobHandler, OnHomePageHandler, OnKeyringRequestHandler, OnNameLookupHandler, OnRpcRequestHandler, OnSignatureHandler, OnTransactionHandler } from '@metamask/snaps-sdk';
import type { OnCronjobHandler, OnHomePageHandler, OnKeyringRequestHandler, OnNameLookupHandler, OnRpcRequestHandler, OnSignatureHandler, OnTransactionHandler, OnUserInputHandler } from '@metamask/snaps-sdk';
import { SeverityLevel } from '@metamask/snaps-sdk';

@@ -56,4 +56,21 @@ import type { SnapHandler } from './handler-types';

};
readonly onUserInput: {
readonly type: HandlerType.OnUserInput;
readonly required: true;
readonly validator: (snapExport: unknown) => snapExport is OnUserInputHandler;
};
};
export declare const OnTransactionResponseStruct: import("superstruct").Struct<{
export declare const OnTransactionSeverityResponseStruct: import("superstruct").Struct<{
severity?: SeverityLevel | undefined;
}, {
severity: import("superstruct").Struct<SeverityLevel | undefined, SeverityLevel>;
}>;
export declare const OnTransactionResponseWithIdStruct: import("superstruct").Struct<{
id: string;
severity?: SeverityLevel | undefined;
}, {
id: import("superstruct").Struct<string, null>;
severity: import("superstruct").Struct<SeverityLevel | undefined, SeverityLevel>;
}>;
export declare const OnTransactionResponseWithContentStruct: import("superstruct").Struct<{
content: import("@metamask/snaps-sdk").Panel | {

@@ -95,5 +112,35 @@ value: string;

variant?: "default" | "warning" | "critical" | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Form;
name: string;
children: ({
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
})[];
};
severity?: SeverityLevel | undefined;
} | null, {
}, {
content: import("superstruct").Struct<import("@metamask/snaps-sdk").Panel | {

@@ -135,6 +182,39 @@ value: string;

variant?: "default" | "warning" | "critical" | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Form;
name: string;
children: ({
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
})[];
}, null>;
severity: import("superstruct").Struct<SeverityLevel | undefined, SeverityLevel>;
}>;
export declare const OnSignatureResponseStruct: import("superstruct").Struct<{
export declare const OnTransactionResponseStruct: import("superstruct").Struct<{
id: string;
severity?: SeverityLevel | undefined;
} | {
content: import("@metamask/snaps-sdk").Panel | {

@@ -176,6 +256,40 @@ value: string;

variant?: "default" | "warning" | "critical" | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Form;
name: string;
children: ({
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
})[];
};
severity?: SeverityLevel | undefined;
} | null, {
content: import("superstruct").Struct<import("@metamask/snaps-sdk").Panel | {
} | null, null>;
export declare const OnSignatureResponseStruct: import("superstruct").Struct<{
id: string;
severity?: SeverityLevel | undefined;
} | {
content: import("@metamask/snaps-sdk").Panel | {
value: string;

@@ -216,6 +330,36 @@ type: import("@metamask/snaps-sdk").NodeType.Copyable;

variant?: "default" | "warning" | "critical" | undefined;
}, null>;
severity: import("superstruct").Struct<SeverityLevel | undefined, SeverityLevel>;
}>;
export declare const OnHomePageResponseStruct: import("superstruct").Struct<{
} | {
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Form;
name: string;
children: ({
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
})[];
};
severity?: SeverityLevel | undefined;
} | null, null>;
export declare const OnHomePageResponseWithContentStruct: import("superstruct").Struct<{
content: import("@metamask/snaps-sdk").Panel | {

@@ -257,2 +401,32 @@ value: string;

variant?: "default" | "warning" | "critical" | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Form;
name: string;
children: ({
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
})[];
};

@@ -296,4 +470,169 @@ }, {

variant?: "default" | "warning" | "critical" | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Form;
name: string;
children: ({
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
})[];
}, null>;
}>;
export declare const OnHomePageResponseWithIdStruct: import("superstruct").Struct<{
id: string;
}, {
id: import("superstruct").Struct<string, null>;
}>;
export declare const OnHomePageResponseStruct: import("superstruct").Struct<{
content: import("@metamask/snaps-sdk").Panel | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Copyable;
sensitive?: boolean | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Divider;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Heading;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Image;
} | {
type: import("@metamask/snaps-sdk").NodeType.Spinner;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Text;
markdown?: boolean | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Address;
} | {
value: {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Image;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Text;
markdown?: boolean | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Address;
};
type: import("@metamask/snaps-sdk").NodeType.Row;
label: string;
variant?: "default" | "warning" | "critical" | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
} | {
type: import("@metamask/snaps-sdk").NodeType.Form;
name: string;
children: ({
type: import("@metamask/snaps-sdk").NodeType.Input;
name: string;
value?: string | undefined;
label?: string | undefined;
inputType?: "number" | "text" | "password" | undefined;
placeholder?: string | undefined;
} | {
value: string;
type: import("@metamask/snaps-sdk").NodeType.Button;
name?: string | undefined;
variant?: "primary" | "secondary" | undefined;
buttonType?: "button" | "submit" | undefined;
})[];
};
} | {
id: string;
}, null>;
export declare const AddressResolutionStruct: import("superstruct").Struct<{
protocol: string;
resolvedDomain: string;
}, {
protocol: import("superstruct").Struct<string, null>;
resolvedDomain: import("superstruct").Struct<string, null>;
}>;
export declare const DomainResolutionStruct: import("superstruct").Struct<{
protocol: string;
resolvedAddress: string;
}, {
protocol: import("superstruct").Struct<string, null>;
resolvedAddress: import("superstruct").Struct<string, null>;
}>;
export declare const AddressResolutionResponseStruct: import("superstruct").Struct<{
resolvedDomains: {
protocol: string;
resolvedDomain: string;
}[];
}, {
resolvedDomains: import("superstruct").Struct<{
protocol: string;
resolvedDomain: string;
}[], import("superstruct").Struct<{
protocol: string;
resolvedDomain: string;
}, {
protocol: import("superstruct").Struct<string, null>;
resolvedDomain: import("superstruct").Struct<string, null>;
}>>;
}>;
export declare const DomainResolutionResponseStruct: import("superstruct").Struct<{
resolvedAddresses: {
protocol: string;
resolvedAddress: string;
}[];
}, {
resolvedAddresses: import("superstruct").Struct<{
protocol: string;
resolvedAddress: string;
}[], import("superstruct").Struct<{
protocol: string;
resolvedAddress: string;
}, {
protocol: import("superstruct").Struct<string, null>;
resolvedAddress: import("superstruct").Struct<string, null>;
}>>;
}>;
export declare const OnNameLookupResponseStruct: import("superstruct").Struct<{
resolvedDomains: {
protocol: string;
resolvedDomain: string;
}[];
} | {
resolvedAddresses: {
protocol: string;
resolvedAddress: string;
}[];
} | null, null>;
/**

@@ -300,0 +639,0 @@ * Utility type for getting the handler function type from a handler type.

@@ -103,11 +103,2 @@ import type { Infer } from 'superstruct';

}> | undefined;
'endowment:ethereum-provider'?: {} | undefined;
'endowment:network-access'?: {} | undefined;
'endowment:webassembly'?: {} | undefined;
'endowment:signature-insight'?: {
allowSignatureOrigin?: boolean | undefined;
} | undefined;
'endowment:transaction-insight'?: {
allowTransactionOrigin?: boolean | undefined;
} | undefined;
'endowment:cronjob'?: {

@@ -123,3 +114,28 @@ jobs: {

}[];
maxRequestTime?: number | undefined;
} | undefined;
'endowment:ethereum-provider'?: {} | undefined;
'endowment:keyring'?: {
allowedOrigins?: string[] | undefined;
maxRequestTime?: number | undefined;
} | undefined;
'endowment:lifecycle-hooks'?: {
maxRequestTime?: number | undefined;
} | undefined;
'endowment:name-lookup'?: {
chains?: `${string}:${string}`[] | undefined;
maxRequestTime?: number | undefined;
matchers?: {
tlds: string[];
} | {
schemes: string[];
} | {
tlds: string[];
schemes: string[];
} | undefined;
} | undefined;
'endowment:network-access'?: {} | undefined;
'endowment:page-home'?: {
maxRequestTime?: number | undefined;
} | undefined;
'endowment:rpc'?: {

@@ -130,7 +146,11 @@ dapps?: boolean | undefined;

} | undefined;
'endowment:name-lookup'?: `${string}:${string}`[] | undefined;
'endowment:keyring'?: {
allowedOrigins?: string[] | undefined;
'endowment:signature-insight'?: {
maxRequestTime?: number | undefined;
allowSignatureOrigin?: boolean | undefined;
} | undefined;
snap_confirm?: {} | undefined;
'endowment:transaction-insight'?: {
maxRequestTime?: number | undefined;
allowTransactionOrigin?: boolean | undefined;
} | undefined;
'endowment:webassembly'?: {} | undefined;
};

@@ -137,0 +157,0 @@ manifestVersion: "0.1";

@@ -40,2 +40,19 @@ import type { InitialPermissions } from '@metamask/snaps-sdk';

export declare const ChainIdsStruct: Struct<`${string}:${string}`[], Struct<`${string}:${string}`, null>>;
export declare const LookupMatchersStruct: Struct<{
tlds: string[];
} | {
schemes: string[];
} | {
tlds: string[];
schemes: string[];
}, null>;
export declare const MINIMUM_REQUEST_TIMEOUT: number;
export declare const MAXIMUM_REQUEST_TIMEOUT: number;
export declare const MaxRequestTimeStruct: Struct<number, null>;
export declare const HandlerCaveatsStruct: Struct<{
maxRequestTime?: number | undefined;
}, {
maxRequestTime: Struct<number | undefined, null>;
}>;
export declare type HandlerCaveats = Infer<typeof HandlerCaveatsStruct>;
export declare const PermissionsStruct: Struct<{

@@ -62,11 +79,2 @@ snap_dialog?: {} | undefined;

}> | undefined;
'endowment:ethereum-provider'?: {} | undefined;
'endowment:network-access'?: {} | undefined;
'endowment:webassembly'?: {} | undefined;
'endowment:signature-insight'?: {
allowSignatureOrigin?: boolean | undefined;
} | undefined;
'endowment:transaction-insight'?: {
allowTransactionOrigin?: boolean | undefined;
} | undefined;
'endowment:cronjob'?: {

@@ -82,3 +90,28 @@ jobs: {

}[];
maxRequestTime?: number | undefined;
} | undefined;
'endowment:ethereum-provider'?: {} | undefined;
'endowment:keyring'?: {
allowedOrigins?: string[] | undefined;
maxRequestTime?: number | undefined;
} | undefined;
'endowment:lifecycle-hooks'?: {
maxRequestTime?: number | undefined;
} | undefined;
'endowment:name-lookup'?: {
chains?: `${string}:${string}`[] | undefined;
maxRequestTime?: number | undefined;
matchers?: {
tlds: string[];
} | {
schemes: string[];
} | {
tlds: string[];
schemes: string[];
} | undefined;
} | undefined;
'endowment:network-access'?: {} | undefined;
'endowment:page-home'?: {
maxRequestTime?: number | undefined;
} | undefined;
'endowment:rpc'?: {

@@ -89,21 +122,12 @@ dapps?: boolean | undefined;

} | undefined;
'endowment:name-lookup'?: `${string}:${string}`[] | undefined;
'endowment:keyring'?: {
allowedOrigins?: string[] | undefined;
'endowment:signature-insight'?: {
maxRequestTime?: number | undefined;
allowSignatureOrigin?: boolean | undefined;
} | undefined;
snap_confirm?: {} | undefined;
'endowment:transaction-insight'?: {
maxRequestTime?: number | undefined;
allowTransactionOrigin?: boolean | undefined;
} | undefined;
'endowment:webassembly'?: {} | undefined;
}, {
'endowment:ethereum-provider': Struct<{} | undefined, {}>;
'endowment:network-access': Struct<{} | undefined, {}>;
'endowment:webassembly': Struct<{} | undefined, {}>;
'endowment:signature-insight': Struct<{
allowSignatureOrigin?: boolean | undefined;
} | undefined, {
allowSignatureOrigin: Struct<boolean | undefined, null>;
}>;
'endowment:transaction-insight': Struct<{
allowTransactionOrigin?: boolean | undefined;
} | undefined, {
allowTransactionOrigin: Struct<boolean | undefined, null>;
}>;
'endowment:cronjob': Struct<{

@@ -119,2 +143,3 @@ jobs: {

}[];
maxRequestTime?: number | undefined;
} | undefined, {

@@ -151,3 +176,46 @@ jobs: Struct<{

}>>;
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:ethereum-provider': Struct<{} | undefined, {}>;
'endowment:keyring': Struct<{
allowedOrigins?: string[] | undefined;
maxRequestTime?: number | undefined;
} | undefined, {
allowedOrigins: Struct<string[] | undefined, Struct<string, null>>;
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:lifecycle-hooks': Struct<{
maxRequestTime?: number | undefined;
} | undefined, {
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:name-lookup': Struct<{
chains?: `${string}:${string}`[] | undefined;
maxRequestTime?: number | undefined;
matchers?: {
tlds: string[];
} | {
schemes: string[];
} | {
tlds: string[];
schemes: string[];
} | undefined;
} | undefined, {
chains: Struct<`${string}:${string}`[] | undefined, Struct<`${string}:${string}`, null>>;
matchers: Struct<{
tlds: string[];
} | {
schemes: string[];
} | {
tlds: string[];
schemes: string[];
} | undefined, null>;
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:network-access': Struct<{} | undefined, {}>;
'endowment:page-home': Struct<{
maxRequestTime?: number | undefined;
} | undefined, {
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:rpc': Struct<{

@@ -162,10 +230,18 @@ dapps?: boolean | undefined;

}>;
'endowment:name-lookup': Struct<`${string}:${string}`[] | undefined, Struct<`${string}:${string}`, null>>;
'endowment:keyring': Struct<{
allowedOrigins?: string[] | undefined;
'endowment:signature-insight': Struct<{
maxRequestTime?: number | undefined;
allowSignatureOrigin?: boolean | undefined;
} | undefined, {
allowedOrigins: Struct<string[] | undefined, Struct<string, null>>;
allowSignatureOrigin: Struct<boolean | undefined, null>;
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:transaction-insight': Struct<{
maxRequestTime?: number | undefined;
allowTransactionOrigin?: boolean | undefined;
} | undefined, {
allowTransactionOrigin: Struct<boolean | undefined, null>;
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:webassembly': Struct<{} | undefined, {}>;
snap_dialog: Struct<{} | undefined, {}>;
snap_confirm: Struct<{} | undefined, {}>;
snap_manageState: Struct<{} | undefined, {}>;

@@ -255,11 +331,2 @@ snap_manageAccounts: Struct<{} | undefined, {}>;

}> | undefined;
'endowment:ethereum-provider'?: {} | undefined;
'endowment:network-access'?: {} | undefined;
'endowment:webassembly'?: {} | undefined;
'endowment:signature-insight'?: {
allowSignatureOrigin?: boolean | undefined;
} | undefined;
'endowment:transaction-insight'?: {
allowTransactionOrigin?: boolean | undefined;
} | undefined;
'endowment:cronjob'?: {

@@ -275,3 +342,28 @@ jobs: {

}[];
maxRequestTime?: number | undefined;
} | undefined;
'endowment:ethereum-provider'?: {} | undefined;
'endowment:keyring'?: {
allowedOrigins?: string[] | undefined;
maxRequestTime?: number | undefined;
} | undefined;
'endowment:lifecycle-hooks'?: {
maxRequestTime?: number | undefined;
} | undefined;
'endowment:name-lookup'?: {
chains?: `${string}:${string}`[] | undefined;
maxRequestTime?: number | undefined;
matchers?: {
tlds: string[];
} | {
schemes: string[];
} | {
tlds: string[];
schemes: string[];
} | undefined;
} | undefined;
'endowment:network-access'?: {} | undefined;
'endowment:page-home'?: {
maxRequestTime?: number | undefined;
} | undefined;
'endowment:rpc'?: {

@@ -282,7 +374,11 @@ dapps?: boolean | undefined;

} | undefined;
'endowment:name-lookup'?: `${string}:${string}`[] | undefined;
'endowment:keyring'?: {
allowedOrigins?: string[] | undefined;
'endowment:signature-insight'?: {
maxRequestTime?: number | undefined;
allowSignatureOrigin?: boolean | undefined;
} | undefined;
snap_confirm?: {} | undefined;
'endowment:transaction-insight'?: {
maxRequestTime?: number | undefined;
allowTransactionOrigin?: boolean | undefined;
} | undefined;
'endowment:webassembly'?: {} | undefined;
};

@@ -366,11 +462,2 @@ manifestVersion: "0.1";

}> | undefined;
'endowment:ethereum-provider'?: {} | undefined;
'endowment:network-access'?: {} | undefined;
'endowment:webassembly'?: {} | undefined;
'endowment:signature-insight'?: {
allowSignatureOrigin?: boolean | undefined;
} | undefined;
'endowment:transaction-insight'?: {
allowTransactionOrigin?: boolean | undefined;
} | undefined;
'endowment:cronjob'?: {

@@ -386,3 +473,28 @@ jobs: {

}[];
maxRequestTime?: number | undefined;
} | undefined;
'endowment:ethereum-provider'?: {} | undefined;
'endowment:keyring'?: {
allowedOrigins?: string[] | undefined;
maxRequestTime?: number | undefined;
} | undefined;
'endowment:lifecycle-hooks'?: {
maxRequestTime?: number | undefined;
} | undefined;
'endowment:name-lookup'?: {
chains?: `${string}:${string}`[] | undefined;
maxRequestTime?: number | undefined;
matchers?: {
tlds: string[];
} | {
schemes: string[];
} | {
tlds: string[];
schemes: string[];
} | undefined;
} | undefined;
'endowment:network-access'?: {} | undefined;
'endowment:page-home'?: {
maxRequestTime?: number | undefined;
} | undefined;
'endowment:rpc'?: {

@@ -393,21 +505,12 @@ dapps?: boolean | undefined;

} | undefined;
'endowment:name-lookup'?: `${string}:${string}`[] | undefined;
'endowment:keyring'?: {
allowedOrigins?: string[] | undefined;
'endowment:signature-insight'?: {
maxRequestTime?: number | undefined;
allowSignatureOrigin?: boolean | undefined;
} | undefined;
snap_confirm?: {} | undefined;
'endowment:transaction-insight'?: {
maxRequestTime?: number | undefined;
allowTransactionOrigin?: boolean | undefined;
} | undefined;
'endowment:webassembly'?: {} | undefined;
}, {
'endowment:ethereum-provider': Struct<{} | undefined, {}>;
'endowment:network-access': Struct<{} | undefined, {}>;
'endowment:webassembly': Struct<{} | undefined, {}>;
'endowment:signature-insight': Struct<{
allowSignatureOrigin?: boolean | undefined;
} | undefined, {
allowSignatureOrigin: Struct<boolean | undefined, null>;
}>;
'endowment:transaction-insight': Struct<{
allowTransactionOrigin?: boolean | undefined;
} | undefined, {
allowTransactionOrigin: Struct<boolean | undefined, null>;
}>;
'endowment:cronjob': Struct<{

@@ -423,2 +526,3 @@ jobs: {

}[];
maxRequestTime?: number | undefined;
} | undefined, {

@@ -455,3 +559,46 @@ jobs: Struct<{

}>>;
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:ethereum-provider': Struct<{} | undefined, {}>;
'endowment:keyring': Struct<{
allowedOrigins?: string[] | undefined;
maxRequestTime?: number | undefined;
} | undefined, {
allowedOrigins: Struct<string[] | undefined, Struct<string, null>>;
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:lifecycle-hooks': Struct<{
maxRequestTime?: number | undefined;
} | undefined, {
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:name-lookup': Struct<{
chains?: `${string}:${string}`[] | undefined;
maxRequestTime?: number | undefined;
matchers?: {
tlds: string[];
} | {
schemes: string[];
} | {
tlds: string[];
schemes: string[];
} | undefined;
} | undefined, {
chains: Struct<`${string}:${string}`[] | undefined, Struct<`${string}:${string}`, null>>;
matchers: Struct<{
tlds: string[];
} | {
schemes: string[];
} | {
tlds: string[];
schemes: string[];
} | undefined, null>;
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:network-access': Struct<{} | undefined, {}>;
'endowment:page-home': Struct<{
maxRequestTime?: number | undefined;
} | undefined, {
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:rpc': Struct<{

@@ -466,10 +613,18 @@ dapps?: boolean | undefined;

}>;
'endowment:name-lookup': Struct<`${string}:${string}`[] | undefined, Struct<`${string}:${string}`, null>>;
'endowment:keyring': Struct<{
allowedOrigins?: string[] | undefined;
'endowment:signature-insight': Struct<{
maxRequestTime?: number | undefined;
allowSignatureOrigin?: boolean | undefined;
} | undefined, {
allowedOrigins: Struct<string[] | undefined, Struct<string, null>>;
allowSignatureOrigin: Struct<boolean | undefined, null>;
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:transaction-insight': Struct<{
maxRequestTime?: number | undefined;
allowTransactionOrigin?: boolean | undefined;
} | undefined, {
allowTransactionOrigin: Struct<boolean | undefined, null>;
maxRequestTime: Struct<number | undefined, null>;
}>;
'endowment:webassembly': Struct<{} | undefined, {}>;
snap_dialog: Struct<{} | undefined, {}>;
snap_confirm: Struct<{} | undefined, {}>;
snap_manageState: Struct<{} | undefined, {}>;

@@ -476,0 +631,0 @@ snap_manageAccounts: Struct<{} | undefined, {}>;

@@ -58,3 +58,3 @@ import type { Failure } from 'superstruct';

export declare class SnapsStructError<Type, Schema> extends StructError {
constructor(struct: Struct<Type, Schema>, prefix: string, suffix: string, failure: StructError, failures: () => Generator<Failure>);
constructor(struct: Struct<Type, Schema>, prefix: string, suffix: string, failure: StructError, failures: () => Generator<Failure>, colorize?: boolean);
}

@@ -66,2 +66,3 @@ declare type GetErrorOptions<Type, Schema> = {

error: StructError;
colorize?: boolean;
};

@@ -86,5 +87,6 @@ /**

* @param options.error - The `superstruct` error to wrap.
* @param options.colorize - Whether to colorize the value. Defaults to `true`.
* @returns The `SnapsStructError`.
*/
export declare function getError<Type, Schema>({ struct, prefix, suffix, error, }: GetErrorOptions<Type, Schema>): SnapsStructError<Type, Schema>;
export declare function getError<Type, Schema>({ struct, prefix, suffix, error, colorize, }: GetErrorOptions<Type, Schema>): SnapsStructError<Type, Schema>;
/**

@@ -115,14 +117,16 @@ * A wrapper of `superstruct`'s `create` function that throws a

* @param struct - The struct.
* @param colorize - Whether to colorize the value. Defaults to `true`.
* @returns The union struct names, or `null` if the struct is not a union
* struct.
*/
export declare function getUnionStructNames<Type, Schema>(struct: Struct<Type, Schema>): string[] | null;
export declare function getUnionStructNames<Type, Schema>(struct: Struct<Type, Schema>, colorize?: boolean): string[] | null;
/**
* Get a error prefix from a `superstruct` failure. This is useful for
* Get an error prefix from a `superstruct` failure. This is useful for
* formatting the error message returned by `superstruct`.
*
* @param failure - The `superstruct` failure.
* @param colorize - Whether to colorize the value. Defaults to `true`.
* @returns The error prefix.
*/
export declare function getStructErrorPrefix(failure: Failure): string;
export declare function getStructErrorPrefix(failure: Failure, colorize?: boolean): string;
/**

@@ -135,5 +139,6 @@ * Get a string describing the failure. This is similar to the `message`

* @param failure - The `superstruct` failure.
* @param colorize - Whether to colorize the value. Defaults to `true`.
* @returns A string describing the failure.
*/
export declare function getStructFailureMessage<Type, Schema>(struct: Struct<Type, Schema>, failure: Failure): string;
export declare function getStructFailureMessage<Type, Schema>(struct: Struct<Type, Schema>, failure: Failure, colorize?: boolean): string;
/**

@@ -145,5 +150,54 @@ * Get a string describing the errors. This formats all the errors in a

* @param failures - The `superstruct` failures.
* @param colorize - Whether to colorize the value. Defaults to `true`.
* @returns A string describing the errors.
*/
export declare function getStructErrorMessage<Type, Schema>(struct: Struct<Type, Schema>, failures: Failure[]): string;
export declare function getStructErrorMessage<Type, Schema>(struct: Struct<Type, Schema>, failures: Failure[], colorize?: boolean): string;
/**
* Validate a union struct, and throw readable errors if the value does not
* satisfy the struct. This is useful for improving the error messages returned
* by `superstruct`.
*
* @param value - The value to validate.
* @param struct - The `superstruct` union struct to validate the value against.
* This struct must be a union of object structs, and must have at least one
* shared key to validate against.
* @param structKey - The key to validate against. This key must be present in
* all the object structs in the union struct, and is expected to be a literal
* value.
* @param coerce - Whether to coerce the value to satisfy the struct. Defaults
* to `false`.
* @returns The validated value.
* @throws If the value does not satisfy the struct.
* @example
* const struct = union([
* object({ type: literal('a'), value: string() }),
* object({ type: literal('b'), value: number() }),
* object({ type: literal('c'), value: boolean() }),
* // ...
* ]);
*
* // At path: type — Expected the value to be one of: "a", "b", "c", but received: "d".
* validateUnion({ type: 'd', value: 'foo' }, struct, 'type');
*
* // At path: value — Expected a value of type string, but received: 42.
* validateUnion({ type: 'a', value: 42 }, struct, 'value');
*/
export declare function validateUnion<Type, Schema extends readonly Struct<any, any>[]>(value: unknown, struct: Struct<Type, Schema>, structKey: keyof Type, coerce?: boolean): any;
/**
* Create a value with the coercion logic of a union struct, and throw readable
* errors if the value does not satisfy the struct. This is useful for improving
* the error messages returned by `superstruct`.
*
* @param value - The value to validate.
* @param struct - The `superstruct` union struct to validate the value against.
* This struct must be a union of object structs, and must have at least one
* shared key to validate against.
* @param structKey - The key to validate against. This key must be present in
* all the object structs in the union struct, and is expected to be a literal
* value.
* @returns The validated value.
* @throws If the value does not satisfy the struct.
* @see validateUnion
*/
export declare function createUnion<Type, Schema extends readonly Struct<any, any>[]>(value: unknown, struct: Struct<Type, Schema>, structKey: keyof Type): any;
export {};
{
"name": "@metamask/snaps-utils",
"version": "5.2.0",
"version": "6.0.0",
"repository": {

@@ -72,7 +72,7 @@ "type": "git",

"@metamask/key-tree": "^9.0.0",
"@metamask/permission-controller": "^7.1.0",
"@metamask/permission-controller": "^8.0.0",
"@metamask/rpc-errors": "^6.1.0",
"@metamask/slip44": "^3.1.0",
"@metamask/snaps-registry": "^3.0.0",
"@metamask/snaps-sdk": "^1.4.0",
"@metamask/snaps-sdk": "^2.0.0",
"@metamask/utils": "^8.3.0",

@@ -101,3 +101,3 @@ "@noble/hashes": "^1.3.1",

"@metamask/eslint-config-typescript": "^12.1.0",
"@metamask/post-message-stream": "^7.0.0",
"@metamask/post-message-stream": "^8.0.0",
"@swc/cli": "^0.1.62",

@@ -104,0 +104,0 @@ "@swc/core": "1.3.78",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc