signet.js 0.0.2 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.json +55 -0
- package/.prettierrc +1 -0
- package/babel.config.js +6 -0
- package/docs/pages/index.mdx +36 -0
- package/docs/pages/signetjs/advanced/chain-signatures-contract.mdx +52 -0
- package/docs/pages/signetjs/advanced/chain.mdx +45 -0
- package/docs/pages/signetjs/chains/bitcoin/bitcoin.mdx +171 -0
- package/docs/pages/signetjs/chains/bitcoin/btc-rpc-adapter.mdx +26 -0
- package/docs/pages/signetjs/chains/cosmos.mdx +171 -0
- package/docs/pages/signetjs/chains/evm.mdx +319 -0
- package/docs/pages/signetjs/contract-addresses.mdx +27 -0
- package/docs/pages/signetjs/index.mdx +88 -0
- package/docs/snippets/code/contract.ts +21 -0
- package/docs/snippets/code/evm/env.ts +16 -0
- package/docs/snippets/code/near/env.ts +13 -0
- package/hardhat.config.mts +19 -0
- package/package.json +1 -1
- package/src/chains/Bitcoin/BTCRpcAdapter/BTCRpcAdapter.ts +11 -0
- package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/Mempool.ts +96 -0
- package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/index.ts +1 -0
- package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/types.ts +72 -0
- package/src/chains/Bitcoin/BTCRpcAdapter/index.ts +6 -0
- package/src/chains/Bitcoin/Bitcoin.ts +287 -0
- package/src/chains/Bitcoin/types.ts +48 -0
- package/src/chains/Bitcoin/utils.ts +14 -0
- package/src/chains/Chain.ts +92 -0
- package/src/chains/ChainSignatureContract.ts +65 -0
- package/src/chains/Cosmos/Cosmos.ts +258 -0
- package/src/chains/Cosmos/types.ts +35 -0
- package/src/chains/Cosmos/utils.ts +45 -0
- package/src/chains/EVM/EVM.test.ts +238 -0
- package/src/chains/EVM/EVM.ts +334 -0
- package/src/chains/EVM/types.ts +53 -0
- package/src/chains/EVM/utils.ts +27 -0
- package/src/chains/index.ts +38 -0
- package/src/chains/types.ts +46 -0
- package/src/index.ts +2 -0
- package/src/utils/chains/evm/ChainSignaturesContract.ts +286 -0
- package/src/utils/chains/evm/ChainSignaturesContractABI.ts +359 -0
- package/src/utils/chains/evm/errors.ts +52 -0
- package/src/utils/chains/evm/index.ts +3 -0
- package/src/utils/chains/evm/types.ts +28 -0
- package/src/utils/chains/evm/utils.ts +11 -0
- package/src/utils/chains/index.ts +2 -0
- package/src/utils/chains/near/ChainSignatureContract.ts +155 -0
- package/src/utils/chains/near/account.ts +42 -0
- package/src/utils/chains/near/constants.ts +4 -0
- package/src/utils/chains/near/index.ts +3 -0
- package/src/utils/chains/near/signAndSend/index.ts +1 -0
- package/src/utils/chains/near/signAndSend/keypair.ts +178 -0
- package/src/utils/chains/near/transactionBuilder.ts +73 -0
- package/src/utils/chains/near/types.ts +77 -0
- package/src/utils/constants.ts +62 -0
- package/src/utils/cryptography.ts +131 -0
- package/src/utils/index.ts +3 -0
- package/src/utils/publicKey.ts +23 -0
- package/tsconfig.eslint.json +8 -0
- package/tsconfig.json +122 -0
- package/tsup.config.ts +55 -0
- package/vitest.config.ts +16 -0
- package/vocs.config.ts +73 -0
- package/browser/index.browser.cjs +0 -3
- package/browser/index.browser.cjs.map +0 -1
- package/browser/index.browser.js +0 -3
- package/browser/index.browser.js.map +0 -1
- package/node/index.node.cjs +0 -3
- package/node/index.node.cjs.map +0 -1
- package/node/index.node.js +0 -3
- package/node/index.node.js.map +0 -1
- package/types/index.d.cts +0 -919
- package/types/index.d.ts +0 -919
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { base58 } from '@scure/base'
|
|
2
|
+
import { ec as EC } from 'elliptic'
|
|
3
|
+
import { keccak256 } from 'viem'
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
type NajPublicKey,
|
|
7
|
+
type MPCSignature,
|
|
8
|
+
type RSVSignature,
|
|
9
|
+
type UncompressedPubKeySEC1,
|
|
10
|
+
} from '@chains/types'
|
|
11
|
+
|
|
12
|
+
export const toRSV = (signature: MPCSignature): RSVSignature => {
|
|
13
|
+
// Handle NearNearMpcSignature
|
|
14
|
+
if (
|
|
15
|
+
'big_r' in signature &&
|
|
16
|
+
typeof signature.big_r === 'object' &&
|
|
17
|
+
'affine_point' in signature.big_r &&
|
|
18
|
+
's' in signature &&
|
|
19
|
+
typeof signature.s === 'object' &&
|
|
20
|
+
'scalar' in signature.s
|
|
21
|
+
) {
|
|
22
|
+
return {
|
|
23
|
+
r: signature.big_r.affine_point.substring(2),
|
|
24
|
+
s: signature.s.scalar,
|
|
25
|
+
v: signature.recovery_id + 27,
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
// Handle SigNetNearMpcSignature
|
|
29
|
+
else if (
|
|
30
|
+
'big_r' in signature &&
|
|
31
|
+
typeof signature.big_r === 'string' &&
|
|
32
|
+
's' in signature &&
|
|
33
|
+
typeof signature.s === 'string'
|
|
34
|
+
) {
|
|
35
|
+
return {
|
|
36
|
+
r: signature.big_r.substring(2),
|
|
37
|
+
s: signature.s,
|
|
38
|
+
v: signature.recovery_id + 27,
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
// Handle SigNetEvmMpcSignature
|
|
42
|
+
else if (
|
|
43
|
+
'bigR' in signature &&
|
|
44
|
+
'x' in signature.bigR &&
|
|
45
|
+
's' in signature &&
|
|
46
|
+
typeof signature.s === 'bigint'
|
|
47
|
+
) {
|
|
48
|
+
return {
|
|
49
|
+
r: signature.bigR.x.toString(16).padStart(64, '0'),
|
|
50
|
+
s: signature.s.toString(16).padStart(64, '0'),
|
|
51
|
+
v: signature.recoveryId + 27,
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
throw new Error('Invalid signature format')
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Compresses an uncompressed public key to its compressed format following SEC1 standards.
|
|
60
|
+
* In SEC1, a compressed public key consists of a prefix (02 or 03) followed by the x-coordinate.
|
|
61
|
+
* The prefix indicates whether the y-coordinate is even (02) or odd (03).
|
|
62
|
+
*
|
|
63
|
+
* @param uncompressedPubKeySEC1 - The uncompressed public key in hex format, with or without '04' prefix
|
|
64
|
+
* @returns The compressed public key in hex format
|
|
65
|
+
* @throws Error if the uncompressed public key length is invalid
|
|
66
|
+
*/
|
|
67
|
+
export const compressPubKey = (
|
|
68
|
+
uncompressedPubKeySEC1: UncompressedPubKeySEC1
|
|
69
|
+
): string => {
|
|
70
|
+
const slicedPubKey = uncompressedPubKeySEC1.slice(2)
|
|
71
|
+
|
|
72
|
+
if (slicedPubKey.length !== 128) {
|
|
73
|
+
throw new Error('Invalid uncompressed public key length')
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const x = slicedPubKey.slice(0, 64)
|
|
77
|
+
const y = slicedPubKey.slice(64)
|
|
78
|
+
|
|
79
|
+
const isEven = parseInt(y.slice(-1), 16) % 2 === 0
|
|
80
|
+
const prefix = isEven ? '02' : '03'
|
|
81
|
+
|
|
82
|
+
return prefix + x
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Converts a NAJ public key to an uncompressed SEC1 public key.
|
|
87
|
+
*
|
|
88
|
+
* @param najPublicKey - The NAJ public key to convert (e.g. secp256k1:3Ww8iFjqTHufye5aRGUvrQqETegR4gVUcW8FX5xzscaN9ENhpkffojsxJwi6N1RbbHMTxYa9UyKeqK3fsMuwxjR5)
|
|
89
|
+
* @returns The uncompressed SEC1 public key (e.g. 04 || x || y)
|
|
90
|
+
*/
|
|
91
|
+
export const najToUncompressedPubKeySEC1 = (
|
|
92
|
+
najPublicKey: NajPublicKey
|
|
93
|
+
): UncompressedPubKeySEC1 => {
|
|
94
|
+
const decodedKey = base58.decode(najPublicKey.split(':')[1])
|
|
95
|
+
return `04${Buffer.from(decodedKey).toString('hex')}`
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Derives a child public key from a parent public key using the sig.network v1.0.0 epsilon derivation scheme.
|
|
100
|
+
* The parent public keys are defined in @constants.ts
|
|
101
|
+
*
|
|
102
|
+
* @param najPublicKey - The parent public key in uncompressed SEC1 format (e.g. 04 || x || y)
|
|
103
|
+
* @param predecessorId - The predecessor ID is the address of the account calling the signer contract (e.g EOA or Contract Address)
|
|
104
|
+
* @param path - Optional derivation path suffix (defaults to empty string)
|
|
105
|
+
* @returns The derived child public key in uncompressed SEC1 format (04 || x || y)
|
|
106
|
+
*/
|
|
107
|
+
export function deriveChildPublicKey(
|
|
108
|
+
rootUncompressedPubKeySEC1: UncompressedPubKeySEC1,
|
|
109
|
+
predecessorId: string,
|
|
110
|
+
path: string = '',
|
|
111
|
+
chainId: string
|
|
112
|
+
): UncompressedPubKeySEC1 {
|
|
113
|
+
const ec = new EC('secp256k1')
|
|
114
|
+
|
|
115
|
+
const EPSILON_DERIVATION_PREFIX = 'sig.network v1.0.0 epsilon derivation'
|
|
116
|
+
const derivationPath = `${EPSILON_DERIVATION_PREFIX},${chainId},${predecessorId},${path}`
|
|
117
|
+
|
|
118
|
+
const scalarHex = keccak256(Buffer.from(derivationPath)).slice(2)
|
|
119
|
+
|
|
120
|
+
const x = rootUncompressedPubKeySEC1.substring(2, 66)
|
|
121
|
+
const y = rootUncompressedPubKeySEC1.substring(66)
|
|
122
|
+
|
|
123
|
+
const oldPublicKeyPoint = ec.curve.point(x, y)
|
|
124
|
+
const scalarTimesG = ec.g.mul(scalarHex)
|
|
125
|
+
const newPublicKeyPoint = oldPublicKeyPoint.add(scalarTimesG)
|
|
126
|
+
|
|
127
|
+
const newX = newPublicKeyPoint.getX().toString('hex').padStart(64, '0')
|
|
128
|
+
const newY = newPublicKeyPoint.getY().toString('hex').padStart(64, '0')
|
|
129
|
+
|
|
130
|
+
return `04${newX}${newY}`
|
|
131
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { NajPublicKey } from '@chains/types'
|
|
2
|
+
import {
|
|
3
|
+
CONTRACT_ADDRESSES,
|
|
4
|
+
ROOT_PUBLIC_KEYS,
|
|
5
|
+
type CHAINS,
|
|
6
|
+
} from '@utils/constants'
|
|
7
|
+
|
|
8
|
+
export const getRootPublicKey = (
|
|
9
|
+
contractAddress: string,
|
|
10
|
+
chain: keyof typeof CHAINS
|
|
11
|
+
): NajPublicKey => {
|
|
12
|
+
const environment = Object.entries(CONTRACT_ADDRESSES[chain]).find(
|
|
13
|
+
([_, address]) => address.toLowerCase() === contractAddress.toLowerCase()
|
|
14
|
+
)?.[0] as keyof typeof ROOT_PUBLIC_KEYS | undefined
|
|
15
|
+
|
|
16
|
+
if (environment) {
|
|
17
|
+
return ROOT_PUBLIC_KEYS[environment]
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
throw new Error(
|
|
21
|
+
`Contract address ${contractAddress} not supported for chain ${chain}`
|
|
22
|
+
)
|
|
23
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
/* Visit https://aka.ms/tsconfig to read more about this file */
|
|
4
|
+
|
|
5
|
+
/* Projects */
|
|
6
|
+
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
|
7
|
+
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
|
8
|
+
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
|
9
|
+
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
|
10
|
+
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
|
11
|
+
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
|
12
|
+
|
|
13
|
+
/* Language and Environment */
|
|
14
|
+
"target": "ES2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
|
|
15
|
+
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
|
16
|
+
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
|
17
|
+
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
|
18
|
+
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
|
19
|
+
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
|
20
|
+
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
|
21
|
+
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
|
22
|
+
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
|
23
|
+
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
|
24
|
+
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
|
25
|
+
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
|
26
|
+
|
|
27
|
+
/* Modules */
|
|
28
|
+
"module": "ESNext" /* Specify what module code is generated. */,
|
|
29
|
+
// "rootDir": "./", /* Specify the root folder within your source files. */
|
|
30
|
+
"moduleResolution": "bundler" /* Specify how TypeScript looks up a file from a given module specifier. */,
|
|
31
|
+
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
|
32
|
+
"paths": {
|
|
33
|
+
"@chains": ["./src/chains/index.ts"],
|
|
34
|
+
"@utils": ["./src/utils/index.ts"],
|
|
35
|
+
"@chains/*": ["./src/chains/*"],
|
|
36
|
+
"@utils/*": ["./src/utils/*"]
|
|
37
|
+
} /* Specify a set of entries that re-map imports to additional lookup locations. */,
|
|
38
|
+
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
|
39
|
+
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
|
40
|
+
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
|
41
|
+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
|
42
|
+
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
|
43
|
+
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
|
44
|
+
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
|
45
|
+
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
|
46
|
+
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
|
47
|
+
"resolveJsonModule": true /* Enable importing .json files. */,
|
|
48
|
+
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
|
49
|
+
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
|
50
|
+
|
|
51
|
+
/* JavaScript Support */
|
|
52
|
+
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
|
53
|
+
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
|
54
|
+
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
|
55
|
+
|
|
56
|
+
/* Emit */
|
|
57
|
+
"declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
|
|
58
|
+
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
|
59
|
+
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
|
60
|
+
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
|
61
|
+
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
|
62
|
+
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
|
63
|
+
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
|
|
64
|
+
// "removeComments": true, /* Disable emitting comments. */
|
|
65
|
+
// "noEmit": true, /* Disable emitting files from a compilation. */
|
|
66
|
+
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
|
67
|
+
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
|
68
|
+
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
|
69
|
+
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
|
70
|
+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
|
71
|
+
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
|
72
|
+
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
|
73
|
+
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
|
74
|
+
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
|
75
|
+
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
|
76
|
+
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
|
77
|
+
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
|
78
|
+
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
|
79
|
+
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
|
80
|
+
|
|
81
|
+
/* Interop Constraints */
|
|
82
|
+
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
|
83
|
+
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
|
84
|
+
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
|
85
|
+
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
|
|
86
|
+
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
|
87
|
+
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
|
|
88
|
+
|
|
89
|
+
/* Type Checking */
|
|
90
|
+
"strict": true /* Enable all strict type-checking options. */,
|
|
91
|
+
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
|
92
|
+
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
|
93
|
+
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
|
94
|
+
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
|
95
|
+
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
|
96
|
+
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
|
97
|
+
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
|
98
|
+
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
|
99
|
+
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
|
100
|
+
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
|
101
|
+
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
|
102
|
+
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
|
103
|
+
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
|
104
|
+
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
|
105
|
+
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
|
106
|
+
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
|
107
|
+
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
|
108
|
+
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
|
109
|
+
|
|
110
|
+
/* Completeness */
|
|
111
|
+
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
|
112
|
+
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
|
113
|
+
},
|
|
114
|
+
"include": [
|
|
115
|
+
"src/**/*.ts",
|
|
116
|
+
"src/**/*.d.ts",
|
|
117
|
+
"hardhat.config.mts",
|
|
118
|
+
"vitest.config.ts",
|
|
119
|
+
"tsup.config.ts"
|
|
120
|
+
],
|
|
121
|
+
"exclude": ["**/*.test.ts", "**/*.spec.ts", "node_modules", "dist"]
|
|
122
|
+
}
|
package/tsup.config.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { resolve } from 'path'
|
|
2
|
+
|
|
3
|
+
import { defineConfig } from 'tsup'
|
|
4
|
+
import type { Options } from 'tsup'
|
|
5
|
+
|
|
6
|
+
export default defineConfig((options) => {
|
|
7
|
+
const isNode = options.env?.TARGET === 'node'
|
|
8
|
+
const isBrowser = options.env?.TARGET === 'browser'
|
|
9
|
+
|
|
10
|
+
if (!isNode && !isBrowser) {
|
|
11
|
+
throw new Error(
|
|
12
|
+
'TARGET environment variable must be set to either "node" or "browser"'
|
|
13
|
+
)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const target = isNode ? 'node18' : 'esnext'
|
|
17
|
+
const platform = isNode ? 'node' : 'browser'
|
|
18
|
+
const outDir = `dist/${platform}`
|
|
19
|
+
|
|
20
|
+
const config: Options = {
|
|
21
|
+
entry: ['src/index.ts'],
|
|
22
|
+
format: ['esm', 'cjs'],
|
|
23
|
+
target,
|
|
24
|
+
platform,
|
|
25
|
+
outDir,
|
|
26
|
+
outExtension({ format }) {
|
|
27
|
+
return {
|
|
28
|
+
js: format === 'esm' ? `.${platform}.js` : `.${platform}.cjs`,
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
sourcemap: true,
|
|
32
|
+
minify: true,
|
|
33
|
+
clean: true,
|
|
34
|
+
dts: isNode,
|
|
35
|
+
external: isNode
|
|
36
|
+
? ['path', 'fs', 'crypto', 'stream', 'util', 'events', 'buffer']
|
|
37
|
+
: ['crypto', 'stream', 'util', 'events', 'buffer'],
|
|
38
|
+
treeshake: true,
|
|
39
|
+
splitting: false,
|
|
40
|
+
esbuildOptions(options) {
|
|
41
|
+
options.conditions = isNode
|
|
42
|
+
? ['node', 'import', 'default']
|
|
43
|
+
: ['browser', 'import', 'default']
|
|
44
|
+
options.mainFields = isNode
|
|
45
|
+
? ['module', 'main']
|
|
46
|
+
: ['browser', 'module', 'main']
|
|
47
|
+
options.alias = {
|
|
48
|
+
'@chains': resolve(__dirname, './src/chains'),
|
|
49
|
+
'@utils': resolve(__dirname, './src/utils'),
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return config
|
|
55
|
+
})
|
package/vitest.config.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { resolve } from 'path'
|
|
2
|
+
|
|
3
|
+
import { defineConfig } from 'vitest/config'
|
|
4
|
+
|
|
5
|
+
export default defineConfig({
|
|
6
|
+
test: {
|
|
7
|
+
globals: true,
|
|
8
|
+
environment: 'node',
|
|
9
|
+
},
|
|
10
|
+
resolve: {
|
|
11
|
+
alias: {
|
|
12
|
+
'@chains': resolve(__dirname, './src/chains'),
|
|
13
|
+
'@utils': resolve(__dirname, './src/utils'),
|
|
14
|
+
},
|
|
15
|
+
},
|
|
16
|
+
})
|
package/vocs.config.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { defineConfig, type Config } from 'vocs'
|
|
2
|
+
|
|
3
|
+
export default defineConfig({
|
|
4
|
+
title: 'Sig Network',
|
|
5
|
+
description:
|
|
6
|
+
'Manage and use cryptographic key(s) across multiple chains or multiple contexts, with on-chain-enforced conditions',
|
|
7
|
+
twoslash: {
|
|
8
|
+
compilerOptions: {
|
|
9
|
+
strict: true,
|
|
10
|
+
paths: {
|
|
11
|
+
'signet.js': ['./src'],
|
|
12
|
+
'@chains': ['./src/chains'],
|
|
13
|
+
'@utils': ['./src/utils'],
|
|
14
|
+
'@chains/*': ['./src/chains/*'],
|
|
15
|
+
'@utils/*': ['./src/utils/*'],
|
|
16
|
+
},
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
sidebar: [
|
|
20
|
+
{
|
|
21
|
+
text: 'Chain Signatures',
|
|
22
|
+
items: [{ text: 'Introduction to Chain Signatures', link: '/' }],
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
text: 'Signet.js',
|
|
26
|
+
items: [
|
|
27
|
+
{ text: 'Quick Start', link: '/signetjs' },
|
|
28
|
+
{ text: 'Contract Addresses', link: '/signetjs/contract-addresses' },
|
|
29
|
+
{
|
|
30
|
+
text: 'Supported Chains',
|
|
31
|
+
items: [
|
|
32
|
+
{ text: 'EVM Chains', link: '/signetjs/chains/evm' },
|
|
33
|
+
{
|
|
34
|
+
text: 'Bitcoin',
|
|
35
|
+
items: [
|
|
36
|
+
{ text: 'Overview', link: '/signetjs/chains/bitcoin/bitcoin' },
|
|
37
|
+
{
|
|
38
|
+
text: 'RPC Adapter',
|
|
39
|
+
link: '/signetjs/chains/bitcoin/btc-rpc-adapter',
|
|
40
|
+
},
|
|
41
|
+
],
|
|
42
|
+
},
|
|
43
|
+
{ text: 'Cosmos', link: '/signetjs/chains/cosmos' },
|
|
44
|
+
],
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
text: 'Advanced',
|
|
48
|
+
items: [
|
|
49
|
+
{ text: 'Chain Interface', link: '/signetjs/advanced/chain' },
|
|
50
|
+
{
|
|
51
|
+
text: 'Chain Signatures Contract',
|
|
52
|
+
link: '/signetjs/advanced/chain-signatures-contract',
|
|
53
|
+
},
|
|
54
|
+
],
|
|
55
|
+
},
|
|
56
|
+
],
|
|
57
|
+
},
|
|
58
|
+
],
|
|
59
|
+
|
|
60
|
+
socials: [
|
|
61
|
+
{
|
|
62
|
+
icon: 'github',
|
|
63
|
+
link: 'https://github.com/sig-net',
|
|
64
|
+
},
|
|
65
|
+
],
|
|
66
|
+
|
|
67
|
+
theme: {
|
|
68
|
+
accentColor: {
|
|
69
|
+
light: '#00C08B',
|
|
70
|
+
dark: '#00E6A6',
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
}) as Config
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
'use strict';var xt=require('bn.js'),providers=require('near-api-js/lib/providers'),accounts=require('@near-js/accounts'),crypto=require('@near-js/crypto'),keystores=require('@near-js/keystores'),base=require('@scure/base'),elliptic=require('elliptic'),viem=require('viem'),f=require('bitcoinjs-lib'),qt=require('coinselect'),amino=require('@cosmjs/amino'),crypto$1=require('@cosmjs/crypto'),encoding=require('@cosmjs/encoding'),protoSigning=require('@cosmjs/proto-signing'),stargate=require('@cosmjs/stargate'),bech32=require('bech32'),signing=require('cosmjs-types/cosmos/tx/signing/v1beta1/signing'),tx=require('cosmjs-types/cosmos/tx/v1beta1/tx'),chainRegistry=require('chain-registry');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var xt__default=/*#__PURE__*/_interopDefault(xt);var f__namespace=/*#__PURE__*/_interopNamespace(f);var qt__default=/*#__PURE__*/_interopDefault(qt);var wt=Object.defineProperty;var m=(r,t)=>{for(var e in t)wt(r,e,{get:t[e],enumerable:true});};var bt={};m(bt,{chains:()=>it,constants:()=>nt,cryptography:()=>u});var it={};m(it,{evm:()=>st,near:()=>Q});var Q={};m(Q,{ChainSignatureContract:()=>l,signAndSend:()=>J,transactionBuilder:()=>G});var G={};m(G,{mpcPayloadsToChainSigTransaction:()=>Ft,responseToMpcSignature:()=>Ot});var z=class{},b=class extends z{};var D=new xt__default.default("300000000000000"),A="dontcare";var w=async({networkId:r,accountId:t=A,keypair:e=crypto.KeyPair.fromRandom("ed25519")})=>{let n=new keystores.InMemoryKeyStore;await n.setKey(r,t,e);let a=accounts.Connection.fromConfig({networkId:r,provider:{type:"JsonRpcProvider",args:{url:{testnet:"https://rpc.testnet.near.org",mainnet:"https://rpc.mainnet.near.org"}[r]}},signer:{type:"InMemorySigner",keyStore:n}});return new accounts.Account(a,t)};var u={};m(u,{compressPubKey:()=>Kt,deriveChildPublicKey:()=>Nt,najToUncompressedPubKeySEC1:()=>x,toRSV:()=>kt});var kt=r=>{if("big_r"in r&&typeof r.big_r=="object"&&"affine_point"in r.big_r&&"s"in r&&typeof r.s=="object"&&"scalar"in r.s)return {r:r.big_r.affine_point.substring(2),s:r.s.scalar,v:r.recovery_id+27};if("big_r"in r&&typeof r.big_r=="string"&&"s"in r&&typeof r.s=="string")return {r:r.big_r.substring(2),s:r.s,v:r.recovery_id+27};if("bigR"in r&&"x"in r.bigR&&"s"in r&&typeof r.s=="bigint")return {r:r.bigR.x.toString(16).padStart(64,"0"),s:r.s.toString(16).padStart(64,"0"),v:r.recoveryId+27};throw new Error("Invalid signature format")},Kt=r=>{let t=r.slice(2);if(t.length!==128)throw new Error("Invalid uncompressed public key length");let e=t.slice(0,64),n=t.slice(64);return (parseInt(n.slice(-1),16)%2===0?"02":"03")+e},x=r=>{let t=base.base58.decode(r.split(":")[1]);return `04${Buffer.from(t).toString("hex")}`};function Nt(r,t,e="",n){let a=new elliptic.ec("secp256k1"),i=`sig.network v1.0.0 epsilon derivation,${n},${t},${e}`,o=viem.keccak256(Buffer.from(i)).slice(2),c=r.substring(2,66),p=r.substring(66),y=a.curve.point(c,p),d=a.g.mul(o),V=y.add(d),M=V.getX().toString("hex").padStart(64,"0"),j=V.getY().toString("hex").padStart(64,"0");return `04${M}${j}`}var Mt=r=>{if(r===A)throw new Error("A valid account ID and keypair are required for change methods. Please instantiate a new contract with valid credentials.")},l=class extends b{constructor({networkId:t,contractId:e,accountId:n=A,keypair:a=crypto.KeyPair.fromRandom("ed25519")}){super(),this.networkId=t,this.contractId=e,this.accountId=n,this.keypair=a;}async getContract(){let t=await w({networkId:this.networkId,accountId:this.accountId,keypair:this.keypair});return new accounts.Contract(t,this.contractId,{viewMethods:["public_key","experimental_signature_deposit","derived_public_key"],changeMethods:["sign"],useLocalViewExecution:false})}async getCurrentSignatureDeposit(){let t=await this.getContract();return new xt__default.default((await t.experimental_signature_deposit()).toLocaleString("fullwide",{useGrouping:false}))}async getDerivedPublicKey(t){let n=await(await this.getContract()).derived_public_key(t);return x(n)}async getPublicKey(){let e=await(await this.getContract()).public_key();return x(e)}async sign(t){Mt(this.accountId);let e=await this.getContract(),n=await this.getCurrentSignatureDeposit(),a=await e.sign({args:{request:t},gas:D,amount:n});return u.toRSV(a)}};var Ft=async({networkId:r,contractId:t,hashesToSign:e,path:n})=>{let s=await new l({networkId:r,contractId:t}).getCurrentSignatureDeposit();return {receiverId:t,actions:e.map(i=>({type:"FunctionCall",params:{methodName:"sign",args:{request:{payload:Array.from(i),path:n,key_version:0}},gas:D.div(new xt__default.default(e.length)).toString(),deposit:s?.toString()||"1"}}))}},Ot=({response:r})=>{let t=providers.getTransactionLastResult(r);if(t)return u.toRSV(t)};var J={};m(J,{keypair:()=>Y});var Y={};m(Y,{BTCTransaction:()=>ue,CosmosTransaction:()=>de,EVMTransaction:()=>pe});var h=class{};async function L(r,t){let[e,n]=await Promise.all([r.estimateGas(t),r.estimateFeesPerGas()]),a=n.maxFeePerGas??BigInt(1e10),s=n.maxPriorityFeePerGas??BigInt(1e10);return {gas:e,maxFeePerGas:a,maxPriorityFeePerGas:s}}var B=class extends h{constructor({rpcUrl:t,contract:e}){super(),this.contract=e,this.client=viem.createPublicClient({transport:viem.http(t)});}async attachGasAndNonce(t){let e=await L(this.client,t),n=await this.client.getTransactionCount({address:t.from}),{from:a,...s}=t;return {...e,nonce:n,chainId:Number(await this.client.getChainId()),type:"eip1559",...s}}transformRSVSignature(t){return {r:`0x${t.r}`,s:`0x${t.s}`,yParity:t.v-27}}assembleSignature(t){let{r:e,s:n,yParity:a}=this.transformRSVSignature(t);if(a===void 0)throw new Error("Missing yParity");return viem.concatHex([e,n,viem.numberToHex(a+27,{size:1})])}async deriveAddressAndPublicKey(t,e){let n=await this.contract.getDerivedPublicKey({path:e,predecessor:t});if(!n)throw new Error("Failed to get derived public key");let a=n.startsWith("04")?n.slice(2):n,s=viem.keccak256(Buffer.from(a,"hex"));return {address:viem.getAddress(`0x${s.slice(-40)}`),publicKey:n}}async getBalance(t){return {balance:await this.client.getBalance({address:t}),decimals:18}}serializeTransaction(t){return viem.serializeTransaction(t)}deserializeTransaction(t){return viem.parseTransaction(t)}async prepareTransactionForSigning(t){let e=await this.attachGasAndNonce(t),n=viem.serializeTransaction(e),a=viem.toBytes(viem.keccak256(n));return {transaction:e,hashesToSign:[Array.from(a)]}}async prepareMessageForSigning(t){return {hashesToSign:[Array.from(viem.toBytes(viem.hashMessage(t)))]}}async prepareTypedDataForSigning(t){return {hashesToSign:[Array.from(viem.toBytes(viem.hashTypedData(t)))]}}async prepareUserOpForSigning(t,e,n){let a=n??await this.client.getChainId(),s=e||"0x0000000071727De22E5E9d8BAf0edAc6f37da032",i=viem.encodeAbiParameters([{type:"bytes32"},{type:"address"},{type:"uint256"}],[viem.keccak256(viem.encodeAbiParameters([{type:"address"},{type:"uint256"},{type:"bytes32"},{type:"bytes32"},{type:"bytes32"},{type:"uint256"},{type:"bytes32"},{type:"bytes32"}],[t.sender,viem.hexToBigInt(t.nonce),viem.keccak256("factory"in t&&"factoryData"in t&&t.factory&&t.factoryData?viem.concat([t.factory,t.factoryData]):"initCode"in t?t.initCode:"0x"),viem.keccak256(t.callData),viem.concat([viem.pad(t.verificationGasLimit,{size:16}),viem.pad(t.callGasLimit,{size:16})]),viem.hexToBigInt(t.preVerificationGas),viem.concat([viem.pad(t.maxPriorityFeePerGas,{size:16}),viem.pad(t.maxFeePerGas,{size:16})]),viem.keccak256("paymaster"in t&&t.paymaster&&viem.isAddress(t.paymaster)?viem.concat([t.paymaster,viem.pad(t.paymasterVerificationGasLimit,{size:16}),viem.pad(t.paymasterPostOpGasLimit,{size:16}),t.paymasterData]):"paymasterAndData"in t?t.paymasterAndData:"0x")])),s,BigInt(a)]),o=viem.keccak256(i);return {userOp:t,hashesToSign:[Array.from(viem.toBytes(viem.hashMessage({raw:o})))]}}attachTransactionSignature({transaction:t,rsvSignatures:e}){let n=this.transformRSVSignature(e[0]);return viem.serializeTransaction(t,n)}assembleMessageSignature({rsvSignatures:t}){return this.assembleSignature(t[0])}assembleTypedDataSignature({rsvSignatures:t}){return this.assembleSignature(t[0])}attachUserOpSignature({userOp:t,rsvSignatures:e}){let{r:n,s:a,yParity:s}=this.transformRSVSignature(e[0]);if(s===void 0)throw new Error("Missing yParity");return {...t,signature:viem.concatHex(["0x00",n,a,viem.numberToHex(Number(s+27),{size:1})])}}async broadcastTx(t){try{return await this.client.sendRawTransaction({serializedTransaction:t})}catch(e){throw console.error("Transaction broadcast failed:",e),new Error("Failed to broadcast transaction.")}}};function q(r){switch(r.toLowerCase()){case "mainnet":return f__namespace.networks.bitcoin;case "testnet":return f__namespace.networks.testnet;case "regtest":return f__namespace.networks.regtest;default:throw new Error(`Unknown Bitcoin network: ${r}`)}}var k=class r extends h{static{this.SATOSHIS_PER_BTC=1e8;}constructor({network:t,contract:e,btcRpcAdapter:n}){super(),this.network=t,this.btcRpcAdapter=n,this.contract=e;}static toBTC(t){return t/r.SATOSHIS_PER_BTC}static toSatoshi(t){return Math.round(t*r.SATOSHIS_PER_BTC)}async fetchTransaction(t){let e=await this.btcRpcAdapter.getTransaction(t),n=new f__namespace.Transaction;return e.vout.forEach(a=>{let s=Buffer.from(a.scriptpubkey,"hex");n.addOutput(s,Number(a.value));}),n}static transformRSVSignature(t){let e=t.r.padStart(64,"0"),n=t.s.padStart(64,"0"),a=Buffer.from(e+n,"hex");if(a.length!==64)throw new Error("Invalid signature length.");return a}async createPSBT({transactionRequest:t}){let{inputs:e,outputs:n}=t.inputs&&t.outputs?t:await this.btcRpcAdapter.selectUTXOs(t.from,[{address:t.to,value:parseFloat(t.value)}]),a=new f__namespace.Psbt({network:q(this.network)});return await Promise.all(e.map(async s=>{if(!s.scriptPubKey){let o=(await this.fetchTransaction(s.txid)).outs[s.vout];s.scriptPubKey=o.script;}a.addInput({hash:s.txid,index:s.vout,witnessUtxo:{script:s.scriptPubKey,value:s.value}});})),n.forEach(s=>{"address"in s?a.addOutput({address:s.address,value:s.value}):"script"in s?a.addOutput({script:s.script,value:s.value}):t.from!==void 0&&a.addOutput({value:Number(s.value),address:t.from});}),a}async getBalance(t){return {balance:BigInt(await this.btcRpcAdapter.getBalance(t)),decimals:8}}async deriveAddressAndPublicKey(t,e){let n=await this.contract.getDerivedPublicKey({path:e,predecessor:t});if(!n)throw new Error("Failed to get derived public key");let a=u.compressPubKey(n),s=Buffer.from(a,"hex"),i=q(this.network),o=f__namespace.payments.p2wpkh({pubkey:s,network:i}),{address:c}=o;if(!c)throw new Error("Failed to generate Bitcoin address");return {address:c,publicKey:a}}serializeTransaction(t){return JSON.stringify({psbt:t.psbt.toHex(),publicKey:t.publicKey})}deserializeTransaction(t){let e=JSON.parse(t);return {psbt:f__namespace.Psbt.fromHex(e.psbt),publicKey:e.publicKey}}async prepareTransactionForSigning(t){let e=Buffer.from(t.publicKey,"hex"),n=await this.createPSBT({transactionRequest:t}),a=n.toHex(),s=[],i=o=>({publicKey:e,sign:c=>(s[o]=Array.from(c),Buffer.alloc(64))});for(let o=0;o<n.inputCount;o++)n.signInput(o,i(o));return {transaction:{psbt:f__namespace.Psbt.fromHex(a),publicKey:t.publicKey},hashesToSign:s}}attachTransactionSignature({transaction:{psbt:t,publicKey:e},rsvSignatures:n}){let a=Buffer.from(e,"hex"),s=i=>({publicKey:a,sign:()=>{let o=n[i];return r.transformRSVSignature(o)}});for(let i=0;i<t.inputCount;i++)t.signInput(i,s(i));return t.finalizeAllInputs(),t.extractTransaction().toHex()}async broadcastTx(t){return await this.btcRpcAdapter.broadcastTransaction(t)}};var E=class{};var K=class extends E{constructor(t){super(),this.providerUrl=t;}async fetchFeeRate(t=6){let n=await(await fetch(`${this.providerUrl}/v1/fees/recommended`)).json();return t<=1?n.fastestFee:t<=3?n.halfHourFee:t<=6?n.hourFee:n.economyFee}async fetchUTXOs(t){try{return await(await fetch(`${this.providerUrl}/address/${t}/utxo`)).json()}catch(e){return console.error("Failed to fetch UTXOs:",e),[]}}async selectUTXOs(t,e,n=6){let a=await this.fetchUTXOs(t),s=await this.fetchFeeRate(n),i=qt__default.default(a,e,Math.ceil(s+1));if(!i.inputs||!i.outputs)throw new Error("Invalid transaction: coinselect failed to find a suitable set of inputs and outputs. This could be due to insufficient funds, or no inputs being available that meet the criteria.");return {inputs:i.inputs,outputs:i.outputs}}async broadcastTransaction(t){let e=await fetch(`${this.providerUrl}/tx`,{method:"POST",body:t});if(e.ok)return await e.text();throw new Error(`Failed to broadcast transaction: ${await e.text()}`)}async getBalance(t){let n=await(await fetch(`${this.providerUrl}/address/${t}`)).json();return n.chain_stats.funded_txo_sum-n.chain_stats.spent_txo_sum}async getTransaction(t){return await(await fetch(`${this.providerUrl}/tx/${t}`)).json()}};var W={Mempool:K};var mt=async r=>{let t=chainRegistry.chains.find(d=>d.chain_id===r);if(!t)throw new Error(`Chain info not found for chainId: ${r}`);let{bech32_prefix:e,chain_id:n}=t,a=t.staking?.staking_tokens?.[0]?.denom,s=t.apis?.rpc?.[0]?.address,i=t.apis?.rest?.[0]?.address,o=t.fees?.fee_tokens?.[0]?.average_gas_price;if(!e||!a||!s||!i||!n||o===void 0)throw new Error(`Missing required chain information for ${t.chain_name}`);let p=chainRegistry.assets.find(d=>d.chain_name===t.chain_name)?.assets.find(d=>d.base===a),y=p?.denom_units.find(d=>d.denom===p.display)?.exponent;if(y===void 0)throw new Error(`Could not find decimals for ${a} on chain ${t.chain_name}`);return {prefix:e,denom:a,rpcUrl:s,restUrl:i,expectedChainId:n,gasPrice:o,decimals:y}};var _=class extends h{constructor({chainId:t,contract:e,endpoints:n}){super(),this.contract=e,this.registry=new protoSigning.Registry,this.chainId=t,this.endpoints=n;}transformRSVSignature(t){return new Uint8Array([...encoding.fromHex(t.r),...encoding.fromHex(t.s)])}async getChainInfo(){return {...await mt(this.chainId),...this.endpoints}}async getBalance(t){try{let{restUrl:e,denom:n,decimals:a}=await this.getChainInfo(),s=await fetch(`${e}/cosmos/bank/v1beta1/balances/${t}`);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);let c=(await s.json()).balances.find(p=>p.denom===n)?.amount??"0";return {balance:BigInt(c),decimals:a}}catch(e){throw console.error("Failed to fetch Cosmos balance:",e),new Error("Failed to fetch Cosmos balance")}}async deriveAddressAndPublicKey(t,e){let{prefix:n}=await this.getChainInfo(),a=await this.contract.getDerivedPublicKey({path:e,predecessor:t});if(!a)throw new Error("Failed to get derived public key");let s=u.compressPubKey(a),i=crypto$1.sha256(encoding.fromHex(s)),o=crypto$1.ripemd160(i);return {address:bech32.bech32.encode(n,bech32.bech32.toWords(o)),publicKey:s}}serializeTransaction(t){let e=tx.TxRaw.encode(t).finish();return encoding.toBase64(e)}deserializeTransaction(t){return tx.TxRaw.decode(encoding.fromBase64(t))}async prepareTransactionForSigning(t){let{denom:e,rpcUrl:n,gasPrice:a}=await this.getChainInfo(),s=encoding.fromHex(t.publicKey),i=t.gas||2e5,o=stargate.calculateFee(i,stargate.GasPrice.fromString(`${a}${e}`)),p=await(await stargate.StargateClient.connect(n)).getAccount(t.address);if(!p)throw new Error(`Account ${t.address} does not exist on chain`);let{accountNumber:y,sequence:d}=p,V={typeUrl:"/cosmos.tx.v1beta1.TxBody",value:{messages:t.messages,memo:t.memo||""}},M=this.registry.encode(V),j=protoSigning.encodePubkey(amino.encodeSecp256k1Pubkey(s)),ot=protoSigning.makeAuthInfoBytes([{pubkey:j,sequence:d}],o.amount,Number(o.gas),void 0,void 0,signing.SignMode.SIGN_MODE_DIRECT),Tt=protoSigning.makeSignDoc(M,ot,this.chainId,y),St=protoSigning.makeSignBytes(Tt),Ct=Array.from(crypto$1.sha256(St));return {transaction:tx.TxRaw.fromPartial({bodyBytes:M,authInfoBytes:ot,signatures:[]}),hashesToSign:[Ct]}}attachTransactionSignature({transaction:t,rsvSignatures:e}){t.signatures=e.map(a=>this.transformRSVSignature(a));let n=tx.TxRaw.encode(t).finish();return Buffer.from(n).toString("hex")}async broadcastTx(t){try{let{rpcUrl:e}=await this.getChainInfo(),n=await stargate.StargateClient.connect(e),a=encoding.fromHex(t),s=await n.broadcastTx(a);if(s.code!==0)throw new Error(`Broadcast error: ${s.rawLog}`);return s.transactionHash}catch(e){throw console.error("Transaction broadcast failed:",e),new Error("Failed to broadcast transaction.")}}};var pe=async(r,t)=>{try{let e=await w({networkId:r.nearAuthentication.networkId,accountId:r.nearAuthentication.accountId,keypair:t}),n=new l({networkId:r.nearAuthentication.networkId,contractId:r.chainConfig.contract,accountId:e.accountId,keypair:t}),a=new B({rpcUrl:r.chainConfig.providerUrl,contract:n}),{transaction:s,hashesToSign:i}=await a.prepareTransactionForSigning(r.transaction),o=await n.sign({payload:i[0],path:r.derivationPath,key_version:0}),c=a.attachTransactionSignature({transaction:s,rsvSignatures:[o]});return {transactionHash:await a.broadcastTx(c),success:!0}}catch(e){return console.error(e),{success:false,errorMessage:e instanceof Error?e.message:String(e)}}},ue=async(r,t)=>{try{let e=await w({networkId:r.nearAuthentication.networkId,accountId:r.nearAuthentication.accountId,keypair:t}),n=new l({networkId:r.nearAuthentication.networkId,contractId:r.chainConfig.contract,accountId:e.accountId,keypair:t}),a=new k({btcRpcAdapter:new W.Mempool(r.chainConfig.providerUrl),contract:n,network:r.chainConfig.network}),{transaction:s,hashesToSign:i}=await a.prepareTransactionForSigning(r.transaction),o=await Promise.all(i.map(async y=>await n.sign({payload:y,path:r.derivationPath,key_version:0}))),c=a.attachTransactionSignature({transaction:s,rsvSignatures:o});return {transactionHash:await a.broadcastTx(c),success:!0}}catch(e){return {success:false,errorMessage:e instanceof Error?e.message:String(e)}}},de=async(r,t)=>{try{let e=await w({networkId:r.nearAuthentication.networkId,accountId:r.nearAuthentication.accountId,keypair:t}),n=new l({networkId:r.nearAuthentication.networkId,contractId:r.chainConfig.contract,accountId:e.accountId,keypair:t}),a=new _({contract:n,chainId:r.chainConfig.chainId}),{transaction:s,hashesToSign:i}=await a.prepareTransactionForSigning(r.transaction),o=await Promise.all(i.map(async y=>await n.sign({payload:y,path:r.derivationPath,key_version:0}))),c=a.attachTransactionSignature({transaction:s,rsvSignatures:o});return {transactionHash:await a.broadcastTx(c),success:!0}}catch(e){return console.error(e),{success:false,errorMessage:e instanceof Error?e.message:String(e)}}};var st={};m(st,{ChainSignatureContract:()=>at,abi:()=>C,errors:()=>rt});var nt={};m(nt,{CHAINS:()=>S,CONTRACT_ADDRESSES:()=>et,ENVS:()=>g,KDF_CHAIN_IDS:()=>tt,ROOT_PUBLIC_KEYS:()=>Z});var g={TESTNET_DEV:"TESTNET_DEV",TESTNET:"TESTNET",MAINNET:"MAINNET"},S={ETHEREUM:"ETHEREUM",NEAR:"NEAR"},Z={[g.TESTNET_DEV]:"secp256k1:54hU5wcCmVUPFWLDALXMh1fFToZsVXrx9BbTbHzSfQq1Kd1rJZi52iPa4QQxo6s5TgjWqgpY8HamYuUDzG6fAaUq",[g.TESTNET]:"secp256k1:3Ww8iFjqTHufye5aRGUvrQqETegR4gVUcW8FX5xzscaN9ENhpkffojsxJwi6N1RbbHMTxYa9UyKeqK3fsMuwxjR5",[g.MAINNET]:"secp256k1:4tY4qMzusmgX5wYdG35663Y3Qar3CTbpApotwk9ZKLoF79XA4DjG8XoByaKdNHKQX9Lz5hd7iJqsWdTKyA7dKa6Z"},tt={[S.ETHEREUM]:"0x1",[S.NEAR]:"0x18d"},et={[S.NEAR]:{[g.TESTNET_DEV]:"dev.sig-net.testnet",[g.TESTNET]:"v1.sig-net.testnet",[g.MAINNET]:"v1.sig-net.near"},[S.ETHEREUM]:{[g.TESTNET_DEV]:"0x69C6b28Fdc74618817fa380De29a653060e14009",[g.TESTNET]:"0x83458E8Bf8206131Fe5c05127007FA164c0948A2",[g.MAINNET]:"0xf8bdC0612361a1E49a8E01423d4C0cFc5dF4791A"}};var ft=(r,t)=>{let e=Object.entries(et[t]).find(([n,a])=>a.toLowerCase()===r.toLowerCase())?.[0];if(e)return Z[e];throw new Error(`Contract address ${r} not supported for chain ${t}`)};var C=[{inputs:[{internalType:"address",name:"_mpc_network",type:"address"},{internalType:"uint256",name:"_signatureDeposit",type:"uint256"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"AccessControlBadConfirmation",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"bytes32",name:"neededRole",type:"bytes32"}],name:"AccessControlUnauthorizedAccount",type:"error"},{anonymous:false,inputs:[{indexed:true,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:true,internalType:"bytes32",name:"previousAdminRole",type:"bytes32"},{indexed:true,internalType:"bytes32",name:"newAdminRole",type:"bytes32"}],name:"RoleAdminChanged",type:"event"},{anonymous:false,inputs:[{indexed:true,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:true,internalType:"address",name:"account",type:"address"},{indexed:true,internalType:"address",name:"sender",type:"address"}],name:"RoleGranted",type:"event"},{anonymous:false,inputs:[{indexed:true,internalType:"bytes32",name:"role",type:"bytes32"},{indexed:true,internalType:"address",name:"account",type:"address"},{indexed:true,internalType:"address",name:"sender",type:"address"}],name:"RoleRevoked",type:"event"},{anonymous:false,inputs:[{indexed:true,internalType:"bytes32",name:"requestId",type:"bytes32"},{indexed:false,internalType:"address",name:"responder",type:"address"},{indexed:false,internalType:"string",name:"error",type:"string"}],name:"SignatureError",type:"event"},{anonymous:false,inputs:[{indexed:false,internalType:"address",name:"sender",type:"address"},{indexed:false,internalType:"bytes32",name:"payload",type:"bytes32"},{indexed:false,internalType:"uint32",name:"keyVersion",type:"uint32"},{indexed:false,internalType:"uint256",name:"deposit",type:"uint256"},{indexed:false,internalType:"uint256",name:"chainId",type:"uint256"},{indexed:false,internalType:"string",name:"path",type:"string"},{indexed:false,internalType:"string",name:"algo",type:"string"},{indexed:false,internalType:"string",name:"dest",type:"string"},{indexed:false,internalType:"string",name:"params",type:"string"}],name:"SignatureRequested",type:"event"},{anonymous:false,inputs:[{indexed:true,internalType:"bytes32",name:"requestId",type:"bytes32"},{indexed:false,internalType:"address",name:"responder",type:"address"},{components:[{components:[{internalType:"uint256",name:"x",type:"uint256"},{internalType:"uint256",name:"y",type:"uint256"}],internalType:"struct ChainSignatures.AffinePoint",name:"bigR",type:"tuple"},{internalType:"uint256",name:"s",type:"uint256"},{internalType:"uint8",name:"recoveryId",type:"uint8"}],indexed:false,internalType:"struct ChainSignatures.Signature",name:"signature",type:"tuple"}],name:"SignatureResponded",type:"event"},{anonymous:false,inputs:[{indexed:true,internalType:"address",name:"owner",type:"address"},{indexed:false,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[],name:"DEFAULT_ADMIN_ROLE",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"}],name:"getRoleAdmin",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getSignatureDeposit",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"grantRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"hasRole",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"callerConfirmation",type:"address"}],name:"renounceRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"bytes32",name:"requestId",type:"bytes32"},{components:[{components:[{internalType:"uint256",name:"x",type:"uint256"},{internalType:"uint256",name:"y",type:"uint256"}],internalType:"struct ChainSignatures.AffinePoint",name:"bigR",type:"tuple"},{internalType:"uint256",name:"s",type:"uint256"},{internalType:"uint8",name:"recoveryId",type:"uint8"}],internalType:"struct ChainSignatures.Signature",name:"signature",type:"tuple"}],internalType:"struct ChainSignatures.Response[]",name:"_responses",type:"tuple[]"}],name:"respond",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"bytes32",name:"requestId",type:"bytes32"},{internalType:"string",name:"errorMessage",type:"string"}],internalType:"struct ChainSignatures.ErrorResponse[]",name:"_errors",type:"tuple[]"}],name:"respondError",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"role",type:"bytes32"},{internalType:"address",name:"account",type:"address"}],name:"revokeRole",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_amount",type:"uint256"}],name:"setSignatureDeposit",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"bytes32",name:"payload",type:"bytes32"},{internalType:"string",name:"path",type:"string"},{internalType:"uint32",name:"keyVersion",type:"uint32"},{internalType:"string",name:"algo",type:"string"},{internalType:"string",name:"dest",type:"string"},{internalType:"string",name:"params",type:"string"}],internalType:"struct ChainSignatures.SignRequest",name:"_request",type:"tuple"}],name:"sign",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_amount",type:"uint256"},{internalType:"address",name:"_receiver",type:"address"}],name:"withdraw",outputs:[],stateMutability:"nonpayable",type:"function"}];var rt={};m(rt,{ChainSignatureError:()=>v,SignatureContractError:()=>I,SignatureNotFoundError:()=>R,SigningError:()=>U});var v=class extends Error{constructor(t,e,n){super(t),this.name="ChainSignatureError",this.requestId=e,this.receipt=n;}},R=class extends v{constructor(t,e){super("Signature not found after maximum retries",t,e),this.name="SignatureNotFoundError";}},I=class extends v{constructor(t,e,n){super(`Signature error: ${t}`,e,n),this.name="SignatureContractError",this.errorCode=t;}},U=class extends v{constructor(t,e,n){super("Error signing request",t,e),this.name="SigningError",this.originalError=n;}};var at=class extends b{constructor(t){super(),this.publicClient=t.publicClient,this.walletClient=t.walletClient,this.contractAddress=t.contractAddress,this.rootPublicKey=t.rootPublicKey||ft(this.contractAddress,S.ETHEREUM);}async getCurrentSignatureDeposit(){let t=await this.publicClient.readContract({address:this.contractAddress,abi:C,functionName:"getSignatureDeposit"});return new xt__default.default(t.toString())}async getDerivedPublicKey(t){return u.deriveChildPublicKey(await this.getPublicKey(),t.predecessor.toLowerCase(),t.path,tt.ETHEREUM)}async getPublicKey(){return x(this.rootPublicKey)}async getLatestKeyVersion(){let t=await this.publicClient.readContract({address:this.contractAddress,abi:C,functionName:"latestKeyVersion"});return Number(t)}async sign(t,e={sign:{algo:"",dest:"",params:""},retry:{delay:5e3,retryCount:12}}){if(!this.walletClient?.account)throw new Error("Wallet client required for signing operations");let n={payload:`0x${Buffer.from(t.payload).toString("hex")}`,path:t.path,keyVersion:t.key_version,algo:e.sign.algo??"",dest:e.sign.dest??"",params:e.sign.params??""},a=this.getRequestId(n),s=await this.walletClient.writeContract({address:this.contractAddress,abi:C,chain:this.publicClient.chain,account:this.walletClient.account,functionName:"sign",args:[n],value:BigInt((await this.getCurrentSignatureDeposit()).toString())}),i=await this.publicClient.waitForTransactionReceipt({hash:s});try{let o=await viem.withRetry(async()=>{let c=await this.getSignatureFromEvents(a,i);if(c)return c;throw new Error("Signature not found yet")},{delay:e.retry.delay,retryCount:e.retry.retryCount,shouldRetry:({count:c,error:p})=>(console.log(`Retrying get signature: ${c}/${e.retry.retryCount}`),p.message==="Signature not found yet")});if(o)return o;{let c=await this.getErrorFromEvents(a,i);throw c?new I(c.error,a,i):new R(a,i)}}catch(o){throw o instanceof R||o instanceof I?o:new U(a,i,o instanceof Error?o:void 0)}}getRequestId(t){if(!this.walletClient?.account)throw new Error("Wallet client required for signing operations");let e=viem.encodeAbiParameters([{type:"address"},{type:"bytes"},{type:"string"},{type:"uint32"},{type:"uint256"},{type:"string"},{type:"string"},{type:"string"}],[this.walletClient.account.address,t.payload,t.path,Number(t.keyVersion),this.publicClient.chain?.id?BigInt(this.publicClient.chain.id):0n,t.algo,t.dest,t.params]);return viem.keccak256(e)}async getErrorFromEvents(t,e){let n=await this.publicClient.getContractEvents({address:this.contractAddress,abi:C,eventName:"SignatureError",args:{requestId:t},fromBlock:e.blockNumber,toBlock:"latest"});if(n.length>0){let{args:a}=n[n.length-1];return a}}async getSignatureFromEvents(t,e){let n=await this.publicClient.getContractEvents({address:this.contractAddress,abi:C,eventName:"SignatureResponded",args:{requestId:t},fromBlock:e.blockNumber,toBlock:"latest"});if(n.length>0){let{args:a}=n[n.length-1];return u.toRSV(a.signature)}}};
|
|
2
|
-
exports.BTCRpcAdapter=E;exports.BTCRpcAdapters=W;exports.Bitcoin=k;exports.Chain=h;exports.ChainSignatureContract=b;exports.Cosmos=_;exports.EVM=B;exports.fetchEVMFeeProperties=L;exports.utils=bt;//# sourceMappingURL=index.browser.cjs.map
|
|
3
|
-
//# sourceMappingURL=index.browser.cjs.map
|