|
| 1 | +import { Broadcaster, BroadcastFailure, BroadcastResponse, defaultHttpClient, HexString, HttpClient, HttpClientRequestOptions, Random, Transaction, Utils } from "@bsv/sdk" |
| 2 | +import { doubleSha256BE, sdk } from "../../index.client" |
| 3 | +import { error } from "console" |
| 4 | + |
| 5 | +/** Configuration options for the ARC broadcaster. */ |
| 6 | +export interface ArcConfig { |
| 7 | + /** Authentication token for the ARC API */ |
| 8 | + apiKey?: string |
| 9 | + /** The HTTP client used to make requests to the ARC API. */ |
| 10 | + httpClient?: HttpClient |
| 11 | + /** Deployment id used annotating api calls in XDeployment-ID header - this value will be randomly generated if not set */ |
| 12 | + deploymentId?: string |
| 13 | + /** notification callback endpoint for proofs and double spend notification */ |
| 14 | + callbackUrl?: string |
| 15 | + /** default access token for notification callback endpoint. It will be used as a Authorization header for the http callback */ |
| 16 | + callbackToken?: string |
| 17 | + /** additional headers to be attached to all tx submissions. */ |
| 18 | + headers?: Record<string, string> |
| 19 | +} |
| 20 | + |
| 21 | +function defaultDeploymentId(): string { |
| 22 | + return `ts-sdk-${Utils.toHex(Random(16))}` |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * Represents an ARC transaction broadcaster. |
| 27 | + */ |
| 28 | +export default class ARC { |
| 29 | + readonly URL: string |
| 30 | + readonly apiKey: string | undefined |
| 31 | + readonly deploymentId: string |
| 32 | + readonly callbackUrl: string | undefined |
| 33 | + readonly callbackToken: string | undefined |
| 34 | + readonly headers: Record<string, string> | undefined |
| 35 | + private readonly httpClient: HttpClient |
| 36 | + |
| 37 | + /** |
| 38 | + * Constructs an instance of the ARC broadcaster. |
| 39 | + * |
| 40 | + * @param {string} URL - The URL endpoint for the ARC API. |
| 41 | + * @param {ArcConfig} config - Configuration options for the ARC broadcaster. |
| 42 | + */ |
| 43 | + constructor(URL: string, config?: ArcConfig) |
| 44 | + /** |
| 45 | + * Constructs an instance of the ARC broadcaster. |
| 46 | + * |
| 47 | + * @param {string} URL - The URL endpoint for the ARC API. |
| 48 | + * @param {string} apiKey - The API key used for authorization with the ARC API. |
| 49 | + */ |
| 50 | + constructor(URL: string, apiKey?: string) |
| 51 | + |
| 52 | + constructor(URL: string, config?: string | ArcConfig) { |
| 53 | + this.URL = URL |
| 54 | + if (typeof config === 'string') { |
| 55 | + this.apiKey = config |
| 56 | + this.httpClient = defaultHttpClient() |
| 57 | + this.deploymentId = defaultDeploymentId() |
| 58 | + this.callbackToken = undefined |
| 59 | + this.callbackUrl = undefined |
| 60 | + } else { |
| 61 | + const configObj: ArcConfig = config ?? {} |
| 62 | + const { |
| 63 | + apiKey, |
| 64 | + deploymentId, |
| 65 | + httpClient, |
| 66 | + callbackToken, |
| 67 | + callbackUrl, |
| 68 | + headers |
| 69 | + } = configObj |
| 70 | + this.apiKey = apiKey |
| 71 | + this.httpClient = httpClient ?? defaultHttpClient() |
| 72 | + this.deploymentId = deploymentId ?? defaultDeploymentId() |
| 73 | + this.callbackToken = callbackToken |
| 74 | + this.callbackUrl = callbackUrl |
| 75 | + this.headers = headers |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + /** |
| 80 | + * Constructs a dictionary of the default & supplied request headers. |
| 81 | + */ |
| 82 | + private requestHeaders(): Record<string, string> { |
| 83 | + const headers: Record<string, string> = { |
| 84 | + 'Content-Type': 'application/json', |
| 85 | + 'XDeployment-ID': this.deploymentId |
| 86 | + } |
| 87 | + |
| 88 | + if (this.apiKey != null && this.apiKey !== '') { |
| 89 | + headers.Authorization = `Bearer ${this.apiKey}` |
| 90 | + } |
| 91 | + |
| 92 | + if (this.callbackUrl != null && this.callbackUrl !== '') { |
| 93 | + headers['X-CallbackUrl'] = this.callbackUrl |
| 94 | + } |
| 95 | + |
| 96 | + if (this.callbackToken != null && this.callbackToken !== '') { |
| 97 | + headers['X-CallbackToken'] = this.callbackToken |
| 98 | + } |
| 99 | + |
| 100 | + if (this.headers != null) { |
| 101 | + for (const key in this.headers) { |
| 102 | + headers[key] = this.headers[key] |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + return headers |
| 107 | + } |
| 108 | + |
| 109 | + async postRawTx(rawTx: HexString): Promise<sdk.PostTxResultForTxid> { |
| 110 | + |
| 111 | + const txid = Utils.toHex(doubleSha256BE(Utils.toArray(rawTx, 'hex'))) |
| 112 | + |
| 113 | + const requestOptions: HttpClientRequestOptions = { |
| 114 | + method: 'POST', |
| 115 | + headers: this.requestHeaders(), |
| 116 | + data: { rawTx } |
| 117 | + } |
| 118 | + |
| 119 | + const r: sdk.PostTxResultForTxid = { |
| 120 | + txid, |
| 121 | + status: "success" |
| 122 | + } |
| 123 | + |
| 124 | + try { |
| 125 | + |
| 126 | + const response = await this.httpClient.request<ArcResponse>( |
| 127 | + `${this.URL}/v1/tx`, |
| 128 | + requestOptions |
| 129 | + ) |
| 130 | + |
| 131 | + if (response.ok) { |
| 132 | + const { txid, extraInfo, txStatus, competingTxs } = response.data |
| 133 | + r.data = `${txStatus} ${extraInfo}` |
| 134 | + if (r.txid !== txid) r.data += ` txid altered from ${r.txid} to ${txid}` |
| 135 | + r.txid = txid |
| 136 | + if (txStatus === 'DOUBLE_SPEND_ATTEMPTED') { |
| 137 | + r.status = 'error' |
| 138 | + r.doubleSpend = true |
| 139 | + r.competingTxs = competingTxs |
| 140 | + } |
| 141 | + } else { |
| 142 | + |
| 143 | + r.status = 'error' |
| 144 | + const ed: sdk.PostTxResultForTxidError = {} |
| 145 | + r.data = ed |
| 146 | + const st = typeof response.status |
| 147 | + ed.status = st === 'number' || st === 'string' ? response.status.toString() : 'ERR_UNKNOWN' |
| 148 | + |
| 149 | + let d = response.data |
| 150 | + if (d && typeof d === 'string') { |
| 151 | + try { |
| 152 | + d = JSON.parse(d) |
| 153 | + } catch { |
| 154 | + // Intentionally left empty |
| 155 | + } |
| 156 | + } |
| 157 | + if (d && typeof d === 'object') { |
| 158 | + ed.more = d |
| 159 | + ed.detail = d['detail'] |
| 160 | + if (typeof ed.detail !== 'string') ed.detail = undefined |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + } catch (eu: unknown) { |
| 165 | + const e = sdk.WalletError.fromUnknown(eu) |
| 166 | + r.status = 'error' |
| 167 | + r.data = `${e.code} ${e.message}` |
| 168 | + } |
| 169 | + |
| 170 | + return r |
| 171 | + } |
| 172 | + |
| 173 | + /** |
| 174 | + * Broadcasts multiple transactions via ARC. |
| 175 | + * Handles mixed responses where some transactions succeed and others fail. |
| 176 | + * |
| 177 | + * @param {Transaction[]} txs - Array of transactions to be broadcasted. |
| 178 | + * @returns {Promise<Array<object>>} A promise that resolves to an array of objects. |
| 179 | + */ |
| 180 | + async broadcastMany(txs: Transaction[]): Promise<object[]> { |
| 181 | + const rawTxs = txs.map((tx) => { |
| 182 | + try { |
| 183 | + return { rawTx: tx.toHexEF() } |
| 184 | + } catch (eu: unknown) { |
| 185 | + const e = sdk.WalletError.fromUnknown(eu) |
| 186 | + if ( |
| 187 | + e.message === |
| 188 | + 'All inputs must have source transactions when serializing to EF format' |
| 189 | + ) { |
| 190 | + return { rawTx: tx.toHex() } |
| 191 | + } |
| 192 | + throw eu |
| 193 | + } |
| 194 | + }) |
| 195 | + |
| 196 | + const requestOptions: HttpClientRequestOptions = { |
| 197 | + method: 'POST', |
| 198 | + headers: this.requestHeaders(), |
| 199 | + data: rawTxs |
| 200 | + } |
| 201 | + |
| 202 | + try { |
| 203 | + const response = await this.httpClient.request<object[]>( |
| 204 | + `${this.URL}/v1/txs`, |
| 205 | + requestOptions |
| 206 | + ) |
| 207 | + |
| 208 | + return response.data as object[] |
| 209 | + } catch (eu: unknown) { |
| 210 | + const e = sdk.WalletError.fromUnknown(eu) |
| 211 | + const errorResponse: BroadcastFailure = { |
| 212 | + status: 'error', |
| 213 | + code: '500', |
| 214 | + description: typeof e.message === 'string' ? e.message : 'Internal Server Error' |
| 215 | + } |
| 216 | + return txs.map(() => errorResponse) |
| 217 | + } |
| 218 | + } |
| 219 | +} |
| 220 | + |
| 221 | +interface ArcResponse { |
| 222 | + txid: string |
| 223 | + extraInfo: string |
| 224 | + txStatus: string |
| 225 | + competingTxs?: string[] |
| 226 | +} |
0 commit comments