signet.js 0.0.1-beta.6 → 0.0.1-beta.7

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.
Files changed (121) hide show
  1. package/.eslintrc.json +55 -0
  2. package/.prettierrc +1 -0
  3. package/LICENSE +19 -0
  4. package/README.md +42 -14
  5. package/babel.config.js +6 -0
  6. package/docs/pages/chain-signatures-contract.mdx +56 -0
  7. package/docs/pages/chain.mdx +45 -0
  8. package/docs/pages/chains/bitcoin/bitcoin.mdx +191 -0
  9. package/docs/pages/chains/bitcoin/btc-rpc-adapter.mdx +307 -0
  10. package/docs/pages/chains/cosmos.mdx +181 -0
  11. package/docs/pages/chains/evm.mdx +189 -0
  12. package/docs/pages/index.mdx +99 -0
  13. package/docs/snippets/contract.ts +21 -0
  14. package/docs/snippets/env.ts +13 -0
  15. package/jest.config.ts +199 -0
  16. package/package.json +21 -11
  17. package/src/chains/Bitcoin/BTCRpcAdapter/BTCRpcAdapter.ts +11 -0
  18. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/Mempool.ts +96 -0
  19. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/index.ts +1 -0
  20. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/types.ts +72 -0
  21. package/src/chains/Bitcoin/BTCRpcAdapter/index.ts +6 -0
  22. package/src/chains/Bitcoin/Bitcoin.ts +301 -0
  23. package/src/chains/Bitcoin/types.ts +45 -0
  24. package/src/chains/Bitcoin/utils.ts +14 -0
  25. package/src/chains/Chain.ts +96 -0
  26. package/src/chains/ChainSignatureContract.ts +48 -0
  27. package/src/chains/Cosmos/Cosmos.ts +279 -0
  28. package/src/chains/Cosmos/types.ts +35 -0
  29. package/src/chains/Cosmos/utils.ts +45 -0
  30. package/src/chains/EVM/EVM.ts +180 -0
  31. package/src/chains/EVM/types.ts +7 -0
  32. package/src/chains/EVM/utils.ts +26 -0
  33. package/src/chains/index.ts +34 -0
  34. package/src/chains/types.ts +35 -0
  35. package/src/chains/utils.ts +40 -0
  36. package/src/index.ts +2 -0
  37. package/src/utils/chains/index.ts +1 -0
  38. package/src/utils/chains/near/ChainSignatureContract.ts +195 -0
  39. package/src/utils/chains/near/account.ts +42 -0
  40. package/src/utils/chains/near/constants.ts +4 -0
  41. package/src/utils/chains/near/index.ts +3 -0
  42. package/src/utils/chains/near/relayer/index.ts +1 -0
  43. package/src/utils/chains/near/relayer/relayer.ts +39 -0
  44. package/src/utils/chains/near/relayer/types.ts +24 -0
  45. package/src/utils/chains/near/signAndSend/index.ts +1 -0
  46. package/src/utils/chains/near/signAndSend/keypair.ts +180 -0
  47. package/src/utils/chains/near/transactionBuilder.ts +138 -0
  48. package/src/utils/chains/near/types.ts +67 -0
  49. package/src/utils/index.ts +1 -0
  50. package/tsconfig.eslint.json +8 -0
  51. package/tsconfig.json +116 -0
  52. package/vite.config.ts +47 -0
  53. package/vocs.config.ts +60 -0
  54. package/src/chains/Bitcoin/BTCRpcAdapter/BTCRpcAdapter.d.ts +0 -10
  55. package/src/chains/Bitcoin/BTCRpcAdapter/BTCRpcAdapter.js +0 -2
  56. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/Mempool.d.ts +0 -15
  57. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/Mempool.js +0 -69
  58. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/index.d.ts +0 -1
  59. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/index.js +0 -1
  60. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/types.d.ts +0 -69
  61. package/src/chains/Bitcoin/BTCRpcAdapter/Mempool/types.js +0 -1
  62. package/src/chains/Bitcoin/BTCRpcAdapter/index.d.ts +0 -5
  63. package/src/chains/Bitcoin/BTCRpcAdapter/index.js +0 -5
  64. package/src/chains/Bitcoin/Bitcoin.d.ts +0 -69
  65. package/src/chains/Bitcoin/Bitcoin.js +0 -198
  66. package/src/chains/Bitcoin/types.d.ts +0 -42
  67. package/src/chains/Bitcoin/types.js +0 -1
  68. package/src/chains/Bitcoin/utils.d.ts +0 -2
  69. package/src/chains/Bitcoin/utils.js +0 -13
  70. package/src/chains/Chain.d.ts +0 -89
  71. package/src/chains/Chain.js +0 -9
  72. package/src/chains/ChainSignatureContract.d.ts +0 -62
  73. package/src/chains/ChainSignatureContract.js +0 -7
  74. package/src/chains/Cosmos/Cosmos.d.ts +0 -51
  75. package/src/chains/Cosmos/Cosmos.js +0 -157
  76. package/src/chains/Cosmos/types.d.ts +0 -30
  77. package/src/chains/Cosmos/types.js +0 -1
  78. package/src/chains/Cosmos/utils.d.ts +0 -2
  79. package/src/chains/Cosmos/utils.js +0 -27
  80. package/src/chains/EVM/EVM.d.ts +0 -42
  81. package/src/chains/EVM/EVM.js +0 -109
  82. package/src/chains/EVM/types.d.ts +0 -5
  83. package/src/chains/EVM/types.js +0 -1
  84. package/src/chains/EVM/utils.d.ts +0 -7
  85. package/src/chains/EVM/utils.js +0 -14
  86. package/src/chains/index.d.ts +0 -12
  87. package/src/chains/index.js +0 -12
  88. package/src/chains/types.d.ts +0 -31
  89. package/src/chains/types.js +0 -1
  90. package/src/chains/utils.d.ts +0 -12
  91. package/src/chains/utils.js +0 -27
  92. package/src/index.d.ts +0 -2
  93. package/src/index.js +0 -2
  94. package/src/utils/chains/index.d.ts +0 -1
  95. package/src/utils/chains/index.js +0 -1
  96. package/src/utils/chains/near/account.d.ts +0 -13
  97. package/src/utils/chains/near/account.js +0 -22
  98. package/src/utils/chains/near/constants.d.ts +0 -3
  99. package/src/utils/chains/near/constants.js +0 -3
  100. package/src/utils/chains/near/contract.d.ts +0 -40
  101. package/src/utils/chains/near/contract.js +0 -102
  102. package/src/utils/chains/near/index.d.ts +0 -3
  103. package/src/utils/chains/near/index.js +0 -3
  104. package/src/utils/chains/near/relayer/index.d.ts +0 -1
  105. package/src/utils/chains/near/relayer/index.js +0 -1
  106. package/src/utils/chains/near/relayer/relayer.d.ts +0 -8
  107. package/src/utils/chains/near/relayer/relayer.js +0 -33
  108. package/src/utils/chains/near/relayer/types.d.ts +0 -22
  109. package/src/utils/chains/near/relayer/types.js +0 -1
  110. package/src/utils/chains/near/signAndSend/index.d.ts +0 -1
  111. package/src/utils/chains/near/signAndSend/index.js +0 -1
  112. package/src/utils/chains/near/signAndSend/keypair.d.ts +0 -6
  113. package/src/utils/chains/near/signAndSend/keypair.js +0 -127
  114. package/src/utils/chains/near/transactionBuilder.d.ts +0 -26
  115. package/src/utils/chains/near/transactionBuilder.js +0 -72
  116. package/src/utils/chains/near/types.d.ts +0 -50
  117. package/src/utils/chains/near/types.js +0 -1
  118. package/src/utils/index.d.ts +0 -1
  119. package/src/utils/index.js +0 -1
  120. package/vocs.config.d.ts +0 -3
  121. package/vocs.config.js +0 -71
@@ -0,0 +1,99 @@
1
+ # Signet.js Documentation
2
+
3
+ A TypeScript library for handling interactions with Sig Network MPC and Smart Contracts
4
+
5
+ ## Supported Chains
6
+
7
+ - [EVM Chains](./chains/evm.mdx) - Ethereum and compatible networks
8
+ - [Bitcoin](./chains/bitcoin/bitcoin.mdx) - Bitcoin network
9
+ - [Cosmos Chains](./chains/cosmos.mdx) - Cosmos SDK-based networks
10
+
11
+ ## Core Features
12
+
13
+ - **Balance Checking**: Query account balances across different chains
14
+ - **Address and Public Key Derivation**: Derive addresses and public keys following Sig Network derivation function
15
+ - **Transaction Management**: Create, store, and retrieve transactions
16
+ - **Signature Handling**: Process MPC signatures for transactions
17
+ - **Transaction Broadcasting**: Submit signed transactions to the network
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ npm install signet.js
23
+ # or
24
+ yarn add signet.js
25
+ # or
26
+ pnpm add signet.js
27
+ ```
28
+
29
+ ## Quick Start
30
+
31
+ Here's a basic example using the EVM implementation:
32
+
33
+ ```ts twoslash
34
+ import { EVM, utils } from 'signet.js'
35
+ // [!include ~/snippets/env.ts]
36
+
37
+ const contract = new utils.chains.near.ChainSignatureContract({
38
+ networkId: 'testnet',
39
+ contractId: 'v1.signer-prod.testnet',
40
+ accountId,
41
+ keypair,
42
+ })
43
+
44
+ const evmChain = new EVM({
45
+ rpcUrl: 'https://mainnet.infura.io/v3/YOUR-PROJECT-ID',
46
+ contract,
47
+ })
48
+
49
+ // Derive address and public key
50
+ const { address, publicKey } = await evmChain.deriveAddressAndPublicKey(
51
+ accountId,
52
+ 'any_string'
53
+ )
54
+
55
+ // Check balance
56
+ const balance = await evmChain.getBalance(address)
57
+
58
+ // Create and sign transaction
59
+ const { transaction, mpcPayloads } = await evmChain.getMPCPayloadAndTransaction(
60
+ {
61
+ from: '0x...',
62
+ to: '0x...',
63
+ value: '1000000000000000000',
64
+ }
65
+ )
66
+
67
+ // Sign with MPC
68
+ const signature = await contract.sign({
69
+ payload: mpcPayloads[0].payload,
70
+ path: 'any_string',
71
+ key_version: 0,
72
+ })
73
+
74
+ // Add signature
75
+ const signedTx = evmChain.addSignature({
76
+ transaction,
77
+ mpcSignatures: [signature],
78
+ })
79
+
80
+ // Broadcast transaction
81
+ const txHash = await evmChain.broadcastTx(signedTx)
82
+ ```
83
+
84
+ ## Architecture
85
+
86
+ The library is built around a core `Chain` interface that defines common functionality across all supported blockchain networks. Each specific chain implementation extends this interface with network-specific features while maintaining a consistent API.
87
+
88
+ For more details check the [Chain](./chain.mdx) page.
89
+
90
+ ## Utility Functions
91
+
92
+ Besides the Chain classes the library also provide utility functions to assist you on building transactions, requesting signature in wrapped methods.
93
+
94
+ Currently we support only Near, but we are working on adding support for other chains.
95
+
96
+ ## Repositories
97
+
98
+ - Signet.js: [https://github.com/sig-net/signet.js](https://github.com/sig-net/signet.js).
99
+ - MPC: [https://github.com/sig-net/mpc](https://github.com/sig-net/mpc).
@@ -0,0 +1,21 @@
1
+ import { KeyPair, type KeyPairString } from '@near-js/crypto'
2
+ import { utils } from 'signet.js'
3
+
4
+ // Initialize NEAR connection with credentials from environment
5
+ const accountId = process.env.NEAR_ACCOUNT_ID
6
+ const privateKey = process.env.NEAR_PRIVATE_KEY as KeyPairString
7
+
8
+ if (!accountId || !privateKey) {
9
+ throw new Error(
10
+ 'NEAR_ACCOUNT_ID and NEAR_PRIVATE_KEY must be set in environment'
11
+ )
12
+ }
13
+
14
+ const keypair = KeyPair.fromString(privateKey)
15
+
16
+ const contract = new utils.chains.near.ChainSignatureContract({
17
+ networkId: 'testnet',
18
+ contractId: 'v1.signer-prod.testnet',
19
+ accountId,
20
+ keypair,
21
+ })
@@ -0,0 +1,13 @@
1
+ import { KeyPair, type KeyPairString } from '@near-js/crypto'
2
+
3
+ // Initialize NEAR connection with credentials from environment
4
+ const accountId = process.env.NEAR_ACCOUNT_ID
5
+ const privateKey = process.env.NEAR_PRIVATE_KEY as KeyPairString
6
+
7
+ if (!accountId || !privateKey) {
8
+ throw new Error(
9
+ 'NEAR_ACCOUNT_ID and NEAR_PRIVATE_KEY must be set in environment'
10
+ )
11
+ }
12
+
13
+ const keypair = KeyPair.fromString(privateKey)
package/jest.config.ts ADDED
@@ -0,0 +1,199 @@
1
+ /**
2
+ * For a detailed explanation regarding each configuration property, visit:
3
+ * https://jestjs.io/docs/configuration
4
+ */
5
+
6
+ import type {Config} from 'jest';
7
+
8
+ const config: Config = {
9
+ // All imported modules in your tests should be mocked automatically
10
+ // automock: false,
11
+
12
+ // Stop running tests after `n` failures
13
+ // bail: 0,
14
+
15
+ // The directory where Jest should store its cached dependency information
16
+ // cacheDirectory: "/private/var/folders/dn/p7pfr0cd1x94jsqf6_79fg8m0000gn/T/jest_dx",
17
+
18
+ // Automatically clear mock calls, instances, contexts and results before every test
19
+ clearMocks: true,
20
+
21
+ // Indicates whether the coverage information should be collected while executing the test
22
+ // collectCoverage: false,
23
+
24
+ // An array of glob patterns indicating a set of files for which coverage information should be collected
25
+ // collectCoverageFrom: undefined,
26
+
27
+ // The directory where Jest should output its coverage files
28
+ // coverageDirectory: undefined,
29
+
30
+ // An array of regexp pattern strings used to skip coverage collection
31
+ // coveragePathIgnorePatterns: [
32
+ // "/node_modules/"
33
+ // ],
34
+
35
+ // Indicates which provider should be used to instrument code for coverage
36
+ coverageProvider: "v8",
37
+
38
+ // A list of reporter names that Jest uses when writing coverage reports
39
+ // coverageReporters: [
40
+ // "json",
41
+ // "text",
42
+ // "lcov",
43
+ // "clover"
44
+ // ],
45
+
46
+ // An object that configures minimum threshold enforcement for coverage results
47
+ // coverageThreshold: undefined,
48
+
49
+ // A path to a custom dependency extractor
50
+ // dependencyExtractor: undefined,
51
+
52
+ // Make calling deprecated APIs throw helpful error messages
53
+ // errorOnDeprecated: false,
54
+
55
+ // The default configuration for fake timers
56
+ // fakeTimers: {
57
+ // "enableGlobally": false
58
+ // },
59
+
60
+ // Force coverage collection from ignored files using an array of glob patterns
61
+ // forceCoverageMatch: [],
62
+
63
+ // A path to a module which exports an async function that is triggered once before all test suites
64
+ // globalSetup: undefined,
65
+
66
+ // A path to a module which exports an async function that is triggered once after all test suites
67
+ // globalTeardown: undefined,
68
+
69
+ // A set of global variables that need to be available in all test environments
70
+ // globals: {},
71
+
72
+ // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
73
+ // maxWorkers: "50%",
74
+
75
+ // An array of directory names to be searched recursively up from the requiring module's location
76
+ // moduleDirectories: [
77
+ // "node_modules"
78
+ // ],
79
+
80
+ // An array of file extensions your modules use
81
+ // moduleFileExtensions: [
82
+ // "js",
83
+ // "mjs",
84
+ // "cjs",
85
+ // "jsx",
86
+ // "ts",
87
+ // "tsx",
88
+ // "json",
89
+ // "node"
90
+ // ],
91
+
92
+ // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
93
+ // moduleNameMapper: {},
94
+
95
+ // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
96
+ // modulePathIgnorePatterns: [],
97
+
98
+ // Activates notifications for test results
99
+ // notify: false,
100
+
101
+ // An enum that specifies notification mode. Requires { notify: true }
102
+ // notifyMode: "failure-change",
103
+
104
+ // A preset that is used as a base for Jest's configuration
105
+ // preset: undefined,
106
+
107
+ // Run tests from one or more projects
108
+ // projects: undefined,
109
+
110
+ // Use this configuration option to add custom reporters to Jest
111
+ // reporters: undefined,
112
+
113
+ // Automatically reset mock state before every test
114
+ // resetMocks: false,
115
+
116
+ // Reset the module registry before running each individual test
117
+ // resetModules: false,
118
+
119
+ // A path to a custom resolver
120
+ // resolver: undefined,
121
+
122
+ // Automatically restore mock state and implementation before every test
123
+ // restoreMocks: false,
124
+
125
+ // The root directory that Jest should scan for tests and modules within
126
+ // rootDir: undefined,
127
+
128
+ // A list of paths to directories that Jest should use to search for files in
129
+ // roots: [
130
+ // "<rootDir>"
131
+ // ],
132
+
133
+ // Allows you to use a custom runner instead of Jest's default test runner
134
+ // runner: "jest-runner",
135
+
136
+ // The paths to modules that run some code to configure or set up the testing environment before each test
137
+ // setupFiles: [],
138
+
139
+ // A list of paths to modules that run some code to configure or set up the testing framework before each test
140
+ // setupFilesAfterEnv: [],
141
+
142
+ // The number of seconds after which a test is considered as slow and reported as such in the results.
143
+ // slowTestThreshold: 5,
144
+
145
+ // A list of paths to snapshot serializer modules Jest should use for snapshot testing
146
+ // snapshotSerializers: [],
147
+
148
+ // The test environment that will be used for testing
149
+ // testEnvironment: "jest-environment-node",
150
+
151
+ // Options that will be passed to the testEnvironment
152
+ // testEnvironmentOptions: {},
153
+
154
+ // Adds a location field to test results
155
+ // testLocationInResults: false,
156
+
157
+ // The glob patterns Jest uses to detect test files
158
+ // testMatch: [
159
+ // "**/__tests__/**/*.[jt]s?(x)",
160
+ // "**/?(*.)+(spec|test).[tj]s?(x)"
161
+ // ],
162
+
163
+ // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
164
+ // testPathIgnorePatterns: [
165
+ // "/node_modules/"
166
+ // ],
167
+
168
+ // The regexp pattern or array of patterns that Jest uses to detect test files
169
+ // testRegex: [],
170
+
171
+ // This option allows the use of a custom results processor
172
+ // testResultsProcessor: undefined,
173
+
174
+ // This option allows use of a custom test runner
175
+ // testRunner: "jest-circus/runner",
176
+
177
+ // A map from regular expressions to paths to transformers
178
+ // transform: undefined,
179
+
180
+ // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
181
+ // transformIgnorePatterns: [
182
+ // "/node_modules/",
183
+ // "\\.pnp\\.[^\\/]+$"
184
+ // ],
185
+
186
+ // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
187
+ // unmockedModulePathPatterns: undefined,
188
+
189
+ // Indicates whether each individual test should be reported during the run
190
+ // verbose: undefined,
191
+
192
+ // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
193
+ // watchPathIgnorePatterns: [],
194
+
195
+ // Whether to use watchman for file crawling
196
+ // watchman: true,
197
+ };
198
+
199
+ export default config;
package/package.json CHANGED
@@ -1,15 +1,28 @@
1
1
  {
2
2
  "name": "signet.js",
3
- "version": "0.0.1-beta.6",
3
+ "version": "0.0.1-beta.7",
4
4
  "description": "",
5
5
  "type": "module",
6
- "main": "./src/index.js",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./src/index.d.ts",
9
+ "import": {
10
+ "browser": "./index.js",
11
+ "node": "./index.js"
12
+ },
13
+ "require": "./index.cjs"
14
+ }
15
+ },
16
+ "main": "./index.cjs",
17
+ "module": "./index.js",
18
+ "browser": "./index.js",
7
19
  "types": "./src/index.d.ts",
8
20
  "scripts": {
9
- "build": "tsc --project tsconfig.json && tsc-alias",
10
- "pre:deploy": "npm run build && cp package.json README.md dist/",
11
- "publish-npm": "npm run pre:deploy && cd dist && npm publish",
12
- "publish-npm:beta": "npm run pre:deploy && cd dist && npm publish --tag beta",
21
+ "build": "rm -rf dist && vite build && cp package.json README.md LICENSE dist/",
22
+ "watch": "vite build --watch",
23
+ "pre:deploy": "npm run build && npm run docs:build",
24
+ "publish-npm": "npm run pre:deploy && npm publish",
25
+ "publish-npm:beta": "npm run pre:deploy && npm publish --tag beta",
13
26
  "test": "jest",
14
27
  "docs:dev": "vocs dev",
15
28
  "docs:build": "vocs build",
@@ -18,9 +31,6 @@
18
31
  "author": "",
19
32
  "license": "ISC",
20
33
  "devDependencies": {
21
- "@babel/core": "^7.25.2",
22
- "@babel/preset-env": "^7.25.3",
23
- "@babel/preset-typescript": "^7.24.7",
24
34
  "@types/bn.js": "^5.1.5",
25
35
  "@typescript-eslint/eslint-plugin": "^6.21.0",
26
36
  "babel-jest": "^29.7.0",
@@ -34,9 +44,9 @@
34
44
  "eslint-plugin-promise": "^6.1.1",
35
45
  "jest": "^29.7.0",
36
46
  "prettier": "^3.2.5",
37
- "ts-node": "^10.9.2",
38
- "tsc-alias": "^1.8.10",
39
47
  "typescript": "^5.4.3",
48
+ "vite": "^6.0.7",
49
+ "vite-plugin-dts": "^4.4.0",
40
50
  "vocs": "1.0.0-alpha.62"
41
51
  },
42
52
  "dependencies": {
@@ -0,0 +1,11 @@
1
+ import type { BTCTransaction, BTCInput, BTCOutput } from '@chains/Bitcoin/types'
2
+
3
+ export abstract class BTCRpcAdapter {
4
+ abstract selectUTXOs(
5
+ from: string,
6
+ targets: BTCOutput[]
7
+ ): Promise<{ inputs: BTCInput[]; outputs: BTCOutput[] }>
8
+ abstract broadcastTransaction(transactionHex: string): Promise<string>
9
+ abstract getBalance(address: string): Promise<number>
10
+ abstract getTransaction(txid: string): Promise<BTCTransaction>
11
+ }
@@ -0,0 +1,96 @@
1
+ // There is no types for coinselect
2
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3
+ // @ts-expect-error
4
+ import coinselect from 'coinselect'
5
+
6
+ import { BTCRpcAdapter } from '@chains/Bitcoin/BTCRpcAdapter/BTCRpcAdapter'
7
+ import {
8
+ type BTCFeeRecommendation,
9
+ type UTXO,
10
+ } from '@chains/Bitcoin/BTCRpcAdapter/Mempool/types'
11
+ import type { BTCTransaction, BTCInput, BTCOutput } from '@chains/Bitcoin/types'
12
+
13
+ export class Mempool extends BTCRpcAdapter {
14
+ private readonly providerUrl: string
15
+
16
+ constructor(providerUrl: string) {
17
+ super()
18
+ this.providerUrl = providerUrl
19
+ }
20
+
21
+ private async fetchFeeRate(confirmationTarget = 6): Promise<number> {
22
+ const response = await fetch(`${this.providerUrl}/v1/fees/recommended`)
23
+ const data = (await response.json()) as BTCFeeRecommendation
24
+
25
+ if (confirmationTarget <= 1) {
26
+ return data.fastestFee
27
+ } else if (confirmationTarget <= 3) {
28
+ return data.halfHourFee
29
+ } else if (confirmationTarget <= 6) {
30
+ return data.hourFee
31
+ } else {
32
+ return data.economyFee
33
+ }
34
+ }
35
+
36
+ private async fetchUTXOs(address: string): Promise<UTXO[]> {
37
+ try {
38
+ const response = await fetch(
39
+ `${this.providerUrl}/address/${address}/utxo`
40
+ )
41
+ return (await response.json()) as UTXO[]
42
+ } catch (error) {
43
+ console.error('Failed to fetch UTXOs:', error)
44
+ return []
45
+ }
46
+ }
47
+
48
+ async selectUTXOs(
49
+ from: string,
50
+ targets: BTCOutput[],
51
+ confirmationTarget = 6
52
+ ): Promise<{ inputs: BTCInput[]; outputs: BTCOutput[] }> {
53
+ const utxos = await this.fetchUTXOs(from)
54
+ const feeRate = await this.fetchFeeRate(confirmationTarget)
55
+
56
+ // Add a small amount to the fee rate to ensure the transaction is confirmed
57
+ const ret = coinselect(utxos, targets, Math.ceil(feeRate + 1))
58
+
59
+ if (!ret.inputs || !ret.outputs) {
60
+ throw new Error(
61
+ '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.'
62
+ )
63
+ }
64
+
65
+ return {
66
+ inputs: ret.inputs,
67
+ outputs: ret.outputs,
68
+ }
69
+ }
70
+
71
+ async broadcastTransaction(transactionHex: string): Promise<string> {
72
+ const response = await fetch(`${this.providerUrl}/tx`, {
73
+ method: 'POST',
74
+ body: transactionHex,
75
+ })
76
+
77
+ if (response.ok) {
78
+ return await response.text()
79
+ }
80
+
81
+ throw new Error(`Failed to broadcast transaction: ${await response.text()}`)
82
+ }
83
+
84
+ async getBalance(address: string): Promise<number> {
85
+ const response = await fetch(`${this.providerUrl}/address/${address}`)
86
+ const data = (await response.json()) as {
87
+ chain_stats: { funded_txo_sum: number; spent_txo_sum: number }
88
+ }
89
+ return data.chain_stats.funded_txo_sum - data.chain_stats.spent_txo_sum
90
+ }
91
+
92
+ async getTransaction(txid: string): Promise<BTCTransaction> {
93
+ const response = await fetch(`${this.providerUrl}/tx/${txid}`)
94
+ return (await response.json()) as BTCTransaction
95
+ }
96
+ }
@@ -0,0 +1 @@
1
+ export { Mempool } from './Mempool'
@@ -0,0 +1,72 @@
1
+ export interface BTCFeeRecommendation {
2
+ fastestFee: number
3
+ halfHourFee: number
4
+ hourFee: number
5
+ economyFee: number
6
+ minimumFee: number
7
+ }
8
+
9
+ interface BTCAddressStats {
10
+ funded_txo_count: number
11
+ funded_txo_sum: number
12
+ spent_txo_count: number
13
+ spent_txo_sum: number
14
+ tx_count: number
15
+ }
16
+
17
+ export interface BTCAddressInfo {
18
+ address: string
19
+ chain_stats: BTCAddressStats
20
+ mempool_stats: BTCAddressStats
21
+ }
22
+
23
+ export interface Transaction {
24
+ txid: string
25
+ version: number
26
+ locktime: number
27
+ vin: Array<{
28
+ txid: string
29
+ vout: number
30
+ prevout: {
31
+ scriptpubkey: string
32
+ scriptpubkey_asm: string
33
+ scriptpubkey_type: string
34
+ scriptpubkey_address: string
35
+ value: number
36
+ }
37
+ scriptsig: string
38
+ scriptsig_asm: string
39
+ witness: string[]
40
+ is_coinbase: boolean
41
+ sequence: number
42
+ }>
43
+ vout: Array<{
44
+ scriptpubkey: string
45
+ scriptpubkey_asm: string
46
+ scriptpubkey_type: string
47
+ scriptpubkey_address: string
48
+ value: number
49
+ }>
50
+ size: number
51
+ weight: number
52
+ sigops?: number
53
+ fee: number
54
+ status: {
55
+ confirmed: boolean
56
+ block_height: number
57
+ block_hash: string
58
+ block_time: number
59
+ }
60
+ }
61
+
62
+ export interface UTXO {
63
+ txid: string
64
+ vout: number
65
+ status: {
66
+ confirmed: boolean
67
+ block_height: number
68
+ block_hash: string
69
+ block_time: number
70
+ }
71
+ value: number
72
+ }
@@ -0,0 +1,6 @@
1
+ import { Mempool } from './Mempool'
2
+ export { BTCRpcAdapter } from './BTCRpcAdapter'
3
+
4
+ export const BTCRpcAdapters = {
5
+ Mempool,
6
+ }