UNPKG

@walletconnect/core

Version:
1 lines 342 kB
{"version":3,"file":"index.cjs.js","sources":["../src/constants/core.ts","../src/constants/crypto.ts","../src/constants/keychain.ts","../src/constants/messages.ts","../src/constants/publisher.ts","../src/constants/relayer.ts","../src/constants/store.ts","../src/constants/subscriber.ts","../src/constants/pairing.ts","../src/constants/history.ts","../src/constants/expirer.ts","../src/constants/verify.ts","../src/constants/echo.ts","../src/constants/events.ts","../../../node_modules/multiformats/esm/vendor/base-x.js","../../../node_modules/multiformats/esm/src/bytes.js","../../../node_modules/multiformats/esm/src/bases/base.js","../../../node_modules/multiformats/esm/src/bases/identity.js","../../../node_modules/multiformats/esm/src/bases/base2.js","../../../node_modules/multiformats/esm/src/bases/base8.js","../../../node_modules/multiformats/esm/src/bases/base10.js","../../../node_modules/multiformats/esm/src/bases/base16.js","../../../node_modules/multiformats/esm/src/bases/base32.js","../../../node_modules/multiformats/esm/src/bases/base36.js","../../../node_modules/multiformats/esm/src/bases/base58.js","../../../node_modules/multiformats/esm/src/bases/base64.js","../../../node_modules/multiformats/esm/src/bases/base256emoji.js","../../../node_modules/multiformats/esm/vendor/varint.js","../../../node_modules/multiformats/esm/src/varint.js","../../../node_modules/multiformats/esm/src/hashes/digest.js","../../../node_modules/multiformats/esm/src/hashes/hasher.js","../../../node_modules/multiformats/esm/src/hashes/sha2-browser.js","../../../node_modules/multiformats/esm/src/hashes/identity.js","../../../node_modules/multiformats/esm/src/codecs/json.js","../../../node_modules/multiformats/esm/src/basics.js","../../../node_modules/uint8arrays/esm/src/alloc.js","../../../node_modules/uint8arrays/esm/src/util/bases.js","../../../node_modules/uint8arrays/esm/src/from-string.js","../src/controllers/keychain.ts","../src/controllers/crypto.ts","../src/controllers/messages.ts","../src/controllers/publisher.ts","../src/controllers/topicmap.ts","../src/controllers/subscriber.ts","../src/controllers/relayer.ts","../../../node_modules/es-toolkit/dist/function/noop.mjs","../../../node_modules/es-toolkit/dist/predicate/isPlainObject.mjs","../../../node_modules/es-toolkit/dist/compat/_internal/getSymbols.mjs","../../../node_modules/es-toolkit/dist/compat/_internal/getTag.mjs","../../../node_modules/es-toolkit/dist/compat/_internal/tags.mjs","../../../node_modules/es-toolkit/dist/compat/util/eq.mjs","../../../node_modules/es-toolkit/dist/predicate/isEqualWith.mjs","../../../node_modules/es-toolkit/dist/predicate/isEqual.mjs","../src/controllers/store.ts","../src/controllers/pairing.ts","../src/controllers/history.ts","../src/controllers/expirer.ts","../src/controllers/verify.ts","../src/controllers/echo.ts","../src/controllers/events.ts","../src/core.ts","../src/index.ts"],"sourcesContent":["export const CORE_PROTOCOL = \"wc\";\nexport const CORE_VERSION = 2;\nexport const CORE_CONTEXT = \"core\";\n\nexport const CORE_STORAGE_PREFIX = `${CORE_PROTOCOL}@${CORE_VERSION}:${CORE_CONTEXT}:`;\n\nexport const CORE_DEFAULT = {\n name: CORE_CONTEXT,\n logger: \"error\",\n};\n\nexport const CORE_STORAGE_OPTIONS = {\n database: \":memory:\",\n};\n","import { ONE_DAY } from \"@walletconnect/time\";\n\nexport const CRYPTO_CONTEXT = \"crypto\";\n\nexport const CRYPTO_CLIENT_SEED = \"client_ed25519_seed\";\n\nexport const CRYPTO_JWT_TTL = ONE_DAY;\n","export const KEYCHAIN_CONTEXT = \"keychain\";\n\nexport const KEYCHAIN_STORAGE_VERSION = \"0.3\";\n","export const MESSAGES_CONTEXT = \"messages\";\n\nexport const MESSAGES_STORAGE_VERSION = \"0.3\";\n","import { SIX_HOURS } from \"@walletconnect/time\";\n\nexport const PUBLISHER_DEFAULT_TTL = SIX_HOURS;\n\nexport const PUBLISHER_CONTEXT = \"publisher\";\n","export const RELAYER_DEFAULT_PROTOCOL = \"irn\";\n\nexport const RELAYER_DEFAULT_LOGGER = \"error\";\n\nexport const RELAYER_DEFAULT_RELAY_URL = \"wss://relay.walletconnect.org\";\n\nexport const RELAYER_CONTEXT = \"relayer\";\n\nexport const RELAYER_EVENTS = {\n message: \"relayer_message\",\n message_ack: \"relayer_message_ack\",\n connect: \"relayer_connect\",\n disconnect: \"relayer_disconnect\",\n error: \"relayer_error\",\n connection_stalled: \"relayer_connection_stalled\",\n transport_closed: \"relayer_transport_closed\",\n publish: \"relayer_publish\",\n};\n\nexport const RELAYER_SUBSCRIBER_SUFFIX = \"_subscription\";\n\nexport const RELAYER_PROVIDER_EVENTS = {\n payload: \"payload\",\n connect: \"connect\",\n disconnect: \"disconnect\",\n error: \"error\",\n};\n\nexport const RELAYER_RECONNECT_TIMEOUT = 0.1;\n\nexport const RELAYER_STORAGE_OPTIONS = {\n database: \":memory:\",\n};\n\n// Updated automatically via `new-version` npm script.\n\nexport const RELAYER_SDK_VERSION = \"2.19.2\";\n\n// delay to wait before closing the transport connection after init if not active\nexport const RELAYER_TRANSPORT_CUTOFF = 10_000;\n\nexport const TRANSPORT_TYPES = {\n link_mode: \"link_mode\",\n relay: \"relay\",\n} as const;\n\nexport const MESSAGE_DIRECTION = {\n inbound: \"inbound\",\n outbound: \"outbound\",\n} as const;\n","export const STORE_STORAGE_VERSION = \"0.3\";\n\nexport const WALLETCONNECT_CLIENT_ID = \"WALLETCONNECT_CLIENT_ID\";\nexport const WALLETCONNECT_LINK_MODE_APPS = \"WALLETCONNECT_LINK_MODE_APPS\";\n","import { THIRTY_DAYS, FIVE_SECONDS } from \"@walletconnect/time\";\n\nexport const SUBSCRIBER_EVENTS = {\n created: \"subscription_created\",\n deleted: \"subscription_deleted\",\n expired: \"subscription_expired\",\n disabled: \"subscription_disabled\",\n sync: \"subscription_sync\",\n resubscribed: \"subscription_resubscribed\",\n};\n\nexport const SUBSCRIBER_DEFAULT_TTL = THIRTY_DAYS;\n\nexport const SUBSCRIBER_CONTEXT = \"subscription\";\n\nexport const SUBSCRIBER_STORAGE_VERSION = \"0.3\";\n\nexport const PENDING_SUB_RESOLUTION_TIMEOUT = FIVE_SECONDS * 1000;\n","import { THIRTY_DAYS, ONE_DAY, THIRTY_SECONDS } from \"@walletconnect/time\";\nimport { RelayerTypes, PairingJsonRpcTypes } from \"@walletconnect/types\";\n\nexport const PAIRING_CONTEXT = \"pairing\";\n\nexport const PAIRING_STORAGE_VERSION = \"0.3\";\n\nexport const PAIRING_DEFAULT_TTL = THIRTY_DAYS;\n\nexport const PAIRING_RPC_OPTS: Record<\n PairingJsonRpcTypes.WcMethod | \"unregistered_method\",\n {\n req: RelayerTypes.PublishOptions;\n res: RelayerTypes.PublishOptions;\n }\n> = {\n wc_pairingDelete: {\n req: {\n ttl: ONE_DAY,\n prompt: false,\n tag: 1000,\n },\n res: {\n ttl: ONE_DAY,\n prompt: false,\n tag: 1001,\n },\n },\n wc_pairingPing: {\n req: {\n ttl: THIRTY_SECONDS,\n prompt: false,\n tag: 1002,\n },\n res: {\n ttl: THIRTY_SECONDS,\n prompt: false,\n tag: 1003,\n },\n },\n unregistered_method: {\n req: {\n ttl: ONE_DAY,\n prompt: false,\n tag: 0,\n },\n res: {\n ttl: ONE_DAY,\n prompt: false,\n tag: 0,\n },\n },\n};\n\nexport const PAIRING_EVENTS = {\n create: \"pairing_create\",\n expire: \"pairing_expire\",\n delete: \"pairing_delete\",\n ping: \"pairing_ping\",\n};\n","export const HISTORY_EVENTS = {\n created: \"history_created\",\n updated: \"history_updated\",\n deleted: \"history_deleted\",\n sync: \"history_sync\",\n};\n\nexport const HISTORY_CONTEXT = \"history\";\n\nexport const HISTORY_STORAGE_VERSION = \"0.3\";\n","import { ONE_DAY } from \"@walletconnect/time\";\n\nexport const EXPIRER_CONTEXT = \"expirer\";\n\nexport const EXPIRER_EVENTS = {\n created: \"expirer_created\",\n deleted: \"expirer_deleted\",\n expired: \"expirer_expired\",\n sync: \"expirer_sync\",\n};\n\nexport const EXPIRER_STORAGE_VERSION = \"0.3\";\n\nexport const EXPIRER_DEFAULT_TTL = ONE_DAY;\n","export const VERIFY_CONTEXT = \"verify-api\";\n\nconst VERIFY_SERVER_COM = \"https://verify.walletconnect.com\";\nconst VERIFY_SERVER_ORG = \"https://verify.walletconnect.org\";\nexport const VERIFY_SERVER = VERIFY_SERVER_ORG;\nexport const VERIFY_SERVER_V3 = `${VERIFY_SERVER}/v3`;\n\nexport const TRUSTED_VERIFY_URLS = [VERIFY_SERVER_COM, VERIFY_SERVER_ORG];\n","export const ECHO_CONTEXT = \"echo\";\n\nexport const ECHO_URL = \"https://echo.walletconnect.com\";\n","export const EVENT_CLIENT_CONTEXT = \"event-client\";\n\nexport const EVENT_CLIENT_PAIRING_TRACES = {\n pairing_started: \"pairing_started\",\n pairing_uri_validation_success: \"pairing_uri_validation_success\",\n pairing_uri_not_expired: \"pairing_uri_not_expired\",\n store_new_pairing: \"store_new_pairing\",\n subscribing_pairing_topic: \"subscribing_pairing_topic\",\n subscribe_pairing_topic_success: \"subscribe_pairing_topic_success\",\n existing_pairing: \"existing_pairing\",\n pairing_not_expired: \"pairing_not_expired\",\n emit_inactive_pairing: \"emit_inactive_pairing\",\n emit_session_proposal: \"emit_session_proposal\",\n subscribing_to_pairing_topic: \"subscribing_to_pairing_topic\",\n};\n\nexport const EVENT_CLIENT_PAIRING_ERRORS = {\n no_wss_connection: \"no_wss_connection\",\n no_internet_connection: \"no_internet_connection\",\n malformed_pairing_uri: \"malformed_pairing_uri\",\n active_pairing_already_exists: \"active_pairing_already_exists\",\n subscribe_pairing_topic_failure: \"subscribe_pairing_topic_failure\",\n pairing_expired: \"pairing_expired\",\n proposal_expired: \"proposal_expired\",\n proposal_listener_not_found: \"proposal_listener_not_found\",\n};\n\nexport const EVENT_CLIENT_SESSION_TRACES = {\n session_approve_started: \"session_approve_started\",\n proposal_not_expired: \"proposal_not_expired\",\n session_namespaces_validation_success: \"session_namespaces_validation_success\",\n create_session_topic: \"create_session_topic\",\n subscribing_session_topic: \"subscribing_session_topic\",\n subscribe_session_topic_success: \"subscribe_session_topic_success\",\n publishing_session_approve: \"publishing_session_approve\",\n session_approve_publish_success: \"session_approve_publish_success\",\n store_session: \"store_session\",\n publishing_session_settle: \"publishing_session_settle\",\n session_settle_publish_success: \"session_settle_publish_success\",\n};\n\nexport const EVENT_CLIENT_SESSION_ERRORS = {\n no_internet_connection: \"no_internet_connection\",\n no_wss_connection: \"no_wss_connection\",\n proposal_expired: \"proposal_expired\",\n subscribe_session_topic_failure: \"subscribe_session_topic_failure\",\n session_approve_publish_failure: \"session_approve_publish_failure\",\n session_settle_publish_failure: \"session_settle_publish_failure\",\n session_approve_namespace_validation_failure: \"session_approve_namespace_validation_failure\",\n proposal_not_found: \"proposal_not_found\",\n};\n\nexport const EVENT_CLIENT_AUTHENTICATE_TRACES = {\n authenticated_session_approve_started: \"authenticated_session_approve_started\",\n authenticated_session_not_expired: \"authenticated_session_not_expired\",\n chains_caip2_compliant: \"chains_caip2_compliant\",\n chains_evm_compliant: \"chains_evm_compliant\",\n create_authenticated_session_topic: \"create_authenticated_session_topic\",\n cacaos_verified: \"cacaos_verified\",\n store_authenticated_session: \"store_authenticated_session\",\n subscribing_authenticated_session_topic: \"subscribing_authenticated_session_topic\",\n subscribe_authenticated_session_topic_success: \"subscribe_authenticated_session_topic_success\",\n publishing_authenticated_session_approve: \"publishing_authenticated_session_approve\",\n authenticated_session_approve_publish_success: \"authenticated_session_approve_publish_success\",\n};\n\nexport const EVENT_CLIENT_AUTHENTICATE_ERRORS = {\n no_internet_connection: \"no_internet_connection\",\n no_wss_connection: \"no_wss_connection\",\n missing_session_authenticate_request: \"missing_session_authenticate_request\",\n session_authenticate_request_expired: \"session_authenticate_request_expired\",\n chains_caip2_compliant_failure: \"chains_caip2_compliant_failure\",\n chains_evm_compliant_failure: \"chains_evm_compliant_failure\",\n invalid_cacao: \"invalid_cacao\",\n subscribe_authenticated_session_topic_failure: \"subscribe_authenticated_session_topic_failure\",\n authenticated_session_approve_publish_failure: \"authenticated_session_approve_publish_failure\",\n authenticated_session_pending_request_not_found:\n \"authenticated_session_pending_request_not_found\",\n};\n\nexport const EVENTS_STORAGE_VERSION = 0.1;\n\nexport const EVENTS_STORAGE_CONTEXT = \"event-client\";\n\nexport const EVENTS_STORAGE_CLEANUP_INTERVAL = 86400;\n\nexport const EVENTS_CLIENT_API_URL = \"https://pulse.walletconnect.org/batch\";\n","function base(ALPHABET, name) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256);\n var iFACTOR = Math.log(256) / Math.log(BASE);\n function encode(source) {\n if (source instanceof Uint8Array);\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n var size = (pend - pbegin) * iFACTOR + 1 >>> 0;\n var b58 = new Uint8Array(size);\n while (pbegin !== pend) {\n var carry = source[pbegin];\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && it1 !== -1; it1--, i++) {\n carry += 256 * b58[it1] >>> 0;\n b58[it1] = carry % BASE >>> 0;\n carry = carry / BASE >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n if (source[psz] === ' ') {\n return;\n }\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n var size = (source.length - psz) * FACTOR + 1 >>> 0;\n var b256 = new Uint8Array(size);\n while (source[psz]) {\n var carry = BASE_MAP[source.charCodeAt(psz)];\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && it3 !== -1; it3--, i++) {\n carry += BASE * b256[it3] >>> 0;\n b256[it3] = carry % 256 >>> 0;\n carry = carry / 256 >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n if (source[psz] === ' ') {\n return;\n }\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${ name } character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\nexport default _brrp__multiformats_scope_baseX;","const empty = new Uint8Array(0);\nconst toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\nconst fromHex = hex => {\n const hexes = hex.match(/../g);\n return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n};\nconst equals = (aa, bb) => {\n if (aa === bb)\n return true;\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n};\nconst coerce = o => {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')\n return o;\n if (o instanceof ArrayBuffer)\n return new Uint8Array(o);\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n};\nconst isBinary = o => o instanceof ArrayBuffer || ArrayBuffer.isView(o);\nconst fromString = str => new TextEncoder().encode(str);\nconst toString = b => new TextDecoder().decode(b);\nexport {\n equals,\n coerce,\n isBinary,\n fromHex,\n toHex,\n fromString,\n toString,\n empty\n};","import basex from '../../vendor/base-x.js';\nimport { coerce } from '../bytes.js';\nclass Encoder {\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${ this.prefix }${ this.baseEncode(bytes) }`;\n } else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\nclass Decoder {\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${ JSON.stringify(text) }, ${ this.name } decoder only supports inputs prefixed with ${ this.prefix }`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n } else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder) {\n return decoder.decode(input);\n } else {\n throw RangeError(`Unable to decode multibase string ${ JSON.stringify(input) }, only inputs prefixed with ${ Object.keys(this.decoders) } are supported`);\n }\n }\n}\nexport const or = (left, right) => new ComposedDecoder({\n ...left.decoders || { [left.prefix]: left },\n ...right.decoders || { [right.prefix]: right }\n});\nexport class Codec {\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nexport const from = ({name, prefix, encode, decode}) => new Codec(name, prefix, encode, decode);\nexport const baseX = ({prefix, name, alphabet}) => {\n const {encode, decode} = basex(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: text => coerce(decode(text))\n });\n};\nconst decode = (string, alphabet, bitsPerChar, name) => {\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n const out = new Uint8Array(end * bitsPerChar / 8 | 0);\n let bits = 0;\n let buffer = 0;\n let written = 0;\n for (let i = 0; i < end; ++i) {\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${ name } character`);\n }\n buffer = buffer << bitsPerChar | value;\n bits += bitsPerChar;\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 255 & buffer >> bits;\n }\n }\n if (bits >= bitsPerChar || 255 & buffer << 8 - bits) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n};\nconst encode = (data, alphabet, bitsPerChar) => {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0;\n let buffer = 0;\n for (let i = 0; i < data.length; ++i) {\n buffer = buffer << 8 | data[i];\n bits += 8;\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & buffer >> bits];\n }\n }\n if (bits) {\n out += alphabet[mask & buffer << bitsPerChar - bits];\n }\n if (pad) {\n while (out.length * bitsPerChar & 7) {\n out += '=';\n }\n }\n return out;\n};\nexport const rfc4648 = ({name, prefix, bitsPerChar, alphabet}) => {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n};","import { from } from './base.js';\nimport {\n fromString,\n toString\n} from '../bytes.js';\nexport const identity = from({\n prefix: '\\0',\n name: 'identity',\n encode: buf => toString(buf),\n decode: str => fromString(str)\n});","import { rfc4648 } from './base.js';\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n});","import { rfc4648 } from './base.js';\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n});","import { baseX } from './base.js';\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n});","import { rfc4648 } from './base.js';\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n});\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n});","import { rfc4648 } from './base.js';\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n});\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n});\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n});\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n});\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n});\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n});\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n});\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n});\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});","import { baseX } from './base.js';\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n});\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n});","import { baseX } from './base.js';\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});","import { rfc4648 } from './base.js';\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n});\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n});\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n});\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n});","import { from } from './base.js';\nconst alphabet = Array.from('\\uD83D\\uDE80\\uD83E\\uDE90\\u2604\\uD83D\\uDEF0\\uD83C\\uDF0C\\uD83C\\uDF11\\uD83C\\uDF12\\uD83C\\uDF13\\uD83C\\uDF14\\uD83C\\uDF15\\uD83C\\uDF16\\uD83C\\uDF17\\uD83C\\uDF18\\uD83C\\uDF0D\\uD83C\\uDF0F\\uD83C\\uDF0E\\uD83D\\uDC09\\u2600\\uD83D\\uDCBB\\uD83D\\uDDA5\\uD83D\\uDCBE\\uD83D\\uDCBF\\uD83D\\uDE02\\u2764\\uD83D\\uDE0D\\uD83E\\uDD23\\uD83D\\uDE0A\\uD83D\\uDE4F\\uD83D\\uDC95\\uD83D\\uDE2D\\uD83D\\uDE18\\uD83D\\uDC4D\\uD83D\\uDE05\\uD83D\\uDC4F\\uD83D\\uDE01\\uD83D\\uDD25\\uD83E\\uDD70\\uD83D\\uDC94\\uD83D\\uDC96\\uD83D\\uDC99\\uD83D\\uDE22\\uD83E\\uDD14\\uD83D\\uDE06\\uD83D\\uDE44\\uD83D\\uDCAA\\uD83D\\uDE09\\u263A\\uD83D\\uDC4C\\uD83E\\uDD17\\uD83D\\uDC9C\\uD83D\\uDE14\\uD83D\\uDE0E\\uD83D\\uDE07\\uD83C\\uDF39\\uD83E\\uDD26\\uD83C\\uDF89\\uD83D\\uDC9E\\u270C\\u2728\\uD83E\\uDD37\\uD83D\\uDE31\\uD83D\\uDE0C\\uD83C\\uDF38\\uD83D\\uDE4C\\uD83D\\uDE0B\\uD83D\\uDC97\\uD83D\\uDC9A\\uD83D\\uDE0F\\uD83D\\uDC9B\\uD83D\\uDE42\\uD83D\\uDC93\\uD83E\\uDD29\\uD83D\\uDE04\\uD83D\\uDE00\\uD83D\\uDDA4\\uD83D\\uDE03\\uD83D\\uDCAF\\uD83D\\uDE48\\uD83D\\uDC47\\uD83C\\uDFB6\\uD83D\\uDE12\\uD83E\\uDD2D\\u2763\\uD83D\\uDE1C\\uD83D\\uDC8B\\uD83D\\uDC40\\uD83D\\uDE2A\\uD83D\\uDE11\\uD83D\\uDCA5\\uD83D\\uDE4B\\uD83D\\uDE1E\\uD83D\\uDE29\\uD83D\\uDE21\\uD83E\\uDD2A\\uD83D\\uDC4A\\uD83E\\uDD73\\uD83D\\uDE25\\uD83E\\uDD24\\uD83D\\uDC49\\uD83D\\uDC83\\uD83D\\uDE33\\u270B\\uD83D\\uDE1A\\uD83D\\uDE1D\\uD83D\\uDE34\\uD83C\\uDF1F\\uD83D\\uDE2C\\uD83D\\uDE43\\uD83C\\uDF40\\uD83C\\uDF37\\uD83D\\uDE3B\\uD83D\\uDE13\\u2B50\\u2705\\uD83E\\uDD7A\\uD83C\\uDF08\\uD83D\\uDE08\\uD83E\\uDD18\\uD83D\\uDCA6\\u2714\\uD83D\\uDE23\\uD83C\\uDFC3\\uD83D\\uDC90\\u2639\\uD83C\\uDF8A\\uD83D\\uDC98\\uD83D\\uDE20\\u261D\\uD83D\\uDE15\\uD83C\\uDF3A\\uD83C\\uDF82\\uD83C\\uDF3B\\uD83D\\uDE10\\uD83D\\uDD95\\uD83D\\uDC9D\\uD83D\\uDE4A\\uD83D\\uDE39\\uD83D\\uDDE3\\uD83D\\uDCAB\\uD83D\\uDC80\\uD83D\\uDC51\\uD83C\\uDFB5\\uD83E\\uDD1E\\uD83D\\uDE1B\\uD83D\\uDD34\\uD83D\\uDE24\\uD83C\\uDF3C\\uD83D\\uDE2B\\u26BD\\uD83E\\uDD19\\u2615\\uD83C\\uDFC6\\uD83E\\uDD2B\\uD83D\\uDC48\\uD83D\\uDE2E\\uD83D\\uDE46\\uD83C\\uDF7B\\uD83C\\uDF43\\uD83D\\uDC36\\uD83D\\uDC81\\uD83D\\uDE32\\uD83C\\uDF3F\\uD83E\\uDDE1\\uD83C\\uDF81\\u26A1\\uD83C\\uDF1E\\uD83C\\uDF88\\u274C\\u270A\\uD83D\\uDC4B\\uD83D\\uDE30\\uD83E\\uDD28\\uD83D\\uDE36\\uD83E\\uDD1D\\uD83D\\uDEB6\\uD83D\\uDCB0\\uD83C\\uDF53\\uD83D\\uDCA2\\uD83E\\uDD1F\\uD83D\\uDE41\\uD83D\\uDEA8\\uD83D\\uDCA8\\uD83E\\uDD2C\\u2708\\uD83C\\uDF80\\uD83C\\uDF7A\\uD83E\\uDD13\\uD83D\\uDE19\\uD83D\\uDC9F\\uD83C\\uDF31\\uD83D\\uDE16\\uD83D\\uDC76\\uD83E\\uDD74\\u25B6\\u27A1\\u2753\\uD83D\\uDC8E\\uD83D\\uDCB8\\u2B07\\uD83D\\uDE28\\uD83C\\uDF1A\\uD83E\\uDD8B\\uD83D\\uDE37\\uD83D\\uDD7A\\u26A0\\uD83D\\uDE45\\uD83D\\uDE1F\\uD83D\\uDE35\\uD83D\\uDC4E\\uD83E\\uDD32\\uD83E\\uDD20\\uD83E\\uDD27\\uD83D\\uDCCC\\uD83D\\uDD35\\uD83D\\uDC85\\uD83E\\uDDD0\\uD83D\\uDC3E\\uD83C\\uDF52\\uD83D\\uDE17\\uD83E\\uDD11\\uD83C\\uDF0A\\uD83E\\uDD2F\\uD83D\\uDC37\\u260E\\uD83D\\uDCA7\\uD83D\\uDE2F\\uD83D\\uDC86\\uD83D\\uDC46\\uD83C\\uDFA4\\uD83D\\uDE47\\uD83C\\uDF51\\u2744\\uD83C\\uDF34\\uD83D\\uDCA3\\uD83D\\uDC38\\uD83D\\uDC8C\\uD83D\\uDCCD\\uD83E\\uDD40\\uD83E\\uDD22\\uD83D\\uDC45\\uD83D\\uDCA1\\uD83D\\uDCA9\\uD83D\\uDC50\\uD83D\\uDCF8\\uD83D\\uDC7B\\uD83E\\uDD10\\uD83E\\uDD2E\\uD83C\\uDFBC\\uD83E\\uDD75\\uD83D\\uDEA9\\uD83C\\uDF4E\\uD83C\\uDF4A\\uD83D\\uDC7C\\uD83D\\uDC8D\\uD83D\\uDCE3\\uD83E\\uDD42');\nconst alphabetBytesToChars = alphabet.reduce((p, c, i) => {\n p[i] = c;\n return p;\n}, []);\nconst alphabetCharsToBytes = alphabet.reduce((p, c, i) => {\n p[c.codePointAt(0)] = i;\n return p;\n}, []);\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${ char }`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nexport const base256emoji = from({\n prefix: '\\uD83D\\uDE80',\n name: 'base256emoji',\n encode,\n decode\n});","var encode_1 = encode;\nvar MSB = 128, REST = 127, MSBALL = ~REST, INT = Math.pow(2, 31);\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n while (num >= INT) {\n out[offset++] = num & 255 | MSB;\n num /= 128;\n }\n while (num & MSBALL) {\n out[offset++] = num & 255 | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n encode.bytes = offset - oldOffset + 1;\n return out;\n}\nvar decode = read;\nvar MSB$1 = 128, REST$1 = 127;\nfunction read(buf, offset) {\n var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;\n do {\n if (counter >= l) {\n read.bytes = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf[counter++];\n res += shift < 28 ? (b & REST$1) << shift : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1);\n read.bytes = counter - offset;\n return res;\n}\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\nvar length = function (value) {\n return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10;\n};\nvar varint = {\n encode: encode_1,\n decode: decode,\n encodingLength: length\n};\nvar _brrp_varint = varint;\nexport default _brrp_varint;","import varint from '../vendor/varint.js';\nexport const decode = (data, offset = 0) => {\n const code = varint.decode(data, offset);\n return [\n code,\n varint.decode.bytes\n ];\n};\nexport const encodeTo = (int, target, offset = 0) => {\n varint.encode(int, target, offset);\n return target;\n};\nexport const encodingLength = int => {\n return varint.encodingLength(int);\n};","import {\n coerce,\n equals as equalBytes\n} from '../bytes.js';\nimport * as varint from '../varint.js';\nexport const create = (code, digest) => {\n const size = digest.byteLength;\n const sizeOffset = varint.encodingLength(code);\n const digestOffset = sizeOffset + varint.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n varint.encodeTo(code, bytes, 0);\n varint.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n};\nexport const decode = multihash => {\n const bytes = coerce(multihash);\n const [code, sizeOffset] = varint.decode(bytes);\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n};\nexport const equals = (a, b) => {\n if (a === b) {\n return true;\n } else {\n return a.code === b.code && a.size === b.size && equalBytes(a.bytes, b.bytes);\n }\n};\nexport class Digest {\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}","import * as Digest from './digest.js';\nexport const from = ({name, code, encode}) => new Hasher(name, code, encode);\nexport class Hasher {\n constructor(name, code, encode) {\n this.name = name;\n this.code = code;\n this.encode = encode;\n }\n digest(input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input);\n return result instanceof Uint8Array ? Digest.create(this.code, result) : result.then(digest => Digest.create(this.code, digest));\n } else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}","import { from } from './hasher.js';\nconst sha = name => async data => new Uint8Array(await crypto.subtle.digest(name, data));\nexport const sha256 = from({\n name: 'sha2-256',\n code: 18,\n encode: sha('SHA-256')\n});\nexport const sha512 = from({\n name: 'sha2-512',\n code: 19,\n encode: sha('SHA-512')\n});","import { coerce } from '../bytes.js';\nimport * as Digest from './digest.js';\nconst code = 0;\nconst name = 'identity';\nconst encode = coerce;\nconst digest = input => Digest.create(code, encode(input));\nexport const identity = {\n code,\n name,\n encode,\n digest\n};","const textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\nexport const name = 'json';\nexport const code = 512;\nexport const encode = node => textEncoder.encode(JSON.stringify(node));\nexport const decode = data => JSON.parse(textDecoder.decode(data));","import * as identityBase from './bases/identity.js';\nimport * as base2 from './bases/base2.js';\nimport * as base8 from './bases/base8.js';\nimport * as base10 from './bases/base10.js';\nimport * as base16 from './bases/base16.js';\nimport * as base32 from './bases/base32.js';\nimport * as base36 from './bases/base36.js';\nimport * as base58 from './bases/base58.js';\nimport * as base64 from './bases/base64.js';\nimport * as base256emoji from './bases/base256emoji.js';\nimport * as sha2 from './hashes/sha2.js';\nimport * as identity from './hashes/identity.js';\nimport * as raw from './codecs/raw.js';\nimport * as json from './codecs/json.js';\nimport {\n CID,\n hasher,\n digest,\n varint,\n bytes\n} from './index.js';\nconst bases = {\n ...identityBase,\n ...base2,\n ...base8,\n ...base10,\n ...base16,\n ...base32,\n ...base36,\n ...base58,\n ...base64,\n ...base256emoji\n};\nconst hashes = {\n ...sha2,\n ...identity\n};\nconst codecs = {\n raw,\n json\n};\nexport {\n CID,\n hasher,\n digest,\n varint,\n bytes,\n hashes,\n bases,\n codecs\n};","export function alloc(size = 0) {\n if (globalThis.Buffer != null && globalThis.Buffer.alloc != null) {\n return globalThis.Buffer.alloc(size);\n }\n return new Uint8Array(size);\n}\nexport function allocUnsafe(size = 0) {\n if (globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null) {\n return globalThis.Buffer.allocUnsafe(size);\n }\n return new Uint8Array(size);\n}","import { bases } from 'multiformats/basics';\nimport { allocUnsafe } from '../alloc.js';\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: { decode }\n };\n}\nconst string = createCodec('utf8', 'u', buf => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, str => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', buf => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, str => {\n str = str.substring(1);\n const buf = allocUnsafe(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii: ascii,\n binary: ascii,\n ...bases\n};\nexport default BASES;","import bases from './util/bases.js';\nexport function fromString(string, encoding = 'utf8') {\n const base = bases[encoding];\n if (!base) {\n throw new Error(`Unsupported encoding \"${ encoding }\"`);\n }\n if ((encoding === 'utf8' || encoding === 'utf-8') && globalThis.Buffer != null && globalThis.Buffer.from != null) {\n return globalThis.Buffer.from(string, 'utf8');\n }\n return base.decoder.decode(`${ base.prefix }${ string }`);\n}","import { generateChildLogger, getLoggerContext, Logger } from \"@walletconnect/logger\";\nimport { ICore, IKeyChain } from \"@walletconnect/types\";\nimport { getInternalError, mapToObj, objToMap } from \"@walletconnect/utils\";\n\nimport { CORE_STORAGE_PREFIX, KEYCHAIN_CONTEXT, KEYCHAIN_STORAGE_VERSION } from \"../constants\";\n\nexport class KeyChain implements IKeyChain {\n public keychain = new Map<string, string>();\n public name = KEYCHAIN_CONTEXT;\n public version = KEYCHAIN_STORAGE_VERSION;\n\n private initialized = false;\n private storagePrefix = CORE_STORAGE_PREFIX;\n\n constructor(public core: ICore, public logger: Logger) {\n this.core = core;\n this.logger = generateChildLogger(logger, this.name);\n }\n\n public init: IKeyChain[\"init\"] = async () => {\n if (!this.initialized) {\n const keychain = await this.getKeyChain();\n if (typeof keychain !== \"undefined\") {\n this.keychain = keychain;\n }\n this.initialized = true;\n }\n };\n\n get context() {\n return getLoggerContext(this.logger);\n }\n\n get storageKey() {\n return this.storagePrefix + this.version + this.core.customStoragePrefix + \"//\" + this.name;\n }\n\n public has: IKeyChain[\"has\"] = (tag) => {\n this.isInitialized();\n return this.keychain.has(tag);\n };\n\n public set: IKeyChain[\"set\"] = async (tag, key) => {\n this.isInitialized();\n this.keychain.set(tag, key);\n await this.persist();\n };\n\n public get: IKeyChain[\"get\"] = (tag) => {\n this.isInitialized();\n const key = this.keychain.get(tag);\n if (typeof key === \"undefined\") {\n const { message } = getInternalError(\"NO_MATCHING_KEY\", `${this.name}: ${tag}`);\n throw new Error(message);\n }\n return key;\n };\n\n public del: IKeyChain[\"del\"] = async (tag) => {\n this.isInitialized();\n this.keychain.delete(tag);\n await this.persist();\n };\n\n // ---------- Private ----------------------------------------------- //\n\n private async setKeyChain(keychain: Map<string, string>) {\n await this.core.storage.setItem<Record<string, string>>(this.storageKey, mapToObj(keychain));\n }\n\n private async getKeyChain() {\n const keychain = await this.core.storage.getItem<Record<string, string>>(this.storageKey);\n return typeof keychain !== \"undefined\" ? objToMap(keychain) : undefined;\n }\n\n private async persist() {\n await this.setKeyChain(this.keychain);\n }\n\n private isInitialized() {\n if (!this.initialized) {\n const { message } = getInternalError(\"NOT_INITIALIZED\", this.name);\n throw new Error(message);\n }\n }\n}\n","import { generateChildLogger, getLoggerContext, Logger } from \"@walletconnect/logger\";\nimport { safeJsonParse, safeJsonStringify } from \"@walletconnect/safe-json\";\nimport { ICore, ICrypto, IKeyChain } from \"@walletconnect/types\";\nimport * as relayAuth from \"@walletconnect/relay-auth\";\nimport { fromString } from \"uint8arrays/from-string\";\nimport {\n decrypt,\n deriveSymKey,\n encrypt,\n generateKeyPair as generateKeyPairUtil,\n hashKey,\n getInternalError,\n generateRandomBytes32,\n validateEncoding,\n validateDecoding,\n isTypeOneEnvelope,\n isTypeTwoEnvelope,\n encodeTypeTwoEnvelope,\n decodeTypeTwoEnvelope,\n deserialize,\n decodeTypeByte,\n BASE16,\n BASE64,\n} from \"@walletconnect/utils\";\nimport { toString } from \"uint8arrays\";\n\nimport { CRYPTO_CONTEXT, CRYPTO_CLIENT_SEED, CRYPTO_JWT_TTL } from \"../constants\";\nimport { KeyChain } from \"./keychain\";\n\nexport class Crypto implements ICrypto {\n public name = CRYPTO_CONTEXT;\n public keychain: ICrypto[\"keychain\"];\n public readonly randomSessionIdentifier = generateRandomBytes32();\n\n private initialized = false;\n\n constructor(public core: ICore, public logger: Logger, keychain?: IKeyChain) {\n this.core = core;\n this.logger = generateChildLogger(logger, this.name);\n this.keychain = keychain || new KeyChain(this.core, this.logger);\n }\n\n public init: ICrypto[\"init\"] = async () => {\n if (!this.initialized) {\n await this.keychain.init();\n this.initialized = true;\n }\n };\n\n get context() {\n return getLoggerContext(this.logger);\n }\n\n public hasKeys: ICrypto[\"hasKeys\"] = (tag) => {\n this.isInitialized();\n return this.keychain.has(tag);\n };\n\n public getClientId: ICrypto[\"getClientId\"] = async () => {\n this.isInitialized();\n const seed = await this.getClientSeed();\n const keyPair = relayAuth.generateKeyPair(seed);\n const clientId = relayAuth.encodeIss(keyPair.publicKey);\n return clientId;\n };\n\n public generateKeyPair: ICrypto[\"generateKeyPair\"] = () => {\n this.isInitialized();\n const keyPair = generateKeyPairUtil();\n return this.setPrivateKey(keyPair.publicKey, keyPair.privateKey);\n };\n\n public signJWT: ICrypto[\"signJWT\"] = async (aud) => {\n this.isInitialized();\n const seed = await this.getClientSeed();\n const keyPair = relayAuth.generateKeyPair(seed);\n const sub = this.randomSessionIdentifier;\n const ttl = CRYPTO_JWT_TTL;\n const jwt = await relayAuth.signJWT(sub, aud, ttl, keyPair);\n return jwt;\n };\n\n public generateSharedKey: ICrypto[\"generateSharedKey\"] = (\n selfPublicKey,\n peerPublicKey,\n overrideTopic,\n ) => {\n this.isInitialized();\n const selfPrivateKey = this.getPrivateKey(selfPublicKey);\n const symKey = deriveSymKey(selfPrivateKey, peerPublicKey);\n return this.setSymKey(symKey, overrideTopic);\n };\n\n public setSymKey: ICrypto[\"setSymKey\"] = async (symKey, overrideTopic) => {\n this.isInitialized();\n const topic = overrideTopic || hashKey(symKey);\n await this.keychain.set(topic, symKey);\n return topic;\n };\n\n public deleteKeyPair: ICrypto[\"deleteKeyPair\"] = async (publicKey: string) => {\n this.isInitialized();\n await this.keychain.del(publicKey);\n };\n\n public deleteSymKey: ICrypto[\"deleteSymKey\"] = async (topic: string) => {\n this.isInitialized();\n await this.keychain.del(topic);\n };\n\n public encode: ICrypto[\"encode\"] = async (topic, payload, opts) => {\n this.isInitialized();\n const params = validateEncoding(opts);\n const message = safeJsonStringify(payload);\n\n if (isTypeTwoEnvelope(params)) {\n return encodeTypeTwoEnvelope(message, opts?.encoding);\n }\n\n if (isTypeOneEnvelope(params)) {\n const selfPublicKey = params.senderPublicKey;\n const peerPublicKey = params.receiverPublicKey;\n topic = await this.generateSharedKey(selfPublicKey, peerPublicKey);\n }\n const symKey = this.getSymKey(topic);\n const { type, senderPublicKey } = params;\n const result = encrypt({ type, symKey, message, senderPublicKey, encoding: opts?.encoding });\n return result;\n };\n\n public decode: ICrypto[\"decode\"] = async (topic, encoded, opts) => {\n this.isInitialized();\n const params = validateDecoding(encoded, opts);\n if (isTypeTwoEnvelope(params)) {\n const message = decodeTypeTwoEnvelope(encoded, opts?.encoding);\n return safeJsonParse(message);\n }\n if (isTypeOneEnvelope(params)) {\n const selfPublicKey = params.receiverPublicKey;\n const peerPublicKey = params.senderPublicKey;\n topic = await this.generateSharedKey(selfPublicKey, peerPublicKey);\n }\n try {\n const symKey = this.getSymKey(topic);\n const message = decrypt({ symKey, encoded, encoding: opts?.encoding });\n const payload = safeJsonParse(message);\n return payload;\n } catch (error) {\n this.logger.error(\n `Failed to decode message from topic: '${topic}', clientId: '${await this.getClientId()}'`,\n );\n this.logger.error(error);\n }\n };\n\n public getPayloadType: ICrypto[\"getPayloadType\"] = (encoded, encoding = BASE64) => {\n const deserialized = deserialize({ encoded, encoding });\n return decodeTypeByte(deserialized.type);\n };\n\n public getPayloadSenderPublicKey: ICrypto[\"getPayloadSenderPublicKey\"] = (\n encoded,\n encoding = BASE64,\n ) => {\n const deserialized = deserialize({ encoded, encoding });\n return deserialized.senderPublicKey\n ? toString(deserialized.senderPublicKey, BASE16)\n : undefined;\n };\n\n // ---------- Private ----------------------------------------------- //\n\n private async setPrivateKey(publicKey: string, privateKey: string): Promise<string> {\n await this.keychain.set(publicKey, privateKey);\n return publicKey;\n }\n\n private getPrivateKey(publicKey: string) {\n const privateKey = this.keychain.get(publicKey);\n return privateKey;\n }\n\n private async getClientSeed(): Promise<Uint8Array> {\n let seed = \"\";\n try {\n seed = this.keychain.get(CRYPTO_CLIENT_SEED);\n } catch {\n seed = generateRandomBytes32();\n await this.keychain.set(CRYPTO_CLIENT_SEED, seed);\n }\n return fromString(seed, \"base16\");\n }\n\n private getSymKey(topic: string) {\n const symKey = this.keychain.get(topic);\n return symKey;\n }\n\n private isInitialized() {\n if (!this.initialized) {\n const { message } = getInternalError(\"NOT_INITIALIZED\", this.name);\n throw new Error(message);\n }\n }\n}\n","import { generateChildLogger, getLoggerContext, Logger } from \"@walletconnect/logger\";\nimport { ICore, IMessageTracker, MessageRecord } from \"@walletconnect/types\";\nimport { hashMessage, mapToObj, objToMap, getInternalError } from \"@walletconnect/utils\";\nimport {\n CORE_STORAGE_PREFIX,\n MESSAGE_DIRECTION,\n MESSAGES_CONTEXT,\n MESSAGES_STORAGE_VERSION,\n} from \"../constants\";\n\nexport class MessageTracker extends IMessageTracker {\n public messages = new Map<string, MessageRecord>();\n /**\n * stores messages that have not been acknowledged by the implementing client\n * this is used to prevent losing messages in race conditions such as\n * when a message is received by the relayer before the implementing client is ready to receive it\n */\n public messagesWithoutClientAck = new Map<string, MessageRecord>();\n public name = MESSAGES_CONTEXT;\n public version = MESSAGES_STORAGE_VERSION;\n\n private initialized = false;\n private storagePrefix = CORE_STORAGE_PREFIX;\n\n constructor(public logger: Logger, public core: ICore) {\n super(logger, core);\n this.logger = generateChildLogger(logger, this.name);\n this.core = core;\n }\n\n public init: IMessageTracker[\"init\"] = async () => {\n if (!this.initialized) {\n this.logger.trace(`Initialized`);\n try {\n const messages = await this.getRelayerMessages();\n if (typeof messages !== \"undefined\") {\n this.messages = messages;\n }\n const messagesWithoutClientAck = await this.getRelayerMessagesWithoutClientAck();\n if (typeof messagesWithoutClientAck !== \"undefined\") {\n this.messagesWithoutClientAck = messagesWithoutClientAck;\n }\n this.logger.debug(`Successfully Restored records for ${this.name}`);\n this.logger.trace({ type: \"method\", method: \"restore\", size: this.messages.size });\n } catch (e) {\n this.logger.debug(`Failed to Restore records for ${this.name}`);\n this.logger.error(e as any);\n } finally {\n this.initialized = true;\n }\n }\n };\n\n get context(): string {\n return getLoggerContext(this.logger);\n }\n\n get storageKey() {\n return this.storagePrefix + this.version + this.core.customStoragePrefix + \"//\" + this.name;\n }\n\n get storageKeyWithoutClientAck() {\n return (\n this.storagePrefix +\n this.version +\n this.core.customStoragePrefix +\n \"//\" +\n this.name +\n \"_withoutClientAck\"\n );\n }\n\n public set: IMessageTracker[\"set\"] = async (topic, message, direction) => {\n this.isInitialized();\n const hash = hashMessage(message);\n let messages = this.messages.get(topic);\n if (typeof messages === \"undefined\") {\n messages = {};\n }\n if (typeof messages[hash] !== \"undefined\") {\n return hash;\n }\n messages[hash] = message;\n this.messages.set(topic, messages);\n // Only store messages without client ack for inbound messages\n if (directi