UNPKG

@0xfutbol/id

Version:

React component library with shared providers for 0xFutbol ID

1,068 lines (1,064 loc) 208 kB
import {S as getDefaultExportFromCjs,T as bytesToHex}from'./index-BJCJzM2_.js';import {s as sha256}from'./sha256-DQJaatHj.js';import'react';import'react/jsx-runtime';import'@0xfutbol/id-sign';import'react-use';import'@0xfutbol/constants';import'thirdweb';import'@matchain/matchid-sdk-react';import'@tanstack/react-query';import'@matchain/matchid-sdk-react/index.css';import'react-dom';const walletLogo = (type, width) => { let height; switch (type) { case 'standard': height = width; return `data:image/svg+xml,%3Csvg width='${width}' height='${height}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `; case 'circle': height = width; return `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${width}' height='${height}' viewBox='0 0 999.81 999.81'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052fe;%7D.cls-2%7Bfill:%23fefefe;%7D.cls-3%7Bfill:%230152fe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M655-115.9h56c.83,1.59,2.36.88,3.56,1a478,478,0,0,1,75.06,10.42C891.4-81.76,978.33-32.58,1049.19,44q116.7,126,131.94,297.61c.38,4.14-.34,8.53,1.78,12.45v59c-1.58.84-.91,2.35-1,3.56a482.05,482.05,0,0,1-10.38,74.05c-24,106.72-76.64,196.76-158.83,268.93s-178.18,112.82-287.2,122.6c-4.83.43-9.86-.25-14.51,1.77H654c-1-1.68-2.69-.91-4.06-1a496.89,496.89,0,0,1-105.9-18.59c-93.54-27.42-172.78-77.59-236.91-150.94Q199.34,590.1,184.87,426.58c-.47-5.19.25-10.56-1.77-15.59V355c1.68-1,.91-2.7,1-4.06a498.12,498.12,0,0,1,18.58-105.9c26-88.75,72.64-164.9,140.6-227.57q126-116.27,297.21-131.61C645.32-114.57,650.35-113.88,655-115.9Zm377.92,500c0-192.44-156.31-349.49-347.56-350.15-194.13-.68-350.94,155.13-352.29,347.42-1.37,194.55,155.51,352.1,348.56,352.47C876.15,734.23,1032.93,577.84,1032.93,384.11Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-2' d='M1032.93,384.11c0,193.73-156.78,350.12-351.29,349.74-193-.37-349.93-157.92-348.56-352.47C334.43,189.09,491.24,33.28,685.37,34,876.62,34.62,1032.94,191.67,1032.93,384.11ZM683,496.81q43.74,0,87.48,0c15.55,0,25.32-9.72,25.33-25.21q0-87.48,0-175c0-15.83-9.68-25.46-25.59-25.46H595.77c-15.88,0-25.57,9.64-25.58,25.46q0,87.23,0,174.45c0,16.18,9.59,25.7,25.84,25.71Z' transform='translate(-183.1 115.9)'/%3E%3Cpath class='cls-3' d='M683,496.81H596c-16.25,0-25.84-9.53-25.84-25.71q0-87.23,0-174.45c0-15.82,9.7-25.46,25.58-25.46H770.22c15.91,0,25.59,9.63,25.59,25.46q0,87.47,0,175c0,15.49-9.78,25.2-25.33,25.21Q726.74,496.84,683,496.81Z' transform='translate(-183.1 115.9)'/%3E%3C/svg%3E`; case 'text': height = (0.1 * width).toFixed(2); return `data:image/svg+xml,%3Csvg width='${width}' height='${height}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`; case 'textWithLogo': height = (0.25 * width).toFixed(2); return `data:image/svg+xml,%3Csvg width='${width}' height='${height}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%230052ff;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`; case 'textLight': height = (0.1 * width).toFixed(2); return `data:image/svg+xml,%3Csvg width='${width}' height='${height}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 528.15 53.64'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3ECoinbase_Wordmark_SubBrands_ALL%3C/title%3E%3Cpath class='cls-1' d='M164.45,15a15,15,0,0,0-11.74,5.4V0h-8.64V52.92h8.5V48a15,15,0,0,0,11.88,5.62c10.37,0,18.21-8.21,18.21-19.3S174.67,15,164.45,15Zm-1.3,30.67c-6.19,0-10.73-4.83-10.73-11.31S157,23,163.22,23s10.66,4.82,10.66,11.37S169.34,45.65,163.15,45.65Zm83.31-14.91-6.34-.93c-3-.43-5.18-1.44-5.18-3.82,0-2.59,2.8-3.89,6.62-3.89,4.18,0,6.84,1.8,7.42,4.76h8.35c-.94-7.49-6.7-11.88-15.55-11.88-9.15,0-15.2,4.68-15.2,11.3,0,6.34,4,10,12,11.16l6.33.94c3.1.43,4.83,1.65,4.83,4,0,2.95-3,4.17-7.2,4.17-5.12,0-8-2.09-8.43-5.25h-8.49c.79,7.27,6.48,12.38,16.84,12.38,9.44,0,15.7-4.32,15.7-11.74C258.12,35.28,253.58,31.82,246.46,30.74Zm-27.65-2.3c0-8.06-4.9-13.46-15.27-13.46-9.79,0-15.26,5-16.34,12.6h8.57c.43-3,2.73-5.4,7.63-5.4,4.39,0,6.55,1.94,6.55,4.32,0,3.09-4,3.88-8.85,4.39-6.63.72-14.84,3-14.84,11.66,0,6.7,5,11,12.89,11,6.19,0,10.08-2.59,12-6.7.28,3.67,3,6.05,6.84,6.05h5v-7.7h-4.25Zm-8.5,9.36c0,5-4.32,8.64-9.57,8.64-3.24,0-6-1.37-6-4.25,0-3.67,4.39-4.68,8.42-5.11s6-1.22,7.13-2.88ZM281.09,15c-11.09,0-19.23,8.35-19.23,19.36,0,11.6,8.72,19.3,19.37,19.3,9,0,16.06-5.33,17.86-12.89h-9c-1.3,3.31-4.47,5.19-8.71,5.19-5.55,0-9.72-3.46-10.66-9.51H299.3V33.12C299.3,22.46,291.53,15,281.09,15Zm-9.87,15.26c1.37-5.18,5.26-7.7,9.72-7.7,4.9,0,8.64,2.8,9.51,7.7ZM19.3,23a9.84,9.84,0,0,1,9.5,7h9.14c-1.65-8.93-9-15-18.57-15A19,19,0,0,0,0,34.34c0,11.09,8.28,19.3,19.37,19.3,9.36,0,16.85-6,18.5-15H28.8a9.75,9.75,0,0,1-9.43,7.06c-6.27,0-10.66-4.83-10.66-11.31S13,23,19.3,23Zm41.11-8A19,19,0,0,0,41,34.34c0,11.09,8.28,19.3,19.37,19.3A19,19,0,0,0,79.92,34.27C79.92,23.33,71.64,15,60.41,15Zm.07,30.67c-6.19,0-10.73-4.83-10.73-11.31S54.22,23,60.41,23s10.8,4.89,10.8,11.37S66.67,45.65,60.48,45.65ZM123.41,15c-5.62,0-9.29,2.3-11.45,5.54V15.7h-8.57V52.92H112V32.69C112,27,115.63,23,121,23c5,0,8.06,3.53,8.06,8.64V52.92h8.64V31C137.66,21.6,132.84,15,123.41,15ZM92,.36a5.36,5.36,0,0,0-5.55,5.47,5.55,5.55,0,0,0,11.09,0A5.35,5.35,0,0,0,92,.36Zm-9.72,23h5.4V52.92h8.64V15.7h-14Zm298.17-7.7L366.2,52.92H372L375.29,44H392l3.33,8.88h6L386.87,15.7ZM377,39.23l6.45-17.56h.1l6.56,17.56ZM362.66,15.7l-7.88,29h-.11l-8.14-29H341l-8,28.93h-.1l-8-28.87H319L329.82,53h5.45l8.19-29.24h.11L352,53h5.66L368.1,15.7Zm135.25,0v4.86h12.32V52.92h5.6V20.56h12.32V15.7ZM467.82,52.92h25.54V48.06H473.43v-12h18.35V31.35H473.43V20.56h19.93V15.7H467.82ZM443,15.7h-5.6V52.92h24.32V48.06H443Zm-30.45,0h-5.61V52.92h24.32V48.06H412.52Z'/%3E%3C/svg%3E`; case 'textWithLogoLight': height = (0.25 * width).toFixed(2); return `data:image/svg+xml,%3Csvg width='${width}' height='${height}' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 308.44 77.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fefefe;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M142.94,20.2l-7.88,29H135l-8.15-29h-5.55l-8,28.93h-.11l-8-28.87H99.27l10.84,37.27h5.44l8.2-29.24h.1l8.41,29.24h5.66L148.39,20.2Zm17.82,0L146.48,57.42h5.82l3.28-8.88h16.65l3.34,8.88h6L167.16,20.2Zm-3.44,23.52,6.45-17.55h.11l6.56,17.55ZM278.2,20.2v4.86h12.32V57.42h5.6V25.06h12.32V20.2ZM248.11,57.42h25.54V52.55H253.71V40.61h18.35V35.85H253.71V25.06h19.94V20.2H248.11ZM223.26,20.2h-5.61V57.42H242V52.55H223.26Zm-30.46,0h-5.6V57.42h24.32V52.55H192.8Zm-154,38A19.41,19.41,0,1,1,57.92,35.57H77.47a38.81,38.81,0,1,0,0,6.47H57.92A19.39,19.39,0,0,1,38.81,58.21Z'/%3E%3C/svg%3E`; default: height = width; return `data:image/svg+xml,%3Csvg width='${width}' height='${height}' viewBox='0 0 1024 1024' fill='none' xmlns='http://www.w3.org/2000/svg'%3E %3Crect width='1024' height='1024' fill='%230052FF'/%3E %3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M152 512C152 710.823 313.177 872 512 872C710.823 872 872 710.823 872 512C872 313.177 710.823 152 512 152C313.177 152 152 313.177 152 512ZM420 396C406.745 396 396 406.745 396 420V604C396 617.255 406.745 628 420 628H604C617.255 628 628 617.255 628 604V420C628 406.745 617.255 396 604 396H420Z' fill='white'/%3E %3C/svg%3E `; } };// Copyright (c) 2018-2024 Coinbase, Inc. <https://www.coinbase.com/> // TODO: clean up, or possibly deprecate Storage class class ScopedLocalStorage { constructor(scope, module) { this.scope = scope; this.module = module; } storeObject(key, item) { this.setItem(key, JSON.stringify(item)); } loadObject(key) { const item = this.getItem(key); return item ? JSON.parse(item) : undefined; } setItem(key, value) { localStorage.setItem(this.scopedKey(key), value); } getItem(key) { return localStorage.getItem(this.scopedKey(key)); } removeItem(key) { localStorage.removeItem(this.scopedKey(key)); } clear() { const prefix = this.scopedKey(''); const keysToRemove = []; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); if (typeof key === 'string' && key.startsWith(prefix)) { keysToRemove.push(key); } } keysToRemove.forEach((key) => localStorage.removeItem(key)); } scopedKey(key) { return `-${this.scope}${this.module ? `:${this.module}` : ''}:${key}`; } static clearAll() { new ScopedLocalStorage('CBWSDK').clear(); new ScopedLocalStorage('walletlink').clear(); } }const standardErrorCodes = { rpc: { invalidInput: -32e3, resourceNotFound: -32001, resourceUnavailable: -32002, transactionRejected: -32003, methodNotSupported: -32004, limitExceeded: -32005, parse: -32700, invalidRequest: -32600, methodNotFound: -32601, invalidParams: -32602, internal: -32603, }, provider: { userRejectedRequest: 4001, unauthorized: 4100, unsupportedMethod: 4200, disconnected: 4900, chainDisconnected: 4901, unsupportedChain: 4902, }, }; const errorValues = { '-32700': { standard: 'JSON RPC 2.0', message: 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.', }, '-32600': { standard: 'JSON RPC 2.0', message: 'The JSON sent is not a valid Request object.', }, '-32601': { standard: 'JSON RPC 2.0', message: 'The method does not exist / is not available.', }, '-32602': { standard: 'JSON RPC 2.0', message: 'Invalid method parameter(s).', }, '-32603': { standard: 'JSON RPC 2.0', message: 'Internal JSON-RPC error.', }, '-32000': { standard: 'EIP-1474', message: 'Invalid input.', }, '-32001': { standard: 'EIP-1474', message: 'Resource not found.', }, '-32002': { standard: 'EIP-1474', message: 'Resource unavailable.', }, '-32003': { standard: 'EIP-1474', message: 'Transaction rejected.', }, '-32004': { standard: 'EIP-1474', message: 'Method not supported.', }, '-32005': { standard: 'EIP-1474', message: 'Request limit exceeded.', }, '4001': { standard: 'EIP-1193', message: 'User rejected the request.', }, '4100': { standard: 'EIP-1193', message: 'The requested account and/or method has not been authorized by the user.', }, '4200': { standard: 'EIP-1193', message: 'The requested method is not supported by this Ethereum provider.', }, '4900': { standard: 'EIP-1193', message: 'The provider is disconnected from all chains.', }, '4901': { standard: 'EIP-1193', message: 'The provider is disconnected from the specified chain.', }, '4902': { standard: 'EIP-3085', message: 'Unrecognized chain ID.', }, };const FALLBACK_MESSAGE = 'Unspecified error message.'; const JSON_RPC_SERVER_ERROR_MESSAGE = 'Unspecified server error.'; /** * Gets the message for a given code, or a fallback message if the code has * no corresponding message. */ function getMessageFromCode(code, fallbackMessage = FALLBACK_MESSAGE) { if (code && Number.isInteger(code)) { const codeString = code.toString(); if (hasKey(errorValues, codeString)) { return errorValues[codeString].message; } if (isJsonRpcServerError(code)) { return JSON_RPC_SERVER_ERROR_MESSAGE; } } return fallbackMessage; } /** * Returns whether the given code is valid. * A code is only valid if it has a message. */ function isValidCode(code) { if (!Number.isInteger(code)) { return false; } const codeString = code.toString(); if (errorValues[codeString]) { return true; } if (isJsonRpcServerError(code)) { return true; } return false; } function serialize(error, { shouldIncludeStack = false } = {}) { const serialized = {}; if (error && typeof error === 'object' && !Array.isArray(error) && hasKey(error, 'code') && isValidCode(error.code)) { const _error = error; serialized.code = _error.code; if (_error.message && typeof _error.message === 'string') { serialized.message = _error.message; if (hasKey(_error, 'data')) { serialized.data = _error.data; } } else { serialized.message = getMessageFromCode(serialized.code); serialized.data = { originalError: assignOriginalError(error) }; } } else { serialized.code = standardErrorCodes.rpc.internal; serialized.message = hasStringProperty(error, 'message') ? error.message : FALLBACK_MESSAGE; serialized.data = { originalError: assignOriginalError(error) }; } if (shouldIncludeStack) { serialized.stack = hasStringProperty(error, 'stack') ? error.stack : undefined; } return serialized; } // Internal function isJsonRpcServerError(code) { return code >= -32099 && code <= -32e3; } function assignOriginalError(error) { if (error && typeof error === 'object' && !Array.isArray(error)) { return Object.assign({}, error); } return error; } function hasKey(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } function hasStringProperty(obj, prop) { return (typeof obj === 'object' && obj !== null && prop in obj && typeof obj[prop] === 'string'); }const standardErrors = { rpc: { parse: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.parse, arg), invalidRequest: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.invalidRequest, arg), invalidParams: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.invalidParams, arg), methodNotFound: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.methodNotFound, arg), internal: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.internal, arg), server: (opts) => { if (!opts || typeof opts !== 'object' || Array.isArray(opts)) { throw new Error('Ethereum RPC Server errors must provide single object argument.'); } const { code } = opts; if (!Number.isInteger(code) || code > -32005 || code < -32099) { throw new Error('"code" must be an integer such that: -32099 <= code <= -32005'); } return getEthJsonRpcError(code, opts); }, invalidInput: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.invalidInput, arg), resourceNotFound: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.resourceNotFound, arg), resourceUnavailable: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.resourceUnavailable, arg), transactionRejected: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.transactionRejected, arg), methodNotSupported: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.methodNotSupported, arg), limitExceeded: (arg) => getEthJsonRpcError(standardErrorCodes.rpc.limitExceeded, arg), }, provider: { userRejectedRequest: (arg) => { return getEthProviderError(standardErrorCodes.provider.userRejectedRequest, arg); }, unauthorized: (arg) => { return getEthProviderError(standardErrorCodes.provider.unauthorized, arg); }, unsupportedMethod: (arg) => { return getEthProviderError(standardErrorCodes.provider.unsupportedMethod, arg); }, disconnected: (arg) => { return getEthProviderError(standardErrorCodes.provider.disconnected, arg); }, chainDisconnected: (arg) => { return getEthProviderError(standardErrorCodes.provider.chainDisconnected, arg); }, unsupportedChain: (arg) => { return getEthProviderError(standardErrorCodes.provider.unsupportedChain, arg); }, custom: (opts) => { if (!opts || typeof opts !== 'object' || Array.isArray(opts)) { throw new Error('Ethereum Provider custom errors must provide single object argument.'); } const { code, message, data } = opts; if (!message || typeof message !== 'string') { throw new Error('"message" must be a nonempty string'); } return new EthereumProviderError(code, message, data); }, }, }; // Internal function getEthJsonRpcError(code, arg) { const [message, data] = parseOpts(arg); return new EthereumRpcError(code, message || getMessageFromCode(code), data); } function getEthProviderError(code, arg) { const [message, data] = parseOpts(arg); return new EthereumProviderError(code, message || getMessageFromCode(code), data); } function parseOpts(arg) { if (arg) { if (typeof arg === 'string') { return [arg]; } else if (typeof arg === 'object' && !Array.isArray(arg)) { const { message, data } = arg; if (message && typeof message !== 'string') { throw new Error('Must specify string message.'); } return [message || undefined, data]; } } return []; } class EthereumRpcError extends Error { constructor(code, message, data) { if (!Number.isInteger(code)) { throw new Error('"code" must be an integer.'); } if (!message || typeof message !== 'string') { throw new Error('"message" must be a nonempty string.'); } super(message); this.code = code; if (data !== undefined) { this.data = data; } } } class EthereumProviderError extends EthereumRpcError { /** * Create an Ethereum Provider JSON-RPC error. * `code` must be an integer in the 1000 <= 4999 range. */ constructor(code, message, data) { if (!isValidEthProviderCode(code)) { throw new Error('"code" must be an integer such that: 1000 <= code <= 4999'); } super(code, message, data); } } function isValidEthProviderCode(code) { return Number.isInteger(code) && code >= 1000 && code <= 4999; }function OpaqueType() { return (value) => value; } const HexString = OpaqueType(); const AddressString = OpaqueType(); const BigIntString = OpaqueType(); function IntNumber(num) { return Math.floor(num); }/* eslint-disable @typescript-eslint/no-explicit-any */ // Copyright (c) 2018-2023 Coinbase, Inc. <https://www.coinbase.com/> const INT_STRING_REGEX = /^[0-9]*$/; const HEXADECIMAL_STRING_REGEX = /^[a-f0-9]*$/; /** * @param length number of bytes */ function randomBytesHex(length) { return uint8ArrayToHex(crypto.getRandomValues(new Uint8Array(length))); } function uint8ArrayToHex(value) { return [...value].map((b) => b.toString(16).padStart(2, '0')).join(''); } function hexStringToUint8Array(hexString) { return new Uint8Array(hexString.match(/.{1,2}/g).map((byte) => Number.parseInt(byte, 16))); } function hexStringFromBuffer(buf, includePrefix = false) { const hex = buf.toString('hex'); return HexString(includePrefix ? `0x${hex}` : hex); } function encodeToHexString(str) { return hexStringFromBuffer(ensureBuffer(str), true); } function bigIntStringFromBigInt(bi) { return BigIntString(bi.toString(10)); } function hexStringFromNumber(num) { return HexString(`0x${BigInt(num).toString(16)}`); } function has0xPrefix(str) { return str.startsWith('0x') || str.startsWith('0X'); } function strip0x(hex) { if (has0xPrefix(hex)) { return hex.slice(2); } return hex; } function prepend0x(hex) { if (has0xPrefix(hex)) { return `0x${hex.slice(2)}`; } return `0x${hex}`; } function isHexString(hex) { if (typeof hex !== 'string') { return false; } const s = strip0x(hex).toLowerCase(); return HEXADECIMAL_STRING_REGEX.test(s); } function ensureHexString(hex, includePrefix = false) { if (typeof hex === 'string') { const s = strip0x(hex).toLowerCase(); if (HEXADECIMAL_STRING_REGEX.test(s)) { return HexString(includePrefix ? `0x${s}` : s); } } throw standardErrors.rpc.invalidParams(`"${String(hex)}" is not a hexadecimal string`); } function ensureEvenLengthHexString(hex, includePrefix = false) { let h = ensureHexString(hex, false); if (h.length % 2 === 1) { h = HexString(`0${h}`); } return includePrefix ? HexString(`0x${h}`) : h; } function ensureAddressString(str) { if (typeof str === 'string') { const s = strip0x(str).toLowerCase(); if (isHexString(s) && s.length === 40) { return AddressString(prepend0x(s)); } } throw standardErrors.rpc.invalidParams(`Invalid Ethereum address: ${String(str)}`); } function ensureBuffer(str) { if (Buffer.isBuffer(str)) { return str; } if (typeof str === 'string') { if (isHexString(str)) { const s = ensureEvenLengthHexString(str, false); return Buffer.from(s, 'hex'); } return Buffer.from(str, 'utf8'); } throw standardErrors.rpc.invalidParams(`Not binary data: ${String(str)}`); } function ensureIntNumber(num) { if (typeof num === 'number' && Number.isInteger(num)) { return IntNumber(num); } if (typeof num === 'string') { if (INT_STRING_REGEX.test(num)) { return IntNumber(Number(num)); } if (isHexString(num)) { return IntNumber(Number(BigInt(ensureEvenLengthHexString(num, true)))); } } throw standardErrors.rpc.invalidParams(`Not an integer: ${String(num)}`); } function ensureBigInt(val) { if (val !== null && (typeof val === 'bigint' || isBigNumber(val))) { return BigInt(val.toString(10)); } if (typeof val === 'number') { return BigInt(ensureIntNumber(val)); } if (typeof val === 'string') { if (INT_STRING_REGEX.test(val)) { return BigInt(val); } if (isHexString(val)) { return BigInt(ensureEvenLengthHexString(val, true)); } } throw standardErrors.rpc.invalidParams(`Not an integer: ${String(val)}`); } function ensureParsedJSONObject(val) { if (typeof val === 'string') { return JSON.parse(val); } if (typeof val === 'object') { return val; } throw standardErrors.rpc.invalidParams(`Not a JSON string or an object: ${String(val)}`); } function isBigNumber(val) { if (val == null || typeof val.constructor !== 'function') { return false; } const { constructor } = val; return typeof constructor.config === 'function' && typeof constructor.EUCLID === 'number'; } function getFavicon() { const el = document.querySelector('link[sizes="192x192"]') || document.querySelector('link[sizes="180x180"]') || document.querySelector('link[rel="icon"]') || document.querySelector('link[rel="shortcut icon"]'); const { protocol, host } = document.location; const href = el ? el.getAttribute('href') : null; if (!href || href.startsWith('javascript:') || href.startsWith('vbscript:')) { return `${protocol}//${host}/favicon.ico`; // fallback } if (href.startsWith('http://') || href.startsWith('https://') || href.startsWith('data:')) { return href; } if (href.startsWith('//')) { return protocol + href; } return `${protocol}//${host}${href}`; }async function generateKeyPair() { return crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256', }, true, ['deriveKey']); } async function deriveSharedSecret(ownPrivateKey, peerPublicKey) { return crypto.subtle.deriveKey({ name: 'ECDH', public: peerPublicKey, }, ownPrivateKey, { name: 'AES-GCM', length: 256, }, false, ['encrypt', 'decrypt']); } async function encrypt(sharedSecret, plainText) { const iv = crypto.getRandomValues(new Uint8Array(12)); const cipherText = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, }, sharedSecret, new TextEncoder().encode(plainText)); return { iv, cipherText }; } async function decrypt(sharedSecret, { iv, cipherText }) { const plainText = await crypto.subtle.decrypt({ name: 'AES-GCM', iv, }, sharedSecret, cipherText); return new TextDecoder().decode(plainText); } function getFormat(keyType) { switch (keyType) { case 'public': return 'spki'; case 'private': return 'pkcs8'; } } async function exportKeyToHexString(type, key) { const format = getFormat(type); const exported = await crypto.subtle.exportKey(format, key); return uint8ArrayToHex(new Uint8Array(exported)); } async function importKeyFromHexString(type, hexString) { const format = getFormat(type); const arrayBuffer = hexStringToUint8Array(hexString).buffer; return await crypto.subtle.importKey(format, new Uint8Array(arrayBuffer), { name: 'ECDH', namedCurve: 'P-256', }, true, type === 'private' ? ['deriveKey'] : []); } async function encryptContent(content, sharedSecret) { const serialized = JSON.stringify(content, (_, value) => { if (!(value instanceof Error)) return value; const error = value; return Object.assign(Object.assign({}, (error.code ? { code: error.code } : {})), { message: error.message }); }); return encrypt(sharedSecret, serialized); } async function decryptContent(encryptedData, sharedSecret) { return JSON.parse(await decrypt(sharedSecret, encryptedData)); }const OWN_PRIVATE_KEY = { storageKey: 'ownPrivateKey', keyType: 'private', }; const OWN_PUBLIC_KEY = { storageKey: 'ownPublicKey', keyType: 'public', }; const PEER_PUBLIC_KEY = { storageKey: 'peerPublicKey', keyType: 'public', }; class SCWKeyManager { constructor() { this.storage = new ScopedLocalStorage('CBWSDK', 'SCWKeyManager'); this.ownPrivateKey = null; this.ownPublicKey = null; this.peerPublicKey = null; this.sharedSecret = null; } async getOwnPublicKey() { await this.loadKeysIfNeeded(); return this.ownPublicKey; } // returns null if the shared secret is not yet derived async getSharedSecret() { await this.loadKeysIfNeeded(); return this.sharedSecret; } async setPeerPublicKey(key) { this.sharedSecret = null; this.peerPublicKey = key; await this.storeKey(PEER_PUBLIC_KEY, key); await this.loadKeysIfNeeded(); } async clear() { this.ownPrivateKey = null; this.ownPublicKey = null; this.peerPublicKey = null; this.sharedSecret = null; this.storage.removeItem(OWN_PUBLIC_KEY.storageKey); this.storage.removeItem(OWN_PRIVATE_KEY.storageKey); this.storage.removeItem(PEER_PUBLIC_KEY.storageKey); } async generateKeyPair() { const newKeyPair = await generateKeyPair(); this.ownPrivateKey = newKeyPair.privateKey; this.ownPublicKey = newKeyPair.publicKey; await this.storeKey(OWN_PRIVATE_KEY, newKeyPair.privateKey); await this.storeKey(OWN_PUBLIC_KEY, newKeyPair.publicKey); } async loadKeysIfNeeded() { if (this.ownPrivateKey === null) { this.ownPrivateKey = await this.loadKey(OWN_PRIVATE_KEY); } if (this.ownPublicKey === null) { this.ownPublicKey = await this.loadKey(OWN_PUBLIC_KEY); } if (this.ownPrivateKey === null || this.ownPublicKey === null) { await this.generateKeyPair(); } if (this.peerPublicKey === null) { this.peerPublicKey = await this.loadKey(PEER_PUBLIC_KEY); } if (this.sharedSecret === null) { if (this.ownPrivateKey === null || this.peerPublicKey === null) return; this.sharedSecret = await deriveSharedSecret(this.ownPrivateKey, this.peerPublicKey); } } // storage methods async loadKey(item) { const key = this.storage.getItem(item.storageKey); if (!key) return null; return importKeyFromHexString(item.keyType, key); } async storeKey(item, key) { const hexString = await exportKeyToHexString(item.keyType, key); this.storage.setItem(item.storageKey, hexString); } }const VERSION = '4.3.0'; const NAME = '@coinbase/wallet-sdk';async function fetchRPCRequest(request, rpcUrl) { const requestBody = Object.assign(Object.assign({}, request), { jsonrpc: '2.0', id: crypto.randomUUID() }); const res = await window.fetch(rpcUrl, { method: 'POST', body: JSON.stringify(requestBody), mode: 'cors', headers: { 'Content-Type': 'application/json', 'X-Cbw-Sdk-Version': VERSION, 'X-Cbw-Sdk-Platform': NAME, }, }); const { result, error } = await res.json(); if (error) throw error; return result; } function getCoinbaseInjectedLegacyProvider() { const window = globalThis; return window.coinbaseWalletExtension; } function getInjectedEthereum() { var _a, _b; try { const window = globalThis; return (_a = window.ethereum) !== null && _a !== void 0 ? _a : (_b = window.top) === null || _b === void 0 ? void 0 : _b.ethereum; } catch (_c) { return undefined; } } function getCoinbaseInjectedProvider({ metadata, preference, }) { var _a, _b; const { appName, appLogoUrl, appChainIds } = metadata; if (preference.options !== 'smartWalletOnly') { const extension = getCoinbaseInjectedLegacyProvider(); if (extension) { (_a = extension.setAppInfo) === null || _a === void 0 ? void 0 : _a.call(extension, appName, appLogoUrl, appChainIds, preference); return extension; } } const ethereum = getInjectedEthereum(); if (ethereum === null || ethereum === void 0 ? void 0 : ethereum.isCoinbaseBrowser) { (_b = ethereum.setAppInfo) === null || _b === void 0 ? void 0 : _b.call(ethereum, appName, appLogoUrl, appChainIds, preference); return ethereum; } return undefined; } /** * Validates the arguments for an invalid request and returns an error if any validation fails. * Valid request args are defined here: https://eips.ethereum.org/EIPS/eip-1193#request * @param args The request arguments to validate. * @returns An error object if the arguments are invalid, otherwise undefined. */ function checkErrorForInvalidRequestArgs(args) { if (!args || typeof args !== 'object' || Array.isArray(args)) { throw standardErrors.rpc.invalidParams({ message: 'Expected a single, non-array, object argument.', data: args, }); } const { method, params } = args; if (typeof method !== 'string' || method.length === 0) { throw standardErrors.rpc.invalidParams({ message: "'args.method' must be a non-empty string.", data: args, }); } if (params !== undefined && !Array.isArray(params) && (typeof params !== 'object' || params === null)) { throw standardErrors.rpc.invalidParams({ message: "'args.params' must be an object or array if provided.", data: args, }); } switch (method) { case 'eth_sign': case 'eth_signTypedData_v2': case 'eth_subscribe': case 'eth_unsubscribe': throw standardErrors.provider.unsupportedMethod(); } }const ACCOUNTS_KEY = 'accounts'; const ACTIVE_CHAIN_STORAGE_KEY = 'activeChain'; const AVAILABLE_CHAINS_STORAGE_KEY = 'availableChains'; const WALLET_CAPABILITIES_STORAGE_KEY = 'walletCapabilities'; class SCWSigner { constructor(params) { var _a, _b, _c; this.metadata = params.metadata; this.communicator = params.communicator; this.callback = params.callback; this.keyManager = new SCWKeyManager(); this.storage = new ScopedLocalStorage('CBWSDK', 'SCWStateManager'); this.accounts = (_a = this.storage.loadObject(ACCOUNTS_KEY)) !== null && _a !== void 0 ? _a : []; this.chain = this.storage.loadObject(ACTIVE_CHAIN_STORAGE_KEY) || { id: (_c = (_b = params.metadata.appChainIds) === null || _b === void 0 ? void 0 : _b[0]) !== null && _c !== void 0 ? _c : 1, }; this.handshake = this.handshake.bind(this); this.request = this.request.bind(this); this.createRequestMessage = this.createRequestMessage.bind(this); this.decryptResponseMessage = this.decryptResponseMessage.bind(this); } async handshake(args) { var _a, _b, _c, _d; // Open the popup before constructing the request message. // This is to ensure that the popup is not blocked by some browsers (i.e. Safari) await ((_b = (_a = this.communicator).waitForPopupLoaded) === null || _b === void 0 ? void 0 : _b.call(_a)); const handshakeMessage = await this.createRequestMessage({ handshake: { method: args.method, params: Object.assign({}, this.metadata, (_c = args.params) !== null && _c !== void 0 ? _c : {}), }, }); const response = await this.communicator.postRequestAndWaitForResponse(handshakeMessage); // store peer's public key if ('failure' in response.content) throw response.content.failure; const peerPublicKey = await importKeyFromHexString('public', response.sender); await this.keyManager.setPeerPublicKey(peerPublicKey); const decrypted = await this.decryptResponseMessage(response); const result = decrypted.result; if ('error' in result) throw result.error; switch (args.method) { case 'eth_requestAccounts': { const accounts = result.value; this.accounts = accounts; this.storage.storeObject(ACCOUNTS_KEY, accounts); (_d = this.callback) === null || _d === void 0 ? void 0 : _d.call(this, 'accountsChanged', accounts); break; } } } async request(request) { var _a; if (this.accounts.length === 0) { switch (request.method) { case 'wallet_sendCalls': return this.sendRequestToPopup(request); default: throw standardErrors.provider.unauthorized(); } } switch (request.method) { case 'eth_requestAccounts': (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this, 'connect', { chainId: hexStringFromNumber(this.chain.id) }); return this.accounts; case 'eth_accounts': return this.accounts; case 'eth_coinbase': return this.accounts[0]; case 'net_version': return this.chain.id; case 'eth_chainId': return hexStringFromNumber(this.chain.id); case 'wallet_getCapabilities': return this.storage.loadObject(WALLET_CAPABILITIES_STORAGE_KEY); case 'wallet_switchEthereumChain': return this.handleSwitchChainRequest(request); case 'eth_ecRecover': case 'personal_sign': case 'wallet_sign': case 'personal_ecRecover': case 'eth_signTransaction': case 'eth_sendTransaction': case 'eth_signTypedData_v1': case 'eth_signTypedData_v3': case 'eth_signTypedData_v4': case 'eth_signTypedData': case 'wallet_addEthereumChain': case 'wallet_watchAsset': case 'wallet_sendCalls': case 'wallet_showCallsStatus': case 'wallet_grantPermissions': return this.sendRequestToPopup(request); default: if (!this.chain.rpcUrl) throw standardErrors.rpc.internal('No RPC URL set for chain'); return fetchRPCRequest(request, this.chain.rpcUrl); } } async sendRequestToPopup(request) { var _a, _b; // Open the popup before constructing the request message. // This is to ensure that the popup is not blocked by some browsers (i.e. Safari) await ((_b = (_a = this.communicator).waitForPopupLoaded) === null || _b === void 0 ? void 0 : _b.call(_a)); const response = await this.sendEncryptedRequest(request); const decrypted = await this.decryptResponseMessage(response); const result = decrypted.result; if ('error' in result) throw result.error; return result.value; } async cleanup() { var _a, _b; this.storage.clear(); await this.keyManager.clear(); this.accounts = []; this.chain = { id: (_b = (_a = this.metadata.appChainIds) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : 1, }; } /** * @returns `null` if the request was successful. * https://eips.ethereum.org/EIPS/eip-3326#wallet_switchethereumchain */ async handleSwitchChainRequest(request) { var _a; const params = request.params; if (!params || !((_a = params[0]) === null || _a === void 0 ? void 0 : _a.chainId)) { throw standardErrors.rpc.invalidParams(); } const chainId = ensureIntNumber(params[0].chainId); const localResult = this.updateChain(chainId); if (localResult) return null; const popupResult = await this.sendRequestToPopup(request); if (popupResult === null) { this.updateChain(chainId); } return popupResult; } async sendEncryptedRequest(request) { const sharedSecret = await this.keyManager.getSharedSecret(); if (!sharedSecret) { throw standardErrors.provider.unauthorized('No valid session found, try requestAccounts before other methods'); } const encrypted = await encryptContent({ action: request, chainId: this.chain.id, }, sharedSecret); const message = await this.createRequestMessage({ encrypted }); return this.communicator.postRequestAndWaitForResponse(message); } async createRequestMessage(content) { const publicKey = await exportKeyToHexString('public', await this.keyManager.getOwnPublicKey()); return { id: crypto.randomUUID(), sender: publicKey, content, timestamp: new Date(), }; } async decryptResponseMessage(message) { var _a, _b; const content = message.content; // throw protocol level error if ('failure' in content) { throw content.failure; } const sharedSecret = await this.keyManager.getSharedSecret(); if (!sharedSecret) { throw standardErrors.provider.unauthorized('Invalid session'); } const response = await decryptContent(content.encrypted, sharedSecret); const availableChains = (_a = response.data) === null || _a === void 0 ? void 0 : _a.chains; if (availableChains) { const chains = Object.entries(availableChains).map(([id, rpcUrl]) => ({ id: Number(id), rpcUrl, })); this.storage.storeObject(AVAILABLE_CHAINS_STORAGE_KEY, chains); this.updateChain(this.chain.id, chains); } const walletCapabilities = (_b = response.data) === null || _b === void 0 ? void 0 : _b.capabilities; if (walletCapabilities) { this.storage.storeObject(WALLET_CAPABILITIES_STORAGE_KEY, walletCapabilities); } return response; } updateChain(chainId, newAvailableChains) { var _a; const chains = newAvailableChains !== null && newAvailableChains !== void 0 ? newAvailableChains : this.storage.loadObject(AVAILABLE_CHAINS_STORAGE_KEY); const chain = chains === null || chains === void 0 ? void 0 : chains.find((chain) => chain.id === chainId); if (!chain) return false; if (chain !== this.chain) { this.chain = chain; this.storage.storeObject(ACTIVE_CHAIN_STORAGE_KEY, chain); (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this, 'chainChanged', hexStringFromNumber(chain.id)); } return true; } }var sha3 = {};var _assert = {};var hasRequired_assert; function require_assert () { if (hasRequired_assert) return _assert; hasRequired_assert = 1; /** * Internal assertion helpers. * @module */ Object.defineProperty(_assert, "__esModule", { value: true }); _assert.anumber = anumber; _assert.abytes = abytes; _assert.ahash = ahash; _assert.aexists = aexists; _assert.aoutput = aoutput; /** Asserts something is positive integer. */ function anumber(n) { if (!Number.isSafeInteger(n) || n < 0) throw new Error('positive integer expected, got ' + n); } /** Is number an Uint8Array? Copied from utils for perf. */ function isBytes(a) { return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array'); } /** Asserts something is Uint8Array. */ function abytes(b, ...lengths) { if (!isBytes(b)) throw new Error('Uint8Array expected'); if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length); } /** Asserts something is hash */ function ahash(h) { if (typeof h !== 'function' || typeof h.create !== 'function') throw new Error('Hash should be wrapped by utils.wrapConstructor'); anumber(h.outputLen); anumber(h.blockLen); } /** Asserts a hash instance has not been destroyed / finished */ function aexists(instance, checkFinished = true) { if (instance.destroyed) throw new Error('Hash instance has been destroyed'); if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); } /** Asserts output is properly-sized byte array */ function aoutput(out, instance) { abytes(out); const min = instance.outputLen; if (out.length < min) { throw new Error('digestInto() expects output buffer of length at least ' + min); } } return _assert; }var _u64 = {};var hasRequired_u64; function require_u64 () { if (hasRequired_u64) return _u64; hasRequired_u64 = 1; Object.defineProperty(_u64, "__esModule", { value: true }); _u64.add5L = _u64.add5H = _u64.add4H = _u64.add4L = _u64.add3H = _u64.add3L = _u64.rotlBL = _u64.rotlBH = _u64.rotlSL = _u64.rotlSH = _u64.rotr32L = _u64.rotr32H = _u64.rotrBL = _u64.rotrBH = _u64.rotrSL = _u64.rotrSH = _u64.shrSL = _u64.shrSH = _u64.toBig = void 0; _u64.fromBig = fromBig; _u64.split = split; _u64.add = add; /** * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array. * @todo re-check https://issues.chromium.org/issues/42212588 * @module */ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); const _32n = /* @__PURE__ */ BigInt(32); function fromBig(n, le = false) { if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; } function split(lst, le = false) { let Ah = new Uint32Array(lst.length); let Al = new Uint32Array(lst.length); for (let i = 0; i < lst.length; i++) { const { h, l } = fromBig(lst[i], le); [Ah[i], Al[i]] = [h, l]; } return [Ah, Al]; } const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); _u64.toBig = toBig; // for Shift in [0, 32) const shrSH = (h, _l, s) => h >>> s; _u64.shrSH = shrSH; const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); _u64.shrSL = shrSL; // Right rotate for Shift in [1, 32) const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); _u64.rotrSH = rotrSH; const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); _u64.rotrSL = rotrSL; // Right rotate for Shift in (32, 64), NOTE: 32 is special case. const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); _u64.rotrBH = rotrBH; const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); _u64.rotrBL = rotrBL; // Right rotate for shift===32 (just swaps l&h) const rotr32H = (_h, l) => l; _u64.rotr32H = rotr32H; const rotr32L = (h, _l) => h; _u64.rotr32L = rotr32L; // Left rotate for Shift in [1, 32) const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); _u64.rotlSH = rotlSH; const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); _u64.rotlSL = rotlSL; // Left rotate for Shift in (32, 64), NOTE: 32 is special case. const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); _u64.rotlBH = rotlBH; const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); _u64.rotlBL = rotlBL; // JS uses 32-bit signed integers for bitwise operations which means we cannot // simple take carry out of low bit sum by shift, we need to use division. function add(Ah, Al, Bh, Bl) { const l = (Al >>> 0) + (Bl >>> 0); return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; } // Addition with more than 2 elements const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); _u64.add3L = add3L; const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; _u64.add3H = add3H; const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); _u64.add4L = add4L;