### Install BSV SDK Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/src/identity/README.md Installs the @bsv/sdk package using npm, providing access to the IdentityClient and other functionalities. ```bash npm install @bsv/sdk ``` -------------------------------- ### Multiple Doubling of JacobianPoint Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Example demonstrating multiple doublings of a JacobianPoint instance using the 'dblp' method. ```ts const jp = new JacobianPoint(x, y, z) const result = jp.dblp(3) ``` -------------------------------- ### Double JacobianPoint Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Example demonstrating the doubling of a JacobianPoint instance using the 'dbl' method. ```ts const jp = new JacobianPoint(x, y, z) const result = jp.dbl() ``` -------------------------------- ### TypeScript: fromCompact Method Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Example demonstrating how to create a Signature instance by decoding a Compact-encoded hexadecimal string. ```ts const signature = Signature.fromCompact('1b18c1f5502f8...', 'hex'); ``` -------------------------------- ### Add JacobianPoints Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Example demonstrating the addition of two JacobianPoint instances using the 'add' method. ```ts const p1 = new JacobianPoint(x1, y1, z1) const p2 = new JacobianPoint(x2, y2, z2) const result = p1.add(p2) ``` -------------------------------- ### Compare JacobianPoints Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Example demonstrating the equality check between two JacobianPoint instances using the 'eq' method. ```ts const jp1 = new JacobianPoint(x1, y1, z1) const jp2 = new JacobianPoint(x2, y2, z2) const areEqual = jp1.eq(jp2) ``` -------------------------------- ### Example: Initializing PrivateKey Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to initialize a `PrivateKey` instance using a `BigNumber` object, illustrating the typical usage of the constructor. ```typescript import PrivateKey from './PrivateKey'; import BigNumber from './BigNumber'; const privKey = new PrivateKey(new BigNumber('123456', 10, 'be')); ``` -------------------------------- ### Example: Generating SymmetricKey from Random Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to generate a new `SymmetricKey` instance using the static `fromRandom` method. ```ts const symmetricKey = SymmetricKey.fromRandom(); ``` -------------------------------- ### TS SDK: Example Script from Binary Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/script.md Demonstrates how to create a Script instance from a binary array using the `fromBinary` static method. ```typescript const script = Script.fromBinary([0x76, 0xa9, ...]) ``` -------------------------------- ### TypeScript: Signature Class Constructor Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Example demonstrating how to create a new Signature instance by providing BigNumber objects for the R and S components. ```ts const r = new BigNumber('208755674028...'); const s = new BigNumber('564745627577...'); const signature = new Signature(r, s); ``` -------------------------------- ### TS SDK: Example Script from ASM Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/script.md Demonstrates how to create a Script instance from an ASM string using the `fromASM` static method. ```typescript const script = Script.fromASM("OP_DUP OP_HASH160 abcd... OP_EQUALVERIFY OP_CHECKSIG") ``` -------------------------------- ### SHA512HMAC Constructor Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Example demonstrating how to create a new instance of the SHA512HMAC class using a hexadecimal string key. ```ts const myHMAC = new SHA512HMAC('deadbeef'); ``` -------------------------------- ### TS SDK: Example Script from Hex Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/script.md Demonstrates how to create a Script instance from a hexadecimal string using the `fromHex` static method. ```typescript const script = Script.fromHex("76a9..."); ``` -------------------------------- ### Example: Reconstruct PrivateKey from Backup Shares Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Illustrates how to use two backup shares to reconstruct the original PrivateKey instance. ```ts const share1 = '3znuzt7DZp8HzZTfTh5MF9YQKNX3oSxTbSYmSRGrH2ev.2Nm17qoocmoAhBTCs8TEBxNXCskV9N41rB2PckcgYeqV.2.35449bb9' const share2 = 'Cm5fuUc39X5xgdedao8Pr1kvCSm8Gk7Cfenc7xUKcfLX.2juyK9BxCWn2DiY5JUAgj9NsQ77cc9bWksFyW45haXZm.2.35449bb9' const recoveredKey = PrivateKey.fromBackupShares([share1, share2]) ``` -------------------------------- ### Install BSV SDK using npm Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/README.md This command installs the BSV SDK package from npm, making it available for use in your JavaScript or TypeScript projects. It's the first step to integrate the SDK into your development environment. ```bash npm install @bsv/sdk ``` -------------------------------- ### Example: Convert Number from Montgomery Domain Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to use the `convertFrom` method to convert a number from the Montgomery domain after initializing the `MontgomoryMethod`. ```typescript const montMethod = new MontgomoryMethod(m); const convertedNum = montMethod.convertFrom(num); ``` -------------------------------- ### Example: Sign a Message with PrivateKey Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to generate a random private key and use it to sign a simple string message. ```ts const privateKey = PrivateKey.fromRandom(); const signature = privateKey.sign('Hello, World!'); ``` -------------------------------- ### Example: Encrypting with SymmetricKey Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to use the `encrypt` method of the `SymmetricKey` class to encrypt a plaintext message. ```ts const key = new SymmetricKey(1234); const encryptedMessage = key.encrypt('plainText', 'utf8'); ``` -------------------------------- ### Example: Generate Random PrivateKey Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Shows how to create a new PrivateKey instance by generating it randomly. ```ts const privateKey = PrivateKey.fromRandom(); ``` -------------------------------- ### Example: Convert Number to Montgomery Domain Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to use the `convertTo` method to convert a number into the Montgomery domain after initializing the `MontgomoryMethod`. ```typescript const montMethod = new MontgomoryMethod(m); const convertedNum = montMethod.convertTo(num); ``` -------------------------------- ### Install Node.js Dependencies for BSV SDK Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/CONTRIBUTING.md Installs project dependencies using npm, ensuring all tooling is up to date for the BSV SDK TypeScript project. ```Shell npm install ``` -------------------------------- ### TypeScript: RecoverPublicKey Method Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Example demonstrating how to recover a public key from a signature using a recovery factor and message hash. ```ts const publicKey = signature.RecoverPublicKey(0, msgHash); ``` -------------------------------- ### Install Dependencies for Bitcoin SV TS SDK Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/README.md This command installs all necessary Node.js dependencies for the Bitcoin SV TypeScript SDK project, ensuring the development environment is set up correctly by fetching packages listed in `package.json`. ```shell npm install ``` -------------------------------- ### Example of Spend Class Instantiation Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/script.md Demonstrates how to create an instance of the `Spend` class using its constructor, providing concrete values for all required parameters such as transaction IDs, script details, and satoshi amounts. ```typescript const spend = new Spend({ sourceTXID: "abcd1234", // sourceTXID sourceOutputIndex: 0, // sourceOutputIndex sourceSatoshis: new BigNumber(1000), // sourceSatoshis lockingScript: LockingScript.fromASM("OP_DUP OP_HASH160 abcd1234... OP_EQUALVERIFY OP_CHECKSIG"), transactionVersion: 1, // transactionVersion otherInputs: [{ sourceTXID: "abcd1234", sourceOutputIndex: 1, sequence: 0xffffffff }], // otherInputs outputs: [{ satoshis: new BigNumber(500), lockingScript: LockingScript.fromASM("OP_DUP...") }], // outputs inputIndex: 0, // inputIndex unlockingScript: UnlockingScript.fromASM("3045... 02ab..."), inputSequence: 0xffffffff // inputSequence memoryLimit: 100000 // memoryLimit }); ``` -------------------------------- ### Example: Perform Montgomery Multiplication Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to use the `mul` method to perform a multiplication of two numbers in the Montgomery domain. ```typescript const montMethod = new MontgomoryMethod(m); const product = montMethod.mul(a, b); ``` -------------------------------- ### Example: Convert Bytes to Base64 Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to use the `toBase64` function to convert a byte array representing 'Hello' into its base64 encoded string. ```ts const bytes = [72, 101, 108, 108, 111]; // Represents the string "Hello" console.log(toBase64(bytes)); // Outputs: SGVsbG8= ``` -------------------------------- ### Create and Sign BSV Transaction with SDK Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/README.md This example demonstrates how to create, sign, and broadcast a basic P2PKH transaction using the BSV SDK. It involves importing necessary modules, initializing a private key, defining transaction inputs and outputs, calculating fees, signing the transaction, and broadcasting it to the network. ```javascript import { PrivateKey, P2PKH, Transaction, ARC } from '@bsv/sdk' const privKey = PrivateKey.fromWif('L5EY1SbTvvPNSdCYQe1EJHfXCBBT4PmnF6CDbzCm9iifZptUvDGB') const sourceTransaction = Transaction.fromHex('0200000001849c6419aec8b65d747cb72282cc02f3fc26dd018b46962f5de48957fac50528020000006a473044022008a60c611f3b48eaf0d07b5425d75f6ce65c3730bd43e6208560648081f9661b0220278fa51877100054d0d08e38e069b0afdb4f0f9d38844c68ee2233ace8e0de2141210360cd30f72e805be1f00d53f9ccd47dfd249cbb65b0d4aee5cfaf005a5258be37ffffffff03d0070000000000001976a914acc4d7c37bc9d0be0a4987483058a2d842f2265d88ac75330100000000001976a914db5b7964eecb19fcab929bf6bd29297ec005d52988ac809f7c09000000001976a914c0b0a42e92f062bdbc6a881b1777eed1213c19eb88ac00000000') const version = 1 const input = { sourceTransaction, sourceOutputIndex: 0, unlockingScriptTemplate: new P2PKH().unlock(privKey), } const output = { lockingScript: new P2PKH().lock(privKey.toAddress()), change: true } const tx = new Transaction(version, [input], [output]) await tx.fee() await tx.sign() await tx.broadcast() ``` -------------------------------- ### TypeScript: CalculateRecoveryFactor Method Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Example demonstrating how to calculate the recovery factor for a signature using a public key and message hash. ```ts const recovery = signature.CalculateRecoveryFactor(publicKey, msgHash); ``` -------------------------------- ### Example: Calculate Modular Multiplicative Inverse Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to use the `invm` method to compute the modular multiplicative inverse of a number in the Montgomery domain. ```typescript const montMethod = new MontgomoryMethod(m); const inverse = montMethod.invm(a); ``` -------------------------------- ### TypeScript: Example for BigNumber.toHex Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to convert a BigNumber instance to a hexadecimal string. ```ts const bigNumber = new BigNumber(255) const hex = bigNumber.toHex() ``` -------------------------------- ### Example: Perform In-Place Montgomery Multiplication Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to use the `imul` method to perform an in-place multiplication of two numbers in the Montgomery domain. ```typescript const montMethod = new MontgomoryMethod(m); const product = montMethod.imul(a, b); ``` -------------------------------- ### Example: Verify Transaction with WhatsOnChain and SatoshisPerKilobyte (TypeScript) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/transaction.md Demonstrates how to call the `verify` method on a transaction `tx` using a `WhatsOnChain` instance for chain tracking and a `SatoshisPerKilobyte` instance for fee modeling. ```ts tx.verify(new WhatsOnChain(), new SatoshisPerKilobyte(1)) ``` -------------------------------- ### Schnorr Class for Zero-Knowledge Proofs Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md The Schnorr class implements the Schnorr Zero-Knowledge Proof (ZKP) protocol, enabling a party to prove knowledge of a private key and a shared secret without revealing them. This example demonstrates generating and verifying a proof. ```typescript const schnorr = new Schnorr(); const a = PrivateKey.fromRandom(); // Prover's private key const A = a.toPublicKey(); // Prover's public key const b = PrivateKey.fromRandom(); // Other party's private key const B = b.toPublicKey(); // Other party's public key const S = B.mul(a); // Shared secret // Prover generates the proof const proof = schnorr.generateProof(a, A, B, S); // Verifier verifies the proof const isValid = schnorr.verifyProof(A.point, B.point, S.point, proof); console.log(`Proof is valid: ${isValid}`); ``` -------------------------------- ### Class: Polynomial Overview and Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Describes the `Polynomial` class, used for creating polynomials with a given threshold and private key. These polynomials are essential for generating shares of a private key, often in secret sharing schemes. The example demonstrates how to instantiate a Polynomial object. ```typescript const key = new PrivateKey() const threshold = 2 const polynomial = new Polynomial(key, threshold) ``` -------------------------------- ### Instantiate SHA512 Class Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Provides a simple example of how to create a new instance of the SHA512 cryptographic hash function class. This prepares the object for subsequent hashing operations. ```ts const sha512 = new SHA512(); ``` -------------------------------- ### Example: Derive Shared Secret with PrivateKey Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to generate a random private key, derive its public key, and then use the private key to derive a shared secret from its own public key. ```ts const privateKey = PrivateKey.fromRandom(); const publicKey = privateKey.toPublicKey(); const sharedSecret = privateKey.deriveSharedSecret(publicKey); ``` -------------------------------- ### TypeScript: Example for BigNumber.zeroBits Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to get the number of trailing zero bits from a BigNumber instance. ```ts const bn = new BigNumber('8'); // binary: 1000 const zeroBits = bn.zeroBits(); // 3 ``` -------------------------------- ### SHA512HMAC Update Method Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Example of updating the SHA512HMAC object with a message part, specifying hexadecimal encoding. ```ts myHMAC.update('deadbeef', 'hex'); ``` -------------------------------- ### Instantiate SHA256HMAC Class with Hex Key Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to create a new instance of the SHA256HMAC class. The example uses a hexadecimal string 'deadbeef' as the cryptographic key for initialization. ```ts const myHMAC = new SHA256HMAC('deadbeef'); ``` -------------------------------- ### SHA512HMAC Digest Method Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Example of calling the `digest` method to retrieve the final HMAC hash as a number array. ```ts let hashedMessage = myHMAC.digest(); ``` -------------------------------- ### SHA512HMAC Digest Hex Method Example Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Example of calling the `digestHex` method to retrieve the final HMAC hash as a hexadecimal string. ```ts let hashedMessage = myHMAC.digestHex(); ``` -------------------------------- ### LocalKVStore API Reference Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/kvstore.md Detailed API documentation for the LocalKVStore class, including its constructor, methods, parameters, return types, and exceptions. ```APIDOC Class: LocalKVStore Description: Implements a key-value storage system backed by transaction outputs managed by a wallet. Each key-value pair is represented by a PushDrop token output in a specific context (basket). Allows setting, getting, and removing key-value pairs, with optional encryption. Constructor: Signature: constructor(wallet: WalletInterface = new WalletClient(), context = "kvstore default", encrypt = true, originator?: string) Description: Creates an instance of the localKVStore. Arguments: wallet: Type: WalletInterface Default: new WalletClient() Description: The wallet interface to use. Defaults to a new WalletClient instance. context: Type: string Default: "kvstore default" Description: The context (basket) for namespacing keys. Defaults to 'kvstore default'. encrypt: Type: boolean Default: true Description: Whether to encrypt values. Defaults to true. originator: Type: string | undefined Description: An originator to use with PushDrop and the wallet, if provided. Throws: If the context is missing or empty. Method: get Signature: async get(key: string, defaultValue: string | undefined = undefined): Promise Description: Retrieves the value associated with a given key. Arguments: key: Type: string Description: The key to retrieve the value for. defaultValue: Type: string | undefined Default: undefined Description: The value to return if the key is not found. Returns: A promise that resolves to the value as a string, the defaultValue if the key is not found, or undefined if no defaultValue is provided. Throws: - If too many outputs are found for the key (ambiguous state). - If the found output's locking script cannot be decoded or represents an invalid token format. Method: remove Signature: async remove(key: string): Promise Description: Removes the key-value pair associated with the given key. It finds the existing output(s) for the key and spends them without creating a new output. If multiple outputs exist, they are all spent in the same transaction. If the key does not exist, it does nothing. If signing the removal transaction fails, it relinquishes the original outputs instead of spending. Arguments: key: Type: string Description: The key to remove. Returns: A promise that resolves to the txids of the removal transactions if successful. Method: set Signature: async set(key: string, value: string): Promise Description: Sets or updates the value associated with a given key. If the key already exists (one or more outputs found), it spends the existing output(s) and creates a new one with the updated value. If multiple outputs exist for the key, they are collapsed into a single new output. If the key does not exist, it creates a new output. Handles encryption if enabled. If signing the update/collapse transaction fails, it relinquishes the original outputs and starts over with a new chain. Arguments: key: Type: string Description: The key to set or update. value: Type: string Description: The value to associate with the key. Returns: A promise that resolves to the outpoint string (txid.vout) of the new or updated token output. ``` -------------------------------- ### AuthFetch Constructor API Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/auth.md API documentation for the `AuthFetch` class constructor. ```APIDOC AuthFetch.constructor(wallet: WalletInterface, requestedCertificates?: RequestedCertificateSet, sessionManager?: SessionManager) wallet: WalletInterface - The wallet instance for signing and authentication. requestedCertificates?: RequestedCertificateSet - Optional set of certificates to request from peers. ``` -------------------------------- ### Get Verifiable Certificates (TypeScript) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/auth.md This asynchronous variable/function retrieves verifiable certificates from a wallet based on requested certifiers and types. It filters matching certificates, proves them with the wallet to get the keyring for the verifier, and constructs VerifiableCertificate instances. ```ts getVerifiableCertificates = async (wallet: WalletInterface, requestedCertificates: RequestedCertificateSet, verifierIdentityKey: string): Promise => { const matchingCertificates = await wallet.listCertificates({ certifiers: requestedCertificates.certifiers, types: Object.keys(requestedCertificates.types) }); return await Promise.all(matchingCertificates.certificates.map(async (certificate) => { const { keyringForVerifier } = await wallet.proveCertificate({ certificate, fieldsToReveal: requestedCertificates.types[certificate.type], verifier: verifierIdentityKey }); return new VerifiableCertificate(certificate.type, certificate.serialNumber, certificate.subject, certificate.certifier, certificate.revocationOutpoint, certificate.fields, keyringForVerifier, certificate.signature); })); } ``` -------------------------------- ### TypeScript Interface: AdmittanceInstructions Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/overlay-tools.md Defines instructions for the Overlay Services Engine about which outputs to admit and which previous outputs to retain. This interface is typically returned by a Topic Manager. ```ts export interface AdmittanceInstructions { outputsToAdmit: number[]; coinsToRetain: number[]; coinsRemoved?: number[]; } ``` ```APIDOC coinsRemoved?: number[] The indices of all inputs from the provided transaction which reference previously-admitted outputs, which are now considered spent and have been removed from the managed topic. ``` ```APIDOC coinsToRetain: number[] The indices of all inputs from the provided transaction which spend previously-admitted outputs that should be retained for historical record-keeping. ``` ```APIDOC outputsToAdmit: number[] The indices of all admissible outputs into the managed topic from the provided transaction. ``` -------------------------------- ### Get Y Coordinate of Point (TypeScript) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Returns the Y coordinate of the Point instance as a BigNumber. ```APIDOC Method: getY Signature: getY(): BigNumber Returns: Y coordinate of point ``` ```ts const P = new Point('123', '456'); const x = P.getX(); ``` -------------------------------- ### Get X Coordinate of Point (TypeScript) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Returns the X coordinate of the Point instance as a BigNumber. ```APIDOC Method: getX Signature: getX(): BigNumber Returns: X coordinate of point ``` ```ts const P = new Point('123', '456'); const x = P.getX(); ``` -------------------------------- ### HD.fromBinary Instance Method Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/compat.md Initializes the current HD wallet instance from a binary buffer. Parses the buffer to set up the wallet's properties. ```APIDOC public fromBinary(buf: number[]): this buf: number[] - A buffer containing the wallet data. Returns: this - The current instance with properties set from the buffer. ``` -------------------------------- ### Get Height (TypeScript API) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/wallet.md Retrieves the current height. The return type is incomplete in the provided snippet. ```APIDOC getHeight(args: {}): Promise<{ ``` -------------------------------- ### Get Modulus Bit Length Property (shift) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Represents the number of bits in the modulus. This property is a `number`. ```APIDOC shift: number description: The number of bits in the modulus. ``` -------------------------------- ### Get Square of Shifted Modulus Property (r2) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Represents the square of `r` modulo `m`. This property is a `BigNumber`. ```APIDOC r2: BigNumber description: The square of 'r' modulo 'm'. ``` -------------------------------- ### HD.fromBinary Static Method Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/compat.md Initializes a new HD wallet instance from a binary buffer. Parses the buffer to set up the wallet's properties. ```APIDOC public static fromBinary(buf: number[]): HD buf: number[] - A buffer containing the wallet data. Returns: HD - The new instance with properties set from the buffer. ``` -------------------------------- ### Initialize MontgomoryMethod Class Constructor Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Initializes a new instance of the `MontgomoryMethod` class. It takes a modulus `m` which can be a `BigNumber` or the string 'k256' to set up the Montgomery method reductions. ```APIDOC constructor(m: BigNumber | "k256") m: The modulus to be used for the Montgomery method reductions. ``` -------------------------------- ### OverlayAdminTokenTemplate Constructor API Documentation Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/overlay-tools.md API documentation for the constructor of the `OverlayAdminTokenTemplate` class. It initializes a new instance, requiring a wallet for subsequent locking and unlocking operations. ```APIDOC OverlayAdminTokenTemplate: constructor(wallet: WalletInterface) wallet: Wallet to use for locking and unlocking ``` -------------------------------- ### Initialize IdentityClient Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/src/identity/README.md Imports the IdentityClient class from the @bsv/sdk and creates a new instance for interacting with identity services. ```typescript import { IdentityClient } from '@bsv/sdk' const identityClient = new IdentityClient() ``` -------------------------------- ### Get Shifted Modulus Property (r) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Represents `2^shift`, shifted left by the bit length of modulus `m`. This property is a `BigNumber`. ```APIDOC r: BigNumber description: The 2^shift, shifted left by the bit length of modulus 'm'. ``` -------------------------------- ### Certificate Constructor API Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/auth.md API documentation for the `Certificate` class constructor, detailing parameters for creating a new identity certificate. ```APIDOC Certificate.constructor(type: Base64String, serialNumber: Base64String, subject: PubKeyHex, certifier: PubKeyHex, revocationOutpoint: OutpointString, fields: Record, signature?: HexString) type: Base64String - Type identifier for the certificate, base64 encoded string, 32 bytes. serialNumber: Base64String - Unique serial number of the certificate, base64 encoded string, 32 bytes. subject: PubKeyHex - The public key belonging to the certificate's subject, compressed public key hex string. certifier: PubKeyHex - Public key of the certifier who issued the certificate, compressed public key hex string. revocationOutpoint: OutpointString - The outpoint used to confirm that the certificate has not been revoked (TXID.OutputIndex), as a string. fields: Record - All the fields present in the certificate. signature?: HexString - Certificate signature by the certifier's private key, DER encoded hex string. ``` -------------------------------- ### Get Modular Multiplicative Inverse Property (minv) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Represents the modular multiplicative inverse of `m` modulo `r`. This property is a `BigNumber`. ```APIDOC minv: BigNumber description: The modular multiplicative inverse of 'm' mod 'r'. ``` -------------------------------- ### Generate Project Documentation for BSV SDK Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/CONTRIBUTING.md Generates or updates project documentation for the BSV SDK, a required step to ensure documentation is current before creating a pull request. ```Shell npm run doc ``` -------------------------------- ### Interface: SHIPBroadcasterConfig Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/overlay-tools.md Configuration options for the SHIP broadcaster. This interface defines various settings for network presets, facilitators, resolvers, and acknowledgment requirements from hosts for broadcast success. ```ts export interface SHIPBroadcasterConfig { networkPreset?: "mainnet" | "testnet" | "local"; facilitator?: OverlayBroadcastFacilitator; resolver?: LookupResolver; requireAcknowledgmentFromAllHostsForTopics?: "all" | "any" | string[]; requireAcknowledgmentFromAnyHostForTopics?: "all" | "any" | string[]; requireAcknowledgmentFromSpecificHostsForTopics?: Record; } ``` -------------------------------- ### Method: PrivateKey Constructor Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Documents the constructor for the `PrivateKey` class, detailing its parameters (`number`, `base`, `endian`, `modN`) and their purpose in initializing a private key. It supports various input types and base conversions, with options for field validation. ```APIDOC constructor(number: BigNumber | number | string | number[] = 0, base: number | "be" | "le" | "hex" = 10, endian: "be" | "le" = "be", modN: "apply" | "nocheck" | "error" = "apply") Argument Details + **number** + The number (various types accepted) to construct a BigNumber from. Default is 0. + **base** + The base of number provided. By default is 10. Ignored if number is BigNumber. + **endian** + The endianness provided. By default is 'big endian'. Ignored if number is BigNumber. + **modN** + Optional. Default 'apply. If 'apply', apply modN to input to guarantee a valid PrivateKey. If 'error', if input is out of field throw new Error('Input is out of field'). If 'nocheck', assumes input is in field. ``` -------------------------------- ### Get Version API Method Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/wallet.md Asynchronously retrieves the version of the SDK or underlying protocol. This method returns a string representing the version. ```APIDOC getVersion(args: object, originator?: OriginatorDomainNameStringUnder250Bytes): Promise args: {} originator?: OriginatorDomainNameStringUnder250Bytes Returns: version: VersionString7To30Bytes ``` -------------------------------- ### Instantiate JacobianPoint Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to create new instances of the JacobianPoint class using various constructor arguments, including null for infinity points or hex strings for coordinates. ```ts const pointJ = new JacobianPoint('3', '4', '1'); ``` ```ts const pointJ1 = new JacobianPoint(null, null, null); // creates point at infinity const pointJ2 = new JacobianPoint('3', '4', '1'); // creates point (3, 4, 1) ``` -------------------------------- ### Get Height API Method Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/wallet.md Asynchronously retrieves the current block height of the blockchain. This method provides the latest block number. ```APIDOC getHeight(args: object, originator?: OriginatorDomainNameStringUnder250Bytes): Promise args: {} originator?: OriginatorDomainNameStringUnder250Bytes Returns: height: PositiveInteger ``` -------------------------------- ### Navigate to BSV SDK Directory Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/CONTRIBUTING.md Command to change the current directory to the newly cloned BSV SDK repository. ```Shell cd bsv-sdk ``` -------------------------------- ### Get Default ChainTracker Function (TypeScript) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/transaction.md Returns a default `ChainTracker` instance, which can be used for tracking Bitcoin block headers. ```ts export function defaultChainTracker(): ChainTracker ``` -------------------------------- ### Property: SHIPBroadcasterConfig.networkPreset Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/overlay-tools.md The network preset to use, unless other options override it. Options include 'mainnet', 'testnet', and 'local', each configuring the resolver and facilitator appropriately. ```ts networkPreset?: "mainnet" | "testnet" | "local" ``` -------------------------------- ### Method getFee - Get current transaction fee Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/transaction.md Utility method that returns the current fee based on inputs and outputs ```APIDOC Method: getFee Signature: getFee(): number Description: Utility method that returns the current fee based on inputs and outputs. Returns: The current transaction fee ``` -------------------------------- ### Get Modular Multiplicative Inverse of r Property (rinv) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Represents the modular multiplicative inverse of `r` modulo `m`. This property is a `BigNumber`. ```APIDOC rinv: BigNumber description: The modular multiplicative inverse of 'r' mod 'm'. ``` -------------------------------- ### Interface: CreateActionArgs Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/wallet.md Defines the arguments for creating an action, encompassing a description, optional input/output BEEF, labels, and action-specific options. ```APIDOC Interface: CreateActionArgs Properties: description: DescriptionString5to50Bytes inputBEEF?: BEEF inputs?: CreateActionInput[] outputs?: CreateActionOutput[] lockTime?: PositiveIntegerOrZero version?: PositiveIntegerOrZero labels?: LabelStringUnder300Bytes[] options?: CreateActionOptions ``` -------------------------------- ### JacobianPoint Constructor API Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Documents the constructor for the JacobianPoint class, detailing its parameters and their behavior, including default values and type conversions. ```APIDOC JacobianPoint.constructor(x: string | BigNumber | null, y: string | BigNumber | null, z: string | BigNumber | null) Parameters: x: string | BigNumber | null - If null, the x-coordinate will default to the curve's defined 'one' constant. If x is not a BigNumber, x will be converted to a BigNumber assuming it is a hex string. y: string | BigNumber | null - If null, the y-coordinate will default to the curve's defined 'one' constant. If y is not a BigNumber, y will be converted to a BigNumber assuming it is a hex string. z: string | BigNumber | null - If null, the z-coordinate will default to 0. If z is not a BigNumber, z will be converted to a BigNumber assuming it is a hex string. ``` -------------------------------- ### Get Network API Method Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/wallet.md Asynchronously retrieves the current network the SDK is connected to. This method indicates whether it's 'mainnet' or 'testnet'. ```APIDOC getNetwork(args: object, originator?: OriginatorDomainNameStringUnder250Bytes): Promise args: {} originator?: OriginatorDomainNameStringUnder250Bytes Returns: network: "mainnet" | "testnet" ``` -------------------------------- ### TS SDK: Script fromASM Static Method Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/script.md Creates a new Script instance from an ASM string format. ```APIDOC Method: fromASM Signature: static fromASM(asm: string): Script Description: Creates a new Script instance from an ASM string format. Parameters: asm: string - The script in ASM string format. Returns: Script - A new Script instance. ``` -------------------------------- ### Get Height (TS SDK API) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/wallet.md Retrieves the current block height. (Note: The return type is not fully specified in the provided snippet). ```APIDOC getHeight(args: {}): Promise<{ ``` -------------------------------- ### Interface: WhatsOnChainConfig Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/transaction.md Configuration options for the WhatsOnChain ChainTracker. This interface defines properties for API key and HTTP client configuration. ```ts export interface WhatsOnChainConfig { apiKey?: string; httpClient?: HttpClient; } ``` ```APIDOC WhatsOnChainConfig Properties: apiKey: Description: Authentication token for the WhatsOnChain API Type: string httpClient: Description: The HTTP client used to make requests to the API. Type: HttpClient ``` -------------------------------- ### Clone BSV SDK Repository Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/CONTRIBUTING.md Instructions to clone a forked version of the BSV SDK TypeScript repository from GitHub to your local machine. ```Shell git clone https://github.com/YOUR_USERNAME/ts-sdk.git ``` -------------------------------- ### Get Header For Height API Method Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/wallet.md Asynchronously retrieves the block header for a specified block height. This method returns the header as a hexadecimal string. ```APIDOC getHeaderForHeight(args: object, originator?: OriginatorDomainNameStringUnder250Bytes): Promise args: height: PositiveInteger originator?: OriginatorDomainNameStringUnder250Bytes Returns: header: HexString ``` -------------------------------- ### Get Default Broadcaster Function (TypeScript) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/transaction.md Returns a default `Broadcaster` instance. It can be configured for testnet and accepts an `ArcConfig` object for additional settings. ```ts export function defaultBroadcaster(isTestnet: boolean = false, config: ArcConfig = {}): Broadcaster ``` -------------------------------- ### Mersenne Constructor Usage Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Initializes a new Mersenne instance with a given name and a hexadecimal string representation of the pseudo-Mersenne prime. This constructor sets up the prime for subsequent arithmetic operations. ```APIDOC Constructor: constructor(name: string, p: string) Arguments: name: An identifier for the Mersenne instance. p: A string representation of the pseudo-Mersenne prime, expressed in hexadecimal. ``` ```ts const mersenne = new Mersenne('M31', '7FFFFFFF'); ``` -------------------------------- ### DownloaderConfig Interface Definition Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/storage.md Specifies configuration options for the file downloader, primarily the network preset to use (mainnet, testnet, or local). ```ts export interface DownloaderConfig { networkPreset: "mainnet" | "testnet" | "local"; } ``` -------------------------------- ### TypeScript Utility: Get UHRP URL for File Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/storage.md Generates a UHRP URL for a given file by first computing its SHA256 hash and then converting the hash to a UHRP URL. ```ts getURLForFile = (file: number[]): string => { const hash = sha256(file); return getURLForHash(hash); } ``` -------------------------------- ### TopicBroadcaster Class API Reference Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/overlay-tools.md Documents the `TopicBroadcaster` class, which handles broadcasting transactions to Overlay Services topics. It includes details on its constructor for initialization with topics and configuration, and the `broadcast` method for sending transactions, along with their respective parameters and return types. ```APIDOC Class: TopicBroadcaster Description: Broadcasts transactions to one or more overlay topics. TypeScript Signature: export default class TopicBroadcaster implements Broadcaster Constructor: Description: Constructs an instance of the SHIP broadcaster. TypeScript Signature: constructor(topics: string[], config: SHIPBroadcasterConfig = {}) Arguments: topics: Type: string[] Description: The list of SHIP topic names where transactions are to be sent. config: Type: SHIPBroadcasterConfig Description: Configuration options for the SHIP broadcaster. Method: broadcast Description: Broadcasts a transaction to Overlay Services via SHIP. TypeScript Signature: async broadcast(tx: Transaction): Promise Arguments: tx: Type: Transaction Description: The transaction to be sent. Returns: Type: Promise Description: A promise that resolves to either a success or failure response. ``` -------------------------------- ### TypeScript Interface: LookupResolverConfig Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/overlay-tools.md Provides configuration options for the Lookup resolver, allowing specification of network presets, facilitators, and host overrides for Overlay Services. ```ts export interface LookupResolverConfig { networkPreset?: "mainnet" | "testnet" | "local"; facilitator?: OverlayLookupFacilitator; slapTrackers?: string[]; hostOverrides?: Record; additionalHosts?: Record; } ``` ```APIDOC additionalHosts?: Record Map of lookup service names to arrays of hosts to use in addition to resolving via SLAP. ``` ```APIDOC facilitator?: OverlayLookupFacilitator The facilitator used to make requests to Overlay Services hosts. ``` ```APIDOC hostOverrides?: Record Map of lookup service names to arrays of hosts to use in place of resolving via SLAP. ``` ```APIDOC networkPreset?: "mainnet" | "testnet" | "local" The network preset to use, unless other options override it. - mainnet: use mainnet SLAP trackers and HTTPS facilitator - testnet: use testnet SLAP trackers and HTTPS facilitator - local: directly query from localhost:8080 and a facilitator that permits plain HTTP ``` ```APIDOC slapTrackers?: string[] The list of SLAP trackers queried to resolve Overlay Services hosts for a given lookup service. ``` -------------------------------- ### Call SHA256HMAC update Method with Hex Input Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Demonstrates how to use the `update` method of SHA256HMAC to feed message data. The example shows updating the HMAC with a hexadecimal string 'deadbeef'. ```ts myHMAC.update('deadbeef', 'hex'); ``` -------------------------------- ### AuthFetch Method: consumeReceivedCertificates API Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/auth.md API documentation for the `AuthFetch.consumeReceivedCertificates` method. ```APIDOC AuthFetch.consumeReceivedCertificates(): VerifiableCertificate[] Returns: VerifiableCertificate[] - Any certificates we've collected thus far, then clear them out. ``` -------------------------------- ### HD Class Constructor Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/compat.md Initializes an HD wallet instance with optional parameters for version bytes, depth, parent fingerprint, child index, chain code, private key, and public key. ```APIDOC constructor(versionBytesNum?: number, depth?: number, parentFingerPrint?: number[], childIndex?: number, chainCode?: number[], privKey?: PrivateKey, pubKey?: PublicKey) versionBytesNum: number - Version bytes number for the wallet. depth: number - Depth of the key in the hierarchy. parentFingerPrint: number[] - Fingerprint of the parent key. childIndex: number - Index of the child key. chainCode: number[] - Chain code for key derivation. privKey: PrivateKey - Private key of the wallet. pubKey: PublicKey - Public key of the wallet. ``` -------------------------------- ### AuthFetch Method: fetch API Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/auth.md API documentation for the `AuthFetch.fetch` method, which performs mutually authenticated HTTP requests. ```APIDOC AuthFetch.fetch(url: string, config: SimplifiedFetchRequestOptions = {}): Promise url: string - The URL to send the request to. config: SimplifiedFetchRequestOptions - Configuration options for the request, including method, headers, and body. Returns: Promise - A promise that resolves with the server's response, structured as a Response-like object. Throws: Error - Will throw an error if unsupported headers are used or other validation fails. ``` -------------------------------- ### Example of Spend Class validate Method Usage Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/script.md Illustrates how to call the `validate` method on a `Spend` object and use its boolean return value to determine if the transaction spend is valid, typically for conditional logic. ```typescript if (spend.validate()) { console.log("Spend is valid!"); } else { console.log("Invalid spend!"); } ``` -------------------------------- ### Construct K256 instance (TypeScript) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Initializes a new instance of the K256 class, utilizing the super constructor from Mersenne. ```APIDOC constructor() ``` ```ts const k256 = new K256(); ``` -------------------------------- ### TypeScript Utility: Get UHRP URL for Hash Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/storage.md Converts a 32-byte hash into a UHRP URL using base58 check encoding with a specific prefix. Throws an error if the hash length is not 32 bytes. ```ts getURLForHash = (hash: number[]): string => { if (hash.length !== 32) { throw new Error("Hash length must be 32 bytes (sha256)"); } return toBase58Check(hash, toArray("ce00", "hex")); } ``` -------------------------------- ### StorageDownloader Class API Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/storage.md Defines the `StorageDownloader` class, which is responsible for locating and downloading content via HTTP URLs. It can be configured with a network preset. ```APIDOC class StorageDownloader { constructor(config?: DownloaderConfig) config: Optional configuration for the downloader. networkPreset: "mainnet" | "testnet" | "local" - The network preset to use. public async resolve(uhrpUrl: string): Promise uhrpUrl: The UHRP URL to resolve. Returns: A promise that resolves to an array of strings (HTTP URLs). public async download(uhrpUrl: string): Promise uhrpUrl: The UHRP URL of the file to download. Returns: A promise that resolves to a DownloadResult object. DownloadResult: data: number[] - The downloaded file data as a byte array. mimeType: string | null - The MIME type of the downloaded file. } ``` -------------------------------- ### PushDrop Class Constructor (TypeScript) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/script.md This constructor initializes a new PushDrop instance, requiring a WalletInterface for cryptographic operations and an optional originator string for wallet requests. ```APIDOC constructor(wallet: WalletInterface, originator?: string) wallet: WalletInterface - The wallet interface used for creating signatures and accessing public keys. originator?: string - The originator to use with Wallet requests. ``` -------------------------------- ### Generate Random Hex String with DRBG Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Illustrates how to use the `generate` method of a `DRBG` instance to obtain a deterministic random hexadecimal string. The example requests a string of 256 bits (64 hex characters). ```typescript const randomHex = drbg.generate(256); ``` -------------------------------- ### APIDOC: CompletedProtoWallet Class Reference Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/auth.md Defines the `CompletedProtoWallet` class, which extends `ProtoWallet` and implements `WalletInterface`. This class provides core asynchronous functionalities for a Bitcoin SV wallet, including authentication, network interaction, public key retrieval, action lifecycle management (create, sign, abort, list, internalize), output management, and certificate operations (acquire, list, prove, relinquish, discover). ```APIDOC Class: CompletedProtoWallet Extends: ProtoWallet Implements: WalletInterface Properties: keyDeriver: KeyDeriver Constructor: constructor(rootKeyOrKeyDeriver: PrivateKey | "anyone" | KeyDeriverApi) Methods: isAuthenticated(): Promise waitForAuthentication(): Promise getNetwork(): Promise getVersion(): Promise getPublicKey(args: GetPublicKeyArgs): Promise<{"publicKey": PubKeyHex;}> createAction(): Promise signAction(): Promise abortAction(): Promise listActions(): Promise internalizeAction(): Promise listOutputs(): Promise relinquishOutput(): Promise acquireCertificate(): Promise listCertificates(): Promise proveCertificate(): Promise relinquishCertificate(): Promise discoverByIdentityKey(): Promise discoverByAttributes(): Promise getHeight(): Promise getHeaderForHeight(): Promise ``` -------------------------------- ### TypeScript Utility: Get Hash from UHRP URL Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/storage.md Extracts the 32-byte hash from a UHRP URL. Normalizes the URL and performs base58 check decoding. Throws an error if the URL length is invalid or the prefix is incorrect. ```ts getHashFromURL = (URL: string): number[] => { URL = normalizeURL(URL); const { data, prefix } = fromBase58Check(URL, undefined, 2); if (data.length !== 32) { throw new Error("Invalid length!"); } if (toHex(prefix as number[]) !== "ce00") { throw new Error("Bad prefix"); } return data as number[]; } ``` -------------------------------- ### KeyDeriver Constructor API Reference Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/wallet.md Documents the constructor for the KeyDeriver class, which initializes the instance with a root private key or the string 'anyone'. ```APIDOC KeyDeriver: constructor(rootKey: PrivateKey | "anyone") rootKey: The root private key or the string 'anyone'. ``` -------------------------------- ### KeyShares Class Definition and Usage Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Defines the KeyShares class, which manages points in a finite field, a threshold, and integrity information for cryptographic key sharing schemes. An example demonstrates how to initialize a KeyShares instance from existing shares. ```ts const key = PrivateKey.fromShares(shares) ``` ```APIDOC Class: KeyShares Properties: points: PointInFiniteField[]; threshold: number; integrity: string; Constructor: constructor(points: PointInFiniteField[], threshold: number, integrity: string) Static Methods: static fromBackupFormat(shares: string[]): KeyShares Methods: toBackupFormat(): string[] ``` -------------------------------- ### Get string representation of JacobianPoint (TypeScript) Source: https://github.com/bitcoin-sv/ts-sdk/blob/master/docs/primitives.md Returns a string representation of the JacobianPoint instance. For a point at infinity, it returns ''; otherwise, it formats as ''. ```APIDOC inspect(): string ``` ```ts const point = new JacobianPoint('5', '6', '1'); console.log(point.inspect()); // Output: '' ```