DogeJS / All tools / Core SDK

Keys, coins and signatures in JavaScript

Make Dogecoin wallets, addresses and transactions in the browser or in Node, with no server.

npm install @dogejs/core. Browsers and Node 20 or later, plain ES modules, no server.

A run example: keys and an HD wallet, three derived addresses and the output they printed.

What it does

A run example validating addresses: a mainnet address, a testnet address, one with a typo and plain text, with the output.

Check an address before you use it

Addresses carry a checksum. The library tells you whether one is valid, which network it belongs to and what kind it is.

  • One changed character fails the checksum
  • Mainnet and testnet addresses are told apart
  • Plain functions you can call anywhere
A run example signing and verifying a message, with the output: verifies true, other message false.

Sign a message and verify it

Prove you control an address by signing a message. Anyone can check the signature, and a changed message fails.

  • Signatures are 88 base64 characters
  • Recover the signer from the signature
  • The same format wallets use
A run example that builds and signs a payment, with the transaction it printed.

Build and sign a payment

Give the builder your coins, the recipient and a change address. It works out the fee and signs. Amounts are exact whole numbers, never floats.

  • Choose who pays the fee, or sweep everything
  • Amounts are bigint koinu
  • Runs on the test network first
A run example of a 2-of-3 multisig: signatures added one at a time, with the output.

Multisig and PSBT files

Build a 2-of-3 vault, let each cosigner sign their own copy and combine them. PSBT files and transaction files carry the same transactions to other tools.

  • Count signatures and see who is still missing
  • PSBT version 0, with SegWit fields refused
  • Transaction files carry a checksum

Keys, coins and signatures in JavaScript

Open source, MIT licensed, on GitHub.

For developers

Documentation

Modules, run examples, complete reference and FAQ.

Quick start

Install the package. It runs in browsers and in Node 20 or later, as plain ES modules.

Shell
npm install @dogejs/core

Make a testnet wallet, read its first address, then sign and verify a message.

JavaScript
import { generateMnemonic, HDNode, bip44Path, isValidAddress, signMessage, verifyMessage, testnet } from '@dogejs/core';

const root = HDNode.fromMnemonic(generateMnemonic(), { network: testnet });
const first = root.derive(bip44Path({ network: testnet }));
const address = first.toAddress();

console.log(address);                      // a testnet address, starts with n
isValidAddress(address, testnet);          // true

const signature = signMessage('wow', first.toWif());
verifyMessage('wow', address, signature);  // true
root.wipe();

Keep recovery phrases offline, and call wipe() when you are done with a key.

A bundler can pull in one function at a time through the subpath entries, for example import { isValidAddress } from '@dogejs/core/address'. Amounts are always bigint koinu, not floats.

What you can build

Wallets and addresses

BIP39 phrases, BIP32 and BIP44 keys, P2PKH and P2SH addresses, and WIF keys. HDNode

Signed messages

Prove you own an address. Compatible with Dogecoin Core's signmessage. signMessage

Payments

Pick coins, add change and sign, with dust and fee limits checked for you. TransactionBuilder

Fees you can trust

Let the recipient pay the fee, sweep an address, or check the fee of a file you did not build. checkTransactionFee

Multisig

m-of-n P2SH wallets, with a record of which keys have signed. inspectMultisigInput

PSBT (BIP174)

Hand a transaction to another wallet or tool, and take it back signed. signPsbt

Transaction files

A versioned JSON file that carries a payment from the machine that builds it to the one that signs it. parseTxFile

Examples

Who pays the fee

By default you pay the fee on top. With subtractFeeFrom the recipient pays it, and buildSweep sends everything to one address.

JavaScript
import { TransactionBuilder, buildSweep, formatDoge, parseDoge, testnet } from '@dogejs/core';

// coins: two made-up coins, 6 and 4 DOGE, each with its prevTxHex
const built = new TransactionBuilder({ network: testnet, requirePrevTx: true })
  .addUtxo(coins[0]).addUtxo(coins[1])
  .addOutput(shopAddress, parseDoge('4'))
  .setChangeAddress(changeAddress)
  .build();

built.mode;                                    // 'standard'
built.tx.outputs.map((o) => formatDoge(o.value)); // ['4', '1.99774']
formatDoge(built.fee);                           // '0.00226'

2-of-3 multisig

Three people hold keys, any two can spend. inspectMultisigInput reports who has signed and who is missing.

JavaScript
import { multisigScript, p2shAddressFromScript, p2shScriptForRedeemScript, signInputs,
  combineMultisigInput, inspectMultisigInput, verifyInput, testnet } from '@dogejs/core';

const redeem = multisigScript(2, [pubA, pubB, pubC]);
const address = p2shAddressFromScript(redeem, testnet);
const prevScript = p2shScriptForRedeemScript(redeem);
// built: an unsigned transaction that spends a coin held by address

const first = signInputs(built.tx, built.prevouts, [wifA]);     // OP_0 <sigA> OP_0 <redeem>
const other = signInputs(built.tx, built.prevouts, [wifC]);     // same unsigned tx
const both = combineMultisigInput(first, 0, [other.inputs[0].scriptSig], redeem, prevScript);

// Signed so far in this demo: nobody
inspectMultisigInput(both, 0, redeem, prevScript);
// signed keys [], missing [0,1,2], complete false

A transaction file

Build on one machine, sign on another. The file is read strictly and carries a checksum. Change one digit and the file is refused.

JavaScript
import { createTxFile, serializeTxFile, parseTxFile, addTxFileSignatures, signInputs, testnet } from '@dogejs/core/txfile';
// signInputs comes from '@dogejs/core'

// online machine: write the file
const file = createTxFile({ network: testnet, tx: built.tx, prevouts: built.prevouts, changeIndex: built.changeIndex, requirePrevTx: true });
const text = serializeTxFile(file);

// offline machine: read it strictly, sign, write it back
const f = parseTxFile(text, { network: testnet, requirePrevTx: true });
const signed = addTxFileSignatures(f, signInputs(f.tx, f.inputs, [wif]));
signed.state;   // 'signed'

parseTxFile(editedText); // throws DogeError FILE_CHECKSUM after any edit

Share a transaction as a PSBT

A PSBT (BIP174) is the file other wallets and hardware-wallet tools pass around. @dogejs/core/psbt reads and writes version 0. Dogecoin has no SegWit, so SegWit fields are refused. The signer only signs with the full previous transaction, and takes the amounts from it alone.

JavaScript
import { TransactionBuilder, parseDoge, testnet } from '@dogejs/core';
import {
  psbtFromBuiltTransaction, psbtToBase64, decodePsbt, inspectPsbt,
  signPsbt, finalizePsbt, extractPsbtTransaction,
} from '@dogejs/core/psbt';

// coin: a made-up 10 DOGE coin with its prevTxHex
const built = new TransactionBuilder({ network: testnet, requirePrevTx: true })
  .addUtxo(coin)
  .addOutput(shop, parseDoge('7.5'))
  .setChangeAddress(changeAddress)
  .build();

const text = psbtToBase64(psbtFromBuiltTransaction(built, { network: testnet }));
// text starts "cHNidP8B...": give it to a wallet, a cosigner or a hardware-wallet tool

const psbt = decodePsbt(text);
inspectPsbt(psbt, { network: testnet }).fee;      // 226000n koinu: show this before anyone signs
const done = finalizePsbt(signPsbt(psbt, [wif]).psbt);
done.complete;                                     // true
const tx = extractPsbtTransaction(done.psbt);      // verified, ready to broadcast

For several signers, call signPsbt on each copy and join them with combinePsbts before finalizePsbt. Files convert both ways with psbtToTxFile and txFileToPsbt. The decoder and multisig page open PSBTs, and dogejs psbt works with them on the command line.

How it is tested

The package has 1,633 tests, and the Dogecoin-specific rules come from other people's code, not only ours. The test files carry vectors taken from Dogecoin Core (signature hashes, valid and invalid transactions, scripts, Base58, BIP32), the BIP32, BIP39 and BIP174 reference vectors, and the Dogecoin Foundation's C library, libdogecoin.

For libdogecoin we built it from source (commit bf3f9df), ran its own tests, then asked it the same questions as DogeJS and compared the answers byte for byte. It is a test oracle only, not a dependency.

Compared with libdogecoinCasesResult
P2PKH addresses, mainnet, testnet and regtest48identical
WIF encode and decode72identical
BIP32 nodes (keys, extended keys, addresses)108identical
BIP39 phrases, seeds and BIP44 addresses7 phrasesidentical
Transaction signatures, P2PKH, all six hash types8byte-identical
Message signatures, 4 keys and 11 messages44identical for 1 to 252 bytes, and each verifies the other's
PSBT workflows (single key, 2-of-3, out of order)4identical; libdogecoin reads, finalizes and extracts ours

The comparison found three bugs in libdogecoin and none in DogeJS: its raw-transaction multisig signer writes the redeem script without the right push, so 2-of-3 inputs never verify; its message hash differs from Dogecoin Core for empty and 253-byte or longer messages; and its PSBT signer adds signatures to inputs it cannot sign. PSBT files are checked against libdogecoin and the BIP174 test vectors.

Details and every vector: test/vectors/libdogecoin/README.md and docs/PSBT.md in the package.

Reference

Modules and key functions

Every module is also an import path, for example @dogejs/core/hd. The main entry exports all of them.

ModuleKey functions and classes
networksmainnet, testnet, regtest, getNetwork, networkFromGenesisHash
amountparseDoge, parseKoinu, formatDoge, KOINU_PER_DOGE
keysgeneratePrivateKey, getPublicKey, encodeWif, decodeWif
addressp2pkhAddress, p2shAddressFromScript, decodeAddress, isValidAddress
hdgenerateMnemonic, HDNode, bip44Path, coreHdPath
messagesignMessage, verifyMessage, recoverMessageSigner
scriptaddressToScript, scriptToAddress, classifyScript, multisigScript, nullDataScript
transactiondecodeTransaction, encodeTransaction, getTxid, checkTransaction, checkStandardTx
sign, sighashsignInputs, verifyTransaction, verifyInput, combineMultisigInput, inspectMultisigInput, legacySighash
builderTransactionBuilder, buildSweep, verifyUtxo, checkTransactionFee
fees, policyestimateSize, estimateFee, feeForSize, isDust, fee and dust constants
psbtdecodePsbt, psbtFromBuiltTransaction, inspectPsbt, signPsbt, combinePsbts, finalizePsbt, extractPsbtTransaction, psbtToTxFile, txFileToPsbt
txfilecreateTxFile, parseTxFile, serializeTxFile, addTxFileSignatures, createMultisigDescriptor, parseMultisigDescriptor
bytes, errorsByteReader, ByteWriter, sha256d, hash160, DogeError

Every function throws a DogeError with a code, for example INVALID_CHECKSUM, WRONG_NETWORK, INSUFFICIENT_FUNDS, FEE_TOO_HIGH, FEE_TOO_LOW, DUST_OUTPUT, UTXO_MISMATCH or FILE_CHECKSUM.

Import paths and bundle sizes

Measured with esbuild 0.24, minified, with everything a consumer needs included. Import from the subpath entries when you bundle.

You importMinifiedGzipped
parseDoge from @dogejs/core/amount910 B528 B
networkFromGenesisHash from @dogejs/core/networks1,375 B778 B
isValidAddress from @dogejs/core/address9,342 B4,225 B
TransactionBuilder and signInputs80,232 B28,786 B
parseTxFile from @dogejs/core/txfile86,969 B31,039 B
decodePsbt and signPsbt from @dogejs/core/psbt72,640 B26,856 B
isValidAddress from the main entry78,086 B32,179 B
All of dist/index.mjs (one file, for a CDN)197,721 B68,103 B

Network constants

Namemainnettestnetregtest
P2PKH version byte0x1e (D...)0x71 (n...)0x6f
P2SH version byte0x160xc40xc4
WIF version byte0x9e0xf10xef
Extended public keydgubtpubtpub
BIP44 coin type311
Genesis block hash1a91e3da...bb0a7826...3d2160a3...

Fee and dust constants

From Dogecoin Core 1.14.99. Node operators can change them.

ConstantValueMeaning
RECOMMENDED_FEE_RATE0.01 DOGE/kBDefault fee rate of the builder.
MIN_RELAY_FEE_RATE0.001 DOGE/kBBelow this, nodes do not relay.
SOFT_DUST_LIMIT0.01 DOGERelay adds a fee for each output below it.
HARD_DUST_LIMIT0.001 DOGEOutputs below it are non-standard.
DEFAULT_MAX_TX_FEE100 DOGEAbsolute fee limit (maxFee).
DEFAULT_MAX_FEE_MULTIPLE10Relative limit (maxFeeMultiple): ten times the expected fee, plus any leftover allowance.

Run examples

Each example below was run now against the built package, on testnet, and the output is what it printed. They share one helper that makes a funding transaction the way a backend would hand you one:

JavaScript (common.mjs)
// Shared helper for the examples: makes a "funding" transaction (a coin that pays `address`), the way a chain backend would hand you one.
import { TransactionBuilder, addressToScript, signInputs, encodeTransactionHex, getTxid, parseDoge, testnet } from '@dogejs/core';

export function fund(address, fromKeyWif, fromAddress, doge = '10') {
  const b = new TransactionBuilder({ network: testnet, requirePrevTx: false })
    .addUtxo({ txid: 'bb'.repeat(32), vout: 0, value: parseDoge('50'), script: addressToScript(fromAddress, testnet) })
    .addOutput(address, parseDoge(doge))
    .setChangeAddress(fromAddress)
    .build();
  const signed = signInputs(b.tx, b.prevouts, [fromKeyWif]);
  return { txid: getTxid(signed), hex: encodeTransactionHex(signed), vout: 0, value: parseDoge(doge) };
}

Run: Keys and an HD wallet

JavaScript
import { HDNode, generateMnemonic, validateMnemonic, bip44Path, testnet, mainnet } from '@dogejs/core';

// A fixed 32-byte seed keeps this output the same on every run (never use a fixed seed for real money).
const seed = new Uint8Array(32).fill(7);
const root = HDNode.fromSeed(seed, mainnet);

for (let i = 0; i < 3; i++) {
  const path = bip44Path({ account: 0, change: 0, index: i }); // m/44'/3'/0'/0/i on mainnet
  console.log(path, root.derive(path).toAddress());
}

// The account-level public key can make every address without ever holding a private key.
const account = root.derive("m/44'/3'/0'");
const watchOnly = HDNode.fromExtendedKey(account.toExtendedPublicKey());
console.log('watch-only index 0 matches:', watchOnly.derive('0/0').toAddress() === root.derive("m/44'/3'/0'/0/0").toAddress());
console.log('can sign:', watchOnly.isPrivate);

// A recovery phrase: 24 words by default. Only its size and validity are shown here.
const phrase = generateMnemonic();
console.log(phrase.split(' ').length, 'words, valid:', validateMnemonic(phrase));
console.log('testnet path:', bip44Path({ network: testnet }));
root.wipe();
Output
m/44'/3'/0'/0/0 DG4mTCMmrrf3osupdmhkCLhbrckEyPVT85
m/44'/3'/0'/0/1 DMYfL4B4SKXycmXnUDEvTDhKMoZ6zbmdAF
m/44'/3'/0'/0/2 D8KoKYJQjJTuAirfHyBBa4KGGsJfyNRWhg
watch-only index 0 matches: true
can sign: false
24 words, valid: true
testnet path: m/44'/1'/0'/0/0

Run: Validate addresses

JavaScript
import { isValidAddress, decodeAddress, detectAddressNetworks, mainnet, testnet, DogeError } from '@dogejs/core';

const samples = [
  'DU9umLs2Ze8eNRo69wbSj5HeufphJawFPh', // mainnet P2PKH
  'nUCAGGgZEPN1QyknmQe1oAku817bQAFKFt', // testnet P2PKH
  'DU9umLs2Ze8eNRo69wbSj5HeufphJawFPi', // one character changed: the checksum fails
  'not an address',
];
for (const a of samples) {
  console.log(a.slice(0, 12).padEnd(14), 'mainnet:', isValidAddress(a, mainnet), ' testnet:', isValidAddress(a, testnet),
    ' networks:', detectAddressNetworks(a).map((n) => n.name).join(',') || '-');
}
const ok = decodeAddress('DU9umLs2Ze8eNRo69wbSj5HeufphJawFPh');
console.log(ok.type, ok.network.name, ok.hash.length + ' byte hash');
try { decodeAddress('DU9umLs2Ze8eNRo69wbSj5HeufphJawFPi'); } catch (e) { console.log(e instanceof DogeError, e.code); }
try { decodeAddress('nUCAGGgZEPN1QyknmQe1oAku817bQAFKFt', mainnet); } catch (e) { console.log(e.code); }
Output
DU9umLs2Ze8e   mainnet: true  testnet: false  networks: mainnet
nUCAGGgZEPN1   mainnet: false  testnet: true  networks: testnet
DU9umLs2Ze8e   mainnet: false  testnet: false  networks: -
not an addre   mainnet: false  testnet: false  networks: -
p2pkh mainnet 20 byte hash
true INVALID_CHECKSUM
WRONG_NETWORK

Run: Sign and verify a message

JavaScript
import { generatePrivateKey, getPublicKey, encodeWif, p2pkhAddress, signMessage, verifyMessage, recoverMessageSigner, testnet } from '@dogejs/core';

const priv = generatePrivateKey();
const address = p2pkhAddress(getPublicKey(priv), testnet);
const wif = encodeWif(priv, { network: testnet });

const signature = signMessage('I own this address', wif);
console.log('signature bytes (base64 length):', signature.length); // 88 characters = 65 bytes
console.log('verifies:', verifyMessage('I own this address', address, signature));
console.log('other message:', verifyMessage('I own this address!', address, signature));
console.log('recovered signer is the address:', recoverMessageSigner('I own this address', signature, testnet).address === address);
priv.fill(0);
Output
signature bytes (base64 length): 88
verifies: true
other message: false
recovered signer is the address: true

Run: Build and sign a payment

JavaScript
import { generatePrivateKey, getPublicKey, encodeWif, p2pkhAddress, addressToScript, TransactionBuilder, signInputs, verifyTransaction,
  encodeTransactionHex, getTxid, parseDoge, formatDoge, testnet } from '@dogejs/core';

const priv = generatePrivateKey();
const me = p2pkhAddress(getPublicKey(priv), testnet);
const shop = p2pkhAddress(getPublicKey(generatePrivateKey()), testnet);

// One coin of 10 DOGE that pays "me". A real one comes from a chain backend (see /backends/).
const coin = { txid: 'aa'.repeat(32), vout: 0, value: parseDoge('10'), script: addressToScript(me, testnet) };

const built = new TransactionBuilder({ network: testnet, requirePrevTx: false })
  .addUtxo(coin)
  .addOutput(shop, parseDoge('4'))
  .setChangeAddress(me)
  .build();
console.log('fee', formatDoge(built.fee), 'DOGE, size about', built.estimatedSize, 'bytes, inputs', formatDoge(built.inputTotal), 'outputs', formatDoge(built.outputTotal));
console.log('outputs', built.tx.outputs.map((o) => formatDoge(o.value)).join(' + '));

const signed = signInputs(built.tx, built.prevouts, [encodeWif(priv, { network: testnet })]);
console.log('valid:', verifyTransaction(signed, built.prevouts).valid);
console.log('hex starts', encodeTransactionHex(signed).slice(0, 24) + '...', 'txid length', getTxid(signed).length);
Output
fee 0.00226 DOGE, size about 226 bytes, inputs 10 outputs 9.99774
outputs 4 + 5.99774
valid: true
hex starts 0100000001aaaaaaaaaaaaaa... txid length 64

Run: A 2-of-3 multisig

JavaScript
import { generatePrivateKey, getPublicKey, encodeWif, p2pkhAddress, multisigScript, p2shScriptForRedeemScript, p2shAddressFromScript,
  TransactionBuilder, signInputs, combineMultisigInput, multisigSignatureCount, inspectMultisigInput, verifyInput, formatDoge, parseDoge, testnet } from '@dogejs/core';
import { fund } from './common.mjs';

const keys = [generatePrivateKey(), generatePrivateKey(), generatePrivateKey()];
const pubs = keys.map((k) => getPublicKey(k));
const wif = keys.map((k) => encodeWif(k, { network: testnet }));

// 2-of-3: any two of the three keys can spend. The order of the keys is part of the address.
const redeemScript = multisigScript(2, pubs);
const vault = p2shAddressFromScript(redeemScript, testnet);
console.log('vault address starts with', vault[0], '(test network P2SH)');

const faucet = generatePrivateKey();
const funding = fund(vault, encodeWif(faucet, { network: testnet }), p2pkhAddress(getPublicKey(faucet), testnet));
const pay = p2pkhAddress(getPublicKey(generatePrivateKey()), testnet);

const built = new TransactionBuilder({ network: testnet })
  .addUtxo({ txid: funding.txid, vout: 0, value: funding.value, script: p2shScriptForRedeemScript(redeemScript), redeemScript, prevTxHex: funding.hex })
  .addOutput(pay, parseDoge('3'))
  .setChangeAddress(vault)
  .build();
const lock = built.prevouts[0].script;

// Each cosigner signs their own copy of the same unsigned transaction.
const fromA = signInputs(built.tx, built.prevouts, [wif[0]]);
const fromC = signInputs(built.tx, built.prevouts, [wif[2]]);
console.log('A alone:', JSON.stringify(multisigSignatureCount(fromA, 0, redeemScript, lock)), 'valid:', verifyInput(fromA, 0, lock).valid);

const who = inspectMultisigInput(fromA, 0, redeemScript, lock);
console.log('signed by key', who.signed.map((s) => s.keyIndex), 'missing', who.missing.map((s) => s.keyIndex));

// Combine the signatures into one copy.
const both = combineMultisigInput(fromA, 0, [fromC.inputs[0].scriptSig], redeemScript, lock);
console.log('A + C:', JSON.stringify(multisigSignatureCount(both, 0, redeemScript, lock)), 'valid:', verifyInput(both, 0, lock).valid);
console.log('fee', formatDoge(built.fee), 'DOGE');
Output
vault address starts with 2 (test network P2SH)
A alone: {"have":1,"need":2} valid: false
signed by key [ 0 ] missing [ 1, 2 ]
A + C: {"have":2,"need":2} valid: true
fee 0.00373 DOGE

Run: A PSBT round trip

JavaScript
import { generatePrivateKey, getPublicKey, encodeWif, p2pkhAddress, addressToScript, TransactionBuilder, parseDoge, formatDoge, testnet,
  psbtFromBuiltTransaction, psbtToBase64, decodePsbt, inspectPsbt, signPsbt, finalizePsbt, extractPsbtTransaction, encodeTransactionHex, getTxid, verifyTransaction } from '@dogejs/core';
import { fund } from './common.mjs';

const k = generatePrivateKey();
const me = p2pkhAddress(getPublicKey(k), testnet);
const wif = encodeWif(k, { network: testnet });
const faucet = generatePrivateKey();
const funding = fund(me, encodeWif(faucet, { network: testnet }), p2pkhAddress(getPublicKey(faucet), testnet));
const shop = p2pkhAddress(getPublicKey(generatePrivateKey()), testnet);

// 1. Creator + Updater: an unsigned PSBT from a built transaction (it carries the full previous transaction).
const built = new TransactionBuilder({ network: testnet })
  .addUtxo({ txid: funding.txid, vout: 0, value: funding.value, script: addressToScript(me, testnet), prevTxHex: funding.hex })
  .addOutput(shop, parseDoge('2.5')).setChangeAddress(me).build();
const text = psbtToBase64(psbtFromBuiltTransaction(built, { network: testnet }));
console.log('PSBT text:', text.slice(0, 20) + '... (' + text.length + ' characters, base64)');

// 2. Anyone can read it. Nothing is signed yet.
const before = inspectPsbt(decodePsbt(text), { network: testnet });
console.log('inputs', before.inputs.length, 'outputs', before.outputs.length, 'fee', formatDoge(before.fee), 'finalized', before.finalized);

// 3. Signer, then Finalizer, then Extractor.
const { signed } = signPsbt(decodePsbt(text), [wif]);
console.log('inputs signed:', signed.length);
const done = finalizePsbt(signPsbt(decodePsbt(text), [wif]).psbt);
console.log('complete:', done.complete);
const tx = extractPsbtTransaction(done.psbt);
console.log('valid:', verifyTransaction(tx, built.prevouts).valid, 'txid matches:', getTxid(tx).length === 64, 'hex bytes:', encodeTransactionHex(tx).length / 2);
Output
PSBT text: cHNidP8BAHcBAAAAAXMv... (520 characters, base64)
inputs 1 outputs 2 fee 0.00226 finalized false
inputs signed: 1
complete: true
valid: true txid matches: true hex bytes: 225

Run: Units and fees

JavaScript
import { parseDoge, formatDoge, parseKoinu, KOINU_PER_DOGE, MAX_MONEY, estimateFee, estimateSize, feeForSize, minRelayFee, isDust,
  RECOMMENDED_FEE_RATE, MIN_RELAY_FEE_RATE, SOFT_DUST_LIMIT, HARD_DUST_LIMIT, DogeError } from '@dogejs/core';

console.log(parseDoge('12.5'), formatDoge(1250000000n), formatDoge(100000000n, { minDecimals: 2 }), KOINU_PER_DOGE);
console.log('smallest unit:', formatDoge(1n), 'DOGE; max money:', formatDoge(MAX_MONEY));
for (const bad of ['0.000000001', '-1', '1e3', '1,5']) { try { parseDoge(bad); } catch (e) { console.log(JSON.stringify(bad), '->', e instanceof DogeError ? e.code : e.name); } }

const spec = { inputs: [{ type: 'p2pkh' }, { type: 'p2pkh' }], outputs: [{ type: 'p2pkh' }, { type: 'p2pkh' }] };
console.log('2 in / 2 out:', estimateSize(spec), 'bytes, fee', formatDoge(estimateFee(spec)), 'DOGE');
console.log('rates (koinu per kB): recommended', RECOMMENDED_FEE_RATE, 'minimum relay', MIN_RELAY_FEE_RATE);
console.log('fee for 1000 bytes', formatDoge(feeForSize(1000)), '| relay minimum for 226 bytes', formatDoge(minRelayFee(226)));
console.log('dust: soft', formatDoge(SOFT_DUST_LIMIT), 'hard', formatDoge(HARD_DUST_LIMIT));
for (const v of ['0.001', '0.5']) console.log(v, 'DOGE output is dust:', isDust({ value: parseDoge(v), script: new Uint8Array(25) }));
Output
1250000000n 12.5 1.00 100000000n
smallest unit: 0.00000001 DOGE; max money: 10000000000
"0.000000001" -> INVALID_AMOUNT
"-1" -> INVALID_AMOUNT
"1e3" -> INVALID_AMOUNT
"1,5" -> INVALID_AMOUNT
2 in / 2 out: 374 bytes, fee 0.00374 DOGE
rates (koinu per kB): recommended 1000000n minimum relay 100000n
fee for 1000 bytes 0.01 | relay minimum for 226 bytes 0.000226
dust: soft 0.01 hard 0.001
0.001 DOGE output is dust: true
0.5 DOGE output is dust: false

Run: A transaction file

JavaScript
import { generatePrivateKey, getPublicKey, p2pkhAddress, addressToScript, TransactionBuilder, createTxFile, serializeTxFile, parseTxFile, parseDoge, formatDoge, testnet } from '@dogejs/core';
import { fund } from './common.mjs';
import { encodeWif } from '@dogejs/core';

const k = generatePrivateKey(); const me = p2pkhAddress(getPublicKey(k), testnet);
const f = generatePrivateKey(); const funding = fund(me, encodeWif(f, { network: testnet }), p2pkhAddress(getPublicKey(f), testnet));
const shop = p2pkhAddress(getPublicKey(generatePrivateKey()), testnet);
const built = new TransactionBuilder({ network: testnet })
  .addUtxo({ txid: funding.txid, vout: 0, value: funding.value, script: addressToScript(me, testnet), prevTxHex: funding.hex })
  .addOutput(shop, parseDoge('2')).setChangeAddress(me).build();

// An unsigned transaction file: what you carry to the machine that holds the key.
const file = createTxFile({ network: testnet, tx: built.tx, prevouts: built.prevouts, changeIndex: built.changeIndex, note: 'Order 1042' });
const text = serializeTxFile(file);
const json = JSON.parse(text);
console.log(Object.keys(json).join(', '));
console.log('format', json.format, 'version', json.version, 'state', json.state);
console.log('fee', formatDoge(BigInt(file.summary.feeKoinu)), 'DOGE; checksum', json.checksum.slice(0, 12) + '...');

// Reading it back checks the checksum and every field again; a changed byte is refused.
console.log('round trip ok:', parseTxFile(text).summary.totalSentKoinu === file.summary.totalSentKoinu);
try { parseTxFile(text.replace('"Order 1042"', '"Order 1043"')); } catch (e) { console.log('edited file refused:', e.code); }
Output
format, version, network, note, state, unsignedTx, inputs, summary, checksum
format dogejs-tx version 2 state unsigned
fee 0.00226 DOGE; checksum sha256:569bc...
round trip ok: true
edited file refused: FILE_CHECKSUM

Complete API

Generated from the built type declarations of @dogejs/core 0.4.1 (282 exports). Each module is a separate import path.

address10 exports
NameKindSignatureWhat it does
AddressTypetypeAddressType = 'p2pkh' | 'p2sh';Address kind: `p2pkh` (pay to public key hash, starts with D on mainnet) or `p2sh` (pay to script hash, starts with 9 or A).
decodeAddressfunctiondecodeAddress(address: string, network?: Network): DecodedAddress;Decodes and validates a Dogecoin address. Mirrors Core's CBitcoinAddress::IsValid (src/base58.cpp:252-258): a 20-byte payload with the network's PUBKEY_ADDRESS or SCRIPT_ADDRESS version.
DecodedAddressinterface{ type, hash, network, networks }Result of decodeAddress: the address kind, its 20-byte hash and the network(s) whose version byte it carries.
detectAddressNetworksfunctiondetectAddressNetworks(address: string): readonly Network[];Built-in networks an address is valid for (empty if invalid). Never throws.
encodeAddressfunctionencodeAddress(type: AddressType, hash: Uint8Array, network?: Network): string;Base58Check-encodes `version || hash160`. Core: CBitcoinAddress::Set (src/base58.cpp).
hash160functionhash160(data: Uint8Array): Uint8Array;RIPEMD-160(SHA-256(data)), Dogecoin Core's `Hash160()`.
isValidAddressfunctionisValidAddress(address: string, network?: Network): boolean;True if `address` is a valid Dogecoin address (optionally for `network`). Never throws.
p2pkhAddressfunctionp2pkhAddress(publicKey: Uint8Array, network?: Network): string;P2PKH address of a public key. The address commits to the exact encoding: compressed and uncompressed forms of the same key give different addresses.
p2shAddressfunctionp2shAddress(scriptHash: Uint8Array, network?: Network): string;P2SH address from a 20-byte redeem-script hash (hash160 of the script).
p2shAddressFromScriptfunctionp2shAddressFromScript(redeemScript: Uint8Array, network?: Network): string;P2SH address from a serialized redeem script (hashes it with hash160).
amount8 exports
NameKindSignatureWhat it does
DOGE_DECIMALSconstDOGE_DECIMALS = 8Number of decimal places of one DOGE (log10 of KOINU_PER_DOGE).
formatDogefunctionformatDoge(koinu: bigint, options?: FormatOptions): string;Formats koinu as a decimal DOGE string. Trailing zeros are trimmed down to `minDecimals`. Negative values are formatted with a leading `-` (useful for balance deltas); parseDoge does not accept them back.
FormatOptionsinterface{ minDecimals? }Options for formatDoge.
isMoneyRangefunctionisMoneyRange(koinu: bigint): boolean;True if `value` is between 0 and MAX_MONEY, in koinu.
KOINU_PER_DOGEconstKOINU_PER_DOGE = 100000000nKoinu per DOGE. Dogecoin Core src/amount.h:18 `static const CAmount COIN = 100000000;` Amounts are always `bigint` koinu; no floating point is used anywhere.
MAX_MONEYconstMAX_MONEY: bigintLargest amount of money in koinu: 10 billion DOGE (Core's MAX_MONEY). A sanity limit, not the supply.
parseDogefunctionparseDoge(input: string): bigint;Parses a decimal DOGE string into koinu.
parseKoinufunctionparseKoinu(input: string): bigint;Parses a koinu integer string (digits only, non-negative).
builder14 exports
NameKindSignatureWhat it does
BuilderOptionsinterface{ network, feeRate?, maxFee?, maxFeeMultiple?, requirePrevTx?, maxFeeRate?, dustThreshold?, coinSelection?, locktime?, version?, subtractFeeFrom? }Settings of a TransactionBuilder. Only `network` is required. Amounts are koinu (bigint); fee rates are koinu per 1000 bytes.
buildSweepfunctionbuildSweep(options: BuilderOptions & { readonly utxos: readonly Utxo[]; readonly to: string; readonly data?: Uint8Array; }): BuiltTransaction;One-call sweep: spends every UTXO in `utxos` to `to`, with the fee taken from that output (TransactionBuilder.sweepTo). `data` adds one OP_RETURN output.
buildTransactionfunctionbuildTransaction(options: BuilderOptions & { readonly utxos: readonly Utxo[]; readonly outputs: readonly ({ readonly address: string; readonly value: bigint; } | { readonly data: Uint8Array; })[]; readonly changeAddress: string; }): BuiltTransaction;One-call form of TransactionBuilder.
BuiltTransactioninterface{ tx, prevouts, fee, expectedFee, discardedChange, estimatedSize, changeIndex, inputTotal, outputTotal, mode, feeFromOutputs, changeTopUp }Result of TransactionBuilder.build: the unsigned transaction, the outputs it spends and the fee details. Amounts are koinu.
checkTransactionFeefunctioncheckTransactionFee(transaction: Transaction | Uint8Array | string, prevouts: readonly FeeCheckPrevout[], options?: FeeCheckOptions): FeeCheckResult;Checks the fee of an existing transaction against the builder's guards. Never throws for a failed guard; see the result.
CoinSelectiontypeCoinSelection = 'largest-first' | 'in-order' | 'all';How the builder picks inputs: `largest-first` (default), `in-order` (as given) or `all` (spend every UTXO added).
DEFAULT_MAX_FEE_MULTIPLEconstDEFAULT_MAX_FEE_MULTIPLE = 10Default of BuilderOptions.maxFeeMultiple: the fee may be at most 10 times the fee the builder expects (plus the leftover allowance). DogeJS policy, not a Dogecoin Core constant; Core only has the absolute -maxtxfee (src/validation.h:62).
FeeCheckFailureinterface{ code, guard, message }One failed guard of checkTransactionFee: the error code it stands for, which guard failed, and a message.
FeeCheckOptionsinterface{ feeRate?, maxFee?, maxFeeMultiple?, hasChange?, requirePrevTx? }Guards for checkTransactionFee. Defaults match TransactionBuilder. Amounts are koinu, fee rates koinu per 1000 bytes.
FeeCheckPrevoutinterface{ value, script, redeemScript?, compressed?, prevTxHex? }What the fee check needs to know about the output an input spends.
FeeCheckResultinterface{ ok, fee, inputTotal, outputTotal, size, currentSize, sizeIsEstimate, completeInputs, feeRate, expectedFee, minRelayFee, maxFee, relativeLimit, leftoverAllowance, failures }Result of checkTransactionFee: whether every guard passed, the fee and totals in koinu, and any failures. It never throws for a failed guard.
TransactionBuilderclassclass: addUtxo(), addOutput(), addData(), sweepTo(), setChangeAddress(), build()Builds an unsigned transaction: add UTXOs and outputs, then call TransactionBuilder.build. Selects coins, computes the fee, adds change and enforces the fee, dust and standardness guards; throws DogeError (INSUFFICIENT_FUNDS, FEE_TOO_HIGH, DUST_OUTPUT, UTXO_UNVERIFIED and others) instead of building a bad transaction. Amounts are koinu.
Utxointerface{ txid, vout, value, script, redeemScript?, compressed?, prevTxHex? }An unspent output to spend with TransactionBuilder: outpoint, value in koinu, script and, for P2SH, the redeem script.
verifyUtxofunctionverifyUtxo(utxo: Utxo): void;Authenticates a UTXO's value and script against its full previous transaction (`utxo.prevTxHex`). Throws DogeError: - UTXO_UNVERIFIED if `prevTxHex` is missing; - UTXO_MISMATCH if `prevTxHex` is not a valid legacy transaction, if its txid (double SHA-256 of exactly these bytes, displayed byte-reversed) is not `utxo.txid`, if it has no output `utxo.vout`, or if that output's value or scriptPubKey differ from `utxo.value` / `utxo.script`; - INVALID_ARGUMENT / INVALID_AMOUNT for a malformed UTXO.
bytes17 exports
NameKindSignatureWhat it does
base58checkDecodefunctionbase58checkDecode(input: string): Uint8Array;Base58Check decoding with distinct error codes. Returns the payload (version byte(s) included) without the 4-byte checksum.
base58checkEncodefunctionbase58checkEncode(payload: Uint8Array): string;Base58Check encoding (version and payload already concatenated).
ByteReaderclassclass: position, remaining, bytes(), u8(), u16(), u32(), i32(), u64(), i64(), compactSize(), varBytes()Strict little-endian reader: every read is bounds-checked and fails with `code`.
bytesToHexfunctionbytesToHex(bytes: Uint8Array): string;Lowercase hex encoding.
ByteWriterclassclass: bytes(), u8(), u32(), i32(), i64(), compactSize(), varBytes(), length, finish()Little-endian serializer used for transactions and signature hashes.
compactSizefunctioncompactSize(n: number): Uint8Array;Bitcoin/Dogecoin CompactSize (see Core src/serialize.h WriteCompactSize).
concatBytesfunctionconcatBytes(...parts: Uint8Array[]): Uint8Array;
equalBytesfunctionequalBytes(a: Uint8Array, b: Uint8Array): boolean;Equality of public data (not constant-time; never use for secrets).
hash160functionhash160(data: Uint8Array): Uint8Array;RIPEMD-160(SHA-256(data)), Dogecoin Core's `Hash160()`.
hashToHexfunctionhashToHex(hash: Uint8Array): string;Displayed hex of a 32-byte hash kept in internal (wire) order, as Core's uint256::GetHex: the bytes reversed. Used for txids and block hashes.
hexToBytesfunctionhexToBytes(input: string, name?: string): Uint8Array;Strict hex decoding: even length, hex digits only (either case), no prefix or whitespace.
hexToHashfunctionhexToHash(hex: string): Uint8Array;Internal (wire) order bytes of a displayed 64-hex-character hash (the reverse of hashToHex).
MAX_COMPACT_SIZEconstMAX_COMPACT_SIZE = 33554432Core's MAX_SIZE for CompactSize values, src/serialize.h:26 `static const unsigned int MAX_SIZE = 0x02000000;`
ripemd160constripemd160: CHashRIPEMD-160 - a legacy hash function from 1990s. * https://homes.esat.kuleuven.be/~bosselae/ripemd160.html * https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
sha256constsha256: CHashSHA2-256 hash function from RFC 4634.
sha256dfunctionsha256d(data: Uint8Array): Uint8Array;Double SHA-256, Dogecoin Core's `Hash()`.
toBytesfunctiontoBytes(input: Uint8Array | string, name: string): Uint8Array;Accepts bytes or a hex string; always returns a fresh copy.
errors2 exports
NameKindSignatureWhat it does
DogeErrorclassclass: code, [Symbol.hasInstance]()Error thrown by every DogeJS core function. Messages never contain secret material (private keys, seeds, mnemonics or WIF strings).
DogeErrorCodetypeDogeErrorCode = 'INVALID_ENCODING' | 'INVALID_CHECKSUM' | 'INVALID_LENGTH' | 'INVALID_VERSION' | 'WRONG_NETWORK' | 'INVALID_PRIVATE_KEY' | 'INVALID_PUBLIC_KEY' | 'INVALID_AMOUNT' | 'INVALID_MNEMONIC' | 'INVALID_PATH' | 'INVALID_EXTENDED_KEY' | 'INVALID_SIGNATURE' | 'INVALID_ARGUMENT' | 'INVALID_SCRIPT' | 'INVALID_TRANSACTION' | 'NON_STANDARD' | 'INSUFFICIENT_FUNDS' | 'DUST_OUTPUT' | 'FEE_TOO_HI...Machine-readable reason codes for DogeError.
fees23 exports
NameKindSignatureWhat it does
DEFAULT_MAX_TX_FEEconstDEFAULT_MAX_TX_FEE: bigintDefault ceiling for the fee of one transaction, in koinu: 100 DOGE (Core's -maxtxfee).
DISCARD_THRESHOLDconstDISCARD_THRESHOLD: bigintWallet dust threshold in koinu: 0.01 DOGE. Change below it is given to the fee.
dustPenaltyfunctiondustPenalty(outputs: readonly OutputLike[], limit?: bigint): bigint;Extra fee in koinu that Core charges for dust outputs: `limit` for each one.
ESTIMATED_SIGNATURE_SIZEconstESTIMATED_SIGNATURE_SIZE = 72Signature size assumed by estimates: 72 bytes including the hash-type byte, as Core's DummySignatureCreator (src/script/sign.cpp:412-426). A low-S DER signature is at most 71 bytes plus the hash type, so this is an upper bound.
estimateFeefunctionestimateFee(spec: { inputs: readonly InputSizeDescriptor[]; outputs: readonly OutputSizeDescriptor[]; }, feeRatePerKb?: bigint): bigint;Fee in koinu for the estimated size of a transaction.
estimateScriptSigSizefunctionestimateScriptSigSize(input: InputSizeDescriptor): number;scriptSig length of a P2PKH or P2SH-multisig spend with ESTIMATED_SIGNATURE_SIZE-byte signatures.
estimateSizefunctionestimateSize(spec: { inputs: readonly InputSizeDescriptor[]; outputs: readonly OutputSizeDescriptor[]; }): number;Serialized size of a legacy transaction with the given inputs and outputs. Exact for the given scriptSig sizes; for P2PKH/multisig descriptors it assumes 72-byte signatures, so real signed transactions are the same size or a few bytes smaller (never larger). Typical values: 1-in/2-out P2PKH = 226 bytes, one P2PKH input = 148 bytes, one 2-of-3 P2SH input = 297 bytes.
feeForSizefunctionfeeForSize(sizeBytes: number, feeRatePerKb?: bigint): bigint;Fee in koinu for `sizeBytes` at a rate in koinu per 1000 bytes, truncated, at least 1 koinu (Core's CFeeRate::GetFee).
HARD_DUST_LIMITconstHARD_DUST_LIMIT: bigintHard dust limit in koinu: 0.001 DOGE. Outputs below it are never relayed.
HIGH_FEE_RATEconstHIGH_FEE_RATE: bigintFee rate (koinu per 1000 bytes) above which Core warns: 10 DOGE/kB.
INCREMENTAL_RELAY_FEE_RATEconstINCREMENTAL_RELAY_FEE_RATE: bigintFee rate step (koinu per 1000 bytes) for replacing or evicting mempool transactions: 0.0001 DOGE/kB.
InputSizeDescriptortypeInputSizeDescriptor = /** P2PKH spend: `<sig> <pubkey>`. Compressed key by default. */ { readonly type: 'p2pkh'; readonly compressed?: boolean; } /** P2SH m-of-n multisig spend: `OP_0 <sig>*m <redeemScript>`. Compressed keys by default. */ | { readonly type: 'p2sh-multisig'; readonly m: number; readonly n: number; readonly compressed?: boolean; } /** Any input with a known scriptSig length. */ ...Describes an input for size and fee estimation: a P2PKH spend, a P2SH multisig spend, or any scriptSig of known length.
isDustfunctionisDust(output: OutputLike, limit?: bigint): boolean;True if the output is spendable and its value in koinu is below `limit`.
isUnspendablefunctionisUnspendable(script: Uint8Array): boolean;True if no one can spend the output: its script starts with OP_RETURN or is over 10,000 bytes.
MIN_CHANGEconstMIN_CHANGE: bigintChange size, in koinu, that the wallet aims for during coin selection.
MIN_RELAY_FEE_RATEconstMIN_RELAY_FEE_RATE: bigintDefault minimum relay fee rate (koinu per 1000 bytes): 0.001 DOGE/kB.
minRelayFeefunctionminRelayFee(sizeBytes: number, outputs?: readonly OutputLike[]): bigint;Minimum fee in koinu that a default Dogecoin Core node requires to relay a transaction.
OutputLikeinterface{ value, script }The two things size, dust and fee functions need from an output: its value in koinu and its script.
OutputSizeDescriptortypeOutputSizeDescriptor = { readonly type: 'p2pkh' | 'p2sh'; } | { readonly script: Uint8Array; } | { readonly scriptSize: number; };Describes an output for size estimation: a standard P2PKH or P2SH output, a given script, or a script of known length.
RECOMMENDED_FEE_RATEconstRECOMMENDED_FEE_RATE: bigintRecommended fee rate (koinu per 1000 bytes): 0.01 DOGE/kB. The builder's default.
SOFT_DUST_LIMITconstSOFT_DUST_LIMIT: bigintSoft dust limit in koinu: 0.01 DOGE. Each output below it adds a penalty to the minimum fee.
WALLET_INCREMENTAL_RELAY_FEE_RATEconstWALLET_INCREMENTAL_RELAY_FEE_RATE: bigintFee rate step (koinu per 1000 bytes) when the wallet bumps a fee: 0.001 DOGE/kB.
walletRequiredFeefunctionwalletRequiredFee(sizeBytes: number, outputs?: readonly OutputLike[]): bigint;Fee in koinu that Core's wallet requires by default for a transaction of this size.
hd13 exports
NameKindSignatureWhat it does
Bip44Optionsinterface{ account?, change?, index?, coinType?, network? }Options for bip44Path: account, change chain and address index, all non-negative integers below 2^31.
bip44Pathfunctionbip44Path(options?: Bip44Options): string;BIP44 path `m/44'/coin'/account'/change/index`; on mainnet `m/44'/3'/0'/0/0` by default.
coreHdPathfunctioncoreHdPath(index: number): string;The fixed path Dogecoin Core 1.14's own HD wallet uses for its n-th key: `m/0'/3'/n'` (src/wallet/wallet.cpp:132-170, CWallet::DeriveNewChildKey). Only useful together with Core's HD master key (`hdmasterkeyid`).
englishWordlistconstenglishWordlist: readonly string[]The BIP39 English wordlist (default everywhere). Other lists: import from `@scure/bip39/wordlists/*`.
entropyToMnemonicfunctionentropyToMnemonic(entropy: Uint8Array, wordlist?: readonly string[]): string;Entropy (16, 20, 24, 28 or 32 bytes) to a mnemonic.
generateMnemonicfunctiongenerateMnemonic(strength?: MnemonicStrength, wordlist?: readonly string[]): string;Generates a BIP39 mnemonic (12 words for 128 bits ... 24 words for 256 bits) from `crypto.getRandomValues` via `@scure/bip39`. Default 256 bits (24 words).
HARDENED_OFFSETconstHARDENED_OFFSET = 2147483648BIP32 hardened index offset (Core: BIP32_HARDENED_KEY_LIMIT, src/wallet/wallet.cpp:50).
HDNodeclassclass: network, fromSeed(), fromMnemonic(), fromExtendedKey(), depth, index, parentFingerprint, fingerprint, identifier, chainCode, publicKey, privateKey, isPrivate, derive(), deriveChild(), neuter(), toExtendedPublicKey(), toExtendedPrivateKey(), toWif(), toAddress(), wipe(), toJSON(), toString(), [inspectSymbol]()A BIP32 node with Dogecoin version bytes, built on `@scure/bip32`.
MnemonicStrengthtypeMnemonicStrength = 128 | 160 | 192 | 224 | 256;Entropy bits of a BIP39 mnemonic: 128 (12 words), 160, 192, 224 or 256 (24 words).
mnemonicToEntropyfunctionmnemonicToEntropy(mnemonic: string, wordlist?: readonly string[]): Uint8Array;Mnemonic to its entropy bytes (validates the checksum).
mnemonicToSeedfunctionmnemonicToSeed(mnemonic: string, passphrase?: string, wordlist?: readonly string[]): Promise<Uint8Array>;BIP39 seed (64 bytes, PBKDF2-HMAC-SHA512, 2048 rounds). The mnemonic is validated against `wordlist` first: unlike raw BIP39, an invalid mnemonic is rejected rather than silently producing a seed.
mnemonicToSeedSyncfunctionmnemonicToSeedSync(mnemonic: string, passphrase?: string, wordlist?: readonly string[]): Uint8Array;Synchronous mnemonicToSeed (blocks for the 2048 PBKDF2 rounds).
validateMnemonicfunctionvalidateMnemonic(mnemonic: string, wordlist?: readonly string[]): boolean;True if the mnemonic has a valid length, known words and a valid checksum.
keys10 exports
NameKindSignatureWhat it does
convertPublicKeyfunctionconvertPublicKey(publicKey: Uint8Array, compressed: boolean): Uint8Array;Converts between compressed and uncompressed encodings of a public key.
DecodedWifinterface{ privateKey, compressed, network }Result of decodeWif: the 32-byte private key, whether the public key is compressed, and the network.
decodeWiffunctiondecodeWif(wif: string, network?: Network): DecodedWif;Decodes and validates a WIF private key.
encodeWiffunctionencodeWif(privateKey: Uint8Array, options?: WifOptions): string;Encodes a private key as WIF: Base58Check(version || key || [0x01 if compressed]). Core: CBitcoinSecret::SetKey (src/base58.cpp).
generatePrivateKeyfunctiongeneratePrivateKey(): Uint8Array;Generates a new random private key using
getPublicKeyfunctiongetPublicKey(privateKey: Uint8Array, compressed?: boolean): Uint8Array;Derives the public key; compressed (33 bytes) by default, or uncompressed (65 bytes).
isValidPrivateKeyfunctionisValidPrivateKey(key: Uint8Array): boolean;True if `key` is 32 bytes and 1 <= key < n (the secp256k1 order).
isValidPublicKeyfunctionisValidPublicKey(key: Uint8Array): boolean;True if `key` is a valid 33-byte compressed or 65-byte uncompressed secp256k1 point.
isValidWiffunctionisValidWif(wif: string, network?: Network): boolean;True if `wif` is a valid WIF key (optionally for the given network).
WifOptionsinterface{ network?, compressed? }Options for encodeWif: the network (default mainnet) and whether the public key is compressed.
message8 exports
NameKindSignatureWhat it does
messageHashfunctionmessageHash(message: string | Uint8Array, magic?: string): Uint8Array;The 32-byte digest Core signs for a message (`CHashWriter << strMessageMagic << strMessage`, then `GetHash()`). Strings are encoded as UTF-8.
recoverCompactfunctionrecoverCompact(hash: Uint8Array, signature: Uint8Array): RecoveredKey;Low-level: recovers the public key from a 65-byte compact signature, as Core's CPubKey::RecoverCompact (src/pubkey.cpp:188-206).
RecoveredKeyinterface{ publicKey, compressed }Result of recoverCompact: the public key a compact signature was made with, and whether it is the compressed form.
recoverMessageSignerfunctionrecoverMessageSigner(message: string | Uint8Array, signature: string, network?: Network): RecoveredKey & { readonly address: string; };Recovers the signer of a base64 message signature. Returns the public key and the P2PKH address it corresponds to on `network`. Throws DogeError on malformed input.
signCompactfunctionsignCompact(hash: Uint8Array, privateKey: Uint8Array, compressed?: boolean): Uint8Array;Low-level: 65-byte compact recoverable signature of a 32-byte hash, as Core's CKey::SignCompact. RFC 6979 deterministic nonces and low-S, both as libsecp256k1 in Core; the signing itself is done by `@noble/curves`.
signMessagefunctionsignMessage(message: string | Uint8Array, key: string | Uint8Array, options?: SignMessageOptions): string;Signs a message like `dogecoin-cli signmessagewithprivkey`. Returns base64. `key` is a WIF string (any network) or a raw 32-byte private key.
SignMessageOptionsinterface{ compressed? }Options for signMessage.
verifyMessagefunctionverifyMessage(message: string | Uint8Array, address: string, signature: string, network?: Network): boolean;Verifies a message signature like `dogecoin-cli verifymessage`: recovers the public key and checks that its hash160 equals the P2PKH address's hash.
networks13 exports
NameKindSignatureWhat it does
DOGECOIN_COIN_TYPEconstDOGECOIN_COIN_TYPE = 3Dogecoin's registered BIP44 coin type (3), used on mainnet.
GENESIS_BLOCK_HASHESconstGENESIS_BLOCK_HASHES: Readonly<Record<NetworkName, string>>Genesis block hash of each built-in network, as displayed by Core (byte-reversed hex).
getGenesisHashfunctiongetGenesisHash(network: Network | NetworkName): string;Genesis block hash (displayed hex) of a built-in network.
getNetworkfunctiongetNetwork(name: NetworkName): Network;Looks up a built-in network by name.
mainnetconstmainnet: NetworkDogecoin main network parameters (address versions 0x1e and 0x16, WIF 0x9e, BIP32 xpub/xprv versions, BIP44 coin type 3). Frozen.
MESSAGE_MAGICconstMESSAGE_MAGIC = "Dogecoin Signed Message:\n"Prefix of signed messages, `Dogecoin Signed Message:` and a newline; the same on every network.
Networkinterface{ name, pubKeyHash, scriptHash, wif, bip32, messageMagic, bip44CoinType }Parameters that tell the networks apart: name, address and WIF version bytes, BIP32 versions, message magic and BIP44 coin type. Use mainnet, testnet or regtest.
networkFromGenesisHashfunctionnetworkFromGenesisHash(hash: string): Network | undefined;The built-in network whose genesis block has this hash, or `undefined` if none does. `hash` is 64 hex characters in displayed order (either case; no `0x` prefix). Throws INVALID_ARGUMENT for anything else. Use it to check that a node or indexer serves the chain you expect before trusting any other answer from it.
NetworkNametypeNetworkName = 'mainnet' | 'testnet' | 'regtest';Name of a built-in network: `mainnet`, `testnet` or `regtest`.
NETWORKSconstNETWORKS: readonly Network[]All built-in networks, in detection priority order.
regtestconstregtest: NetworkDogecoin regression-test network parameters (address versions 0x6f and 0xc4, WIF 0xef, BIP44 coin type 1). Frozen.
testnetconsttestnet: NetworkDogecoin test network parameters (address versions 0x71 and 0xc4, WIF 0xf1, BIP44 coin type 1). Frozen.
TESTNET_COIN_TYPEconstTESTNET_COIN_TYPE = 1BIP44 coin type 1, the SLIP-0044 type for "Testnet (all coins)"; used on testnet and regtest.
policy6 exports
NameKindSignatureWhat it does
checkStandardTxfunctioncheckStandardTx(tx: Transaction, options?: StandardTxOptions): StandardTxResult;Checks a transaction against Dogecoin Core's standardness (relay) rules.
isStandardTxfunctionisStandardTx(tx: Transaction, options?: StandardTxOptions): boolean;True if checkStandardTx passes.
MAX_STANDARD_SCRIPTSIG_SIZEconstMAX_STANDARD_SCRIPTSIG_SIZE = 1650Largest standard scriptSig, in bytes (1,650).
MAX_STANDARD_TX_WEIGHTconstMAX_STANDARD_TX_WEIGHT = 400000Largest standard transaction weight; a legacy transaction weighs 4 times its size, so a standard one is under 100,000 bytes.
StandardTxOptionsinterface{ hardDustLimit?, permitBareMultisig? }Core's relay settings for checkStandardTx: data carrier, dust limit (koinu) and bare multisig.
StandardTxResulttypeStandardTxResult = { readonly standard: true; } | { readonly standard: false; readonly reason: string; };Result of checkStandardTx: standard, or not standard with Core's reject reason.
psbt51 exports
NameKindSignatureWhat it does
addMultisigDescriptorToPsbtfunctionaddMultisigDescriptorToPsbt(psbt: Psbt, descriptor: MultisigDescriptor, options?: { readonly derivations?: readonly PsbtDerivation[]; }): Psbt;Attaches a multisig descriptor's redeem script to the inputs and outputs of a PSBT that use its address.
addPsbtRecordsfunctionaddPsbtRecords(psbt: Psbt, additions: readonly PsbtRecordAddition[], options?: PsbtReadOptions): Psbt;Low-level Updater: adds raw records (for example proprietary ones). Every record is validated as on reading; a key already present with a different value is PSBT_MISMATCH.
combinePsbtsfunctioncombinePsbts(psbts: readonly Psbt[], options?: PsbtCombineOptions): Psbt;Combiner: merges PSBTs of the same unsigned transaction (PSBT_MISMATCH otherwise) into one with every record of each. The result is in canonical order, so it does not depend on the order of the PSBTs given.
createPsbtfunctioncreatePsbt(tx: Transaction): Psbt;Creator: a PSBT for an unsigned transaction, with empty input and output maps. The transaction must be strict legacy, with every scriptSig empty, and smaller than a standard transaction.
decodePsbtfunctiondecodePsbt(input: Uint8Array | string, options?: PsbtReadOptions): Psbt;Reads a PSBT from bytes, or from base64 or hex text (whitespace ignored). Throws PSBT_FORMAT for text that is neither, plus every error of parsePsbt.
encodePsbtfunctionencodePsbt(psbt: Psbt): Uint8Array;The binary PSBT: every record in the order it is held, exactly as read or written.
extractPsbtTransactionfunctionextractPsbtTransaction(psbt: Psbt, options?: { readonly verify?: boolean; }): Transaction;Extractor: the network transaction, with each input's final scriptSig. Throws PSBT_INCOMPLETE if an input is not final. Unless `verify: false`, every input must carry its previous transaction (UTXO_UNVERIFIED) and the whole transaction must verify (INVALID_SIGNATURE).
finalizePsbtfunctionfinalizePsbt(psbt: Psbt): PsbtFinalizeResult;Builds the final scriptSigs of every input that has enough valid signatures.
formatPsbtPathfunctionformatPsbtPath(path: readonly number[]): string;Formats path elements as "m/44'/3'/0'/0/1".
inspectPsbtfunctioninspectPsbt(psbt: Psbt, options?: { readonly network?: Network; }): PsbtSummary;Summarises a PSBT for the user before signing: inputs and values, outputs, fee, signatures.
isPsbtFinalizedconstisPsbtFinalized: (psbt: Psbt) => booleanTrue if every input has a final scriptSig.
isPsbtTextfunctionisPsbtText(text: string): boolean;True if `text` looks like a PSBT in base64 ("cHNidP8") or hex ("70736274ff"), ignoring whitespace.
parsePsbtfunctionparsePsbt(bytes: Uint8Array, options?: PsbtReadOptions): Psbt;Parses a binary PSBT. Throws DogeError (PSBT_* codes, UTXO_MISMATCH) with a `path`.
parsePsbtPathfunctionparsePsbtPath(path: string): number[];Parses "m/44'/3'/0'/0/1" (or "44h/3h/...") into path elements.
Psbtinterface{ tx, global, inputs, outputs, hasWitnessFields }A validated PSBT (version 0). Immutable: every role returns a new one.
PSBT_DOGEJS_PREFIXconstPSBT_DOGEJS_PREFIX = "dogejs"Proprietary identifier of the records DogeJS writes (docs/PSBT.md section 4).
PSBT_LIMITSconstPSBT_LIMITS: Readonly<{ maxBytes: 10000000; maxRecordsPerMap: 1000; maxKeyLength: 10000; maxPreviousTxSize: 1000000; maxUnsignedTxSize: number; }>Limits applied to every PSBT read. Derivations: - the unsigned transaction must be smaller than a standard transaction (100,000 bytes, MAX_STANDARD_TX_WEIGHT / 4, Dogecoin Core src/policy/policy.h:34); - one previous transaction is at most 1,000,000 bytes (MAX_TX_SIZE, the consensus block size, src/consensus/consensus.h:17); - `maxBytes` bounds the whole PSBT (10 MB, e.g. 100 inputs with 100 kB previous transactions); base64 and hex text are bounded to match before decoding.
PSBT_MAGICconstPSBT_MAGIC: Uint8ArrayThe 5 magic bytes every PSBT starts with: "psbt" and 0xff.
PSBT_TYPESconstPSBT_TYPES: Readonly<{ GLOBAL_UNSIGNED_TX: 0; GLOBAL_XPUB: 1; GLOBAL_VERSION: 251; GLOBAL_PROPRIETARY: 252; IN_NON_WITNESS_UTXO: 0; IN_WITNESS_UTXO: 1; IN_PARTIAL_SIG: 2; IN_SIGHASH_TYPE: 3; IN_REDEEM_SCRIPT: 4; IN_WITNESS_SCRIPT: 5; IN_BIP32_DERIVATION: 6; IN_FINAL_SCRIPTSIG: 7; IN_FINAL_SCRIPTWITNESS: 8; IN_PROPRIETARY: 252; OUT_REDEEM_SCRIPT: 0; OUT_WITNESS_SCRIPT: 1; OUT_BIP32_DERIVATION: 2...Key types DogeJS knows, by map (BIP174 and its type registry).
PsbtCombineOptionsinterface{ onConflict? }Options for combinePsbts.
PsbtDerivationinterface{ publicKey, fingerprint, path }A BIP32 derivation: the key, its master key fingerprint and the path from that master.
PsbtFinalizeResultinterface{ psbt, finalized, skipped, complete }Result of finalizePsbt: the new PSBT, the inputs that were finalized and the ones skipped with the reason.
psbtFromBuiltTransactionfunctionpsbtFromBuiltTransaction(built: Pick<BuiltTransaction, 'tx' | 'prevouts'> & { readonly changeIndex?: number; }, options?: { readonly network?: Network; readonly feeRate?: bigint; }): Psbt;Creates a PSBT from a built transaction, with its previous transactions and redeem scripts.
PsbtGlobalinterface{ records, xpubs, version, proprietary, unknown }The global map of a PSBT: its records, extended public keys, version (always 0) and proprietary or unknown records.
PsbtInputinterface{ records, previousTx?, previousTxBytes?, partialSigs, sighashType?, redeemScript?, bip32Derivations, finalScriptSig?, proprietary, unknown, witness }One input of a PSBT: previous transaction, redeem script, partial signatures, sighash type, final scriptSig and derivation paths, plus every record in file order.
PsbtInputSummaryinterface{ index, txid, vout, sequence, value, script, utxo, address, kind, required, signatures, finalized, sighashType, derivations, witnessFields }What inspectPsbt reports about one input: outpoint, the output it spends (if known, and whether that is proven), signature count and whether it is final.
PsbtInputUpdateinterface{ previousTx?, redeemScript?, sighashType?, bip32Derivations? }What updatePsbtInput may add to an input. It only adds; it never changes or removes an existing record.
PsbtKeyValueinterface{ type, key, keyData, value }One key-value record exactly as in the PSBT.
psbtMultisigDescriptorsfunctionpsbtMultisigDescriptors(psbt: Psbt, network?: Network): MultisigDescriptor[];The P2SH multisig descriptors whose redeem scripts appear in the PSBT's inputs and outputs (each once).
psbtNetworkfunctionpsbtNetwork(psbt: Psbt): Network | null;The network a PSBT states in its DogeJS proprietary record, or null.
PsbtOutputinterface{ records, redeemScript?, bip32Derivations, proprietary, unknown, witness }One output map of a PSBT: redeem script, derivation paths and proprietary or unknown records, plus every record in file order.
PsbtOutputSummaryinterface{ index, value, script, address, change, derivations }What inspectPsbt reports about one output: value in koinu, script, address (null if not standard) and whether it is marked as change.
PsbtOutputUpdateinterface{ redeemScript?, bip32Derivations? }What updatePsbtOutput may add to an output. It only adds.
PsbtPartialSignatureinterface{ publicKey, signature }A signature in a PSBT input, with the public key it belongs to.
PsbtProprietaryinterface{ identifier, subtype, keyData, value }A proprietary record (type 0xFC), split into its parts.
PsbtReadOptionsinterface{ allowWitness? }Options for parsePsbt, decodePsbt and addPsbtRecords.
PsbtRecordAdditioninterface{ scope, index?, key, value }Where a record goes for addPsbtRecords.
PsbtSignOptionsinterface{ allowedSighashTypes?, inputs? }Options for signPsbt.
PsbtSignResultinterface{ psbt, signed, skipped }Result of signPsbt: the new PSBT, the signatures added and the inputs skipped with the reason.
PsbtSummaryinterface{ network, txid, inputs, outputs, inputTotal, outputTotal, fee, feeVerified, finalized, unknownRecords, proprietaryRecords, witnessRecords, size, warnings }Result of inspectPsbt: network, txid, inputs, outputs, totals and fee in koinu (null when an input value is unknown), and warnings.
psbtToBase64constpsbtToBase64: (psbt: Psbt) => stringSerialises a PSBT to base64 (the usual text form). Same bytes as encodePsbt.
psbtToHexconstpsbtToHex: (psbt: Psbt) => stringSerialises a PSBT to lowercase hex. Same bytes as encodePsbt.
psbtToTxFilefunctionpsbtToTxFile(psbt: Psbt, options?: PsbtToTxFileOptions): PsbtToTxFileResult;A PSBT as a DogeJS transaction file. Each input needs its value and script: from its previous transaction, or from a "dogejs" prevout record (UTXO_UNVERIFIED otherwise). Partial signatures and final scriptSigs become the file's signatures, which are all verified. BIP32 derivations, extended keys, sighash type fields, output redeem scripts, unknown, foreign proprietary and SegWit records have no place in the file: they are listed in `dropped`.
PsbtToTxFileOptionsinterface{ network?, requirePrevTx?, changeIndex? }Options for psbtToTxFile.
PsbtToTxFileResultinterface{ file, dropped }Result of psbtToTxFile: the transaction file and a plain-language list of what a transaction file cannot hold.
PsbtXpubinterface{ xpub, fingerprint, path }A global extended public key record of a PSBT: the 78-byte xpub, the master fingerprint and the derivation path.
signPsbtfunctionsignPsbt(psbt: Psbt, keys: readonly PrivateKeyInput[], options?: PsbtSignOptions): PsbtSignResult;Signer: signs every input it can with `keys` (raw 32-byte keys or WIF) and adds the signatures as partial signatures. Signatures are deterministic (RFC 6979, low S), byte-identical to signInputs for the same transaction and key.
txFileToPsbtfunctiontxFileToPsbt(file: TxFile, options?: TxFileToPsbtOptions): Psbt;Converts a DogeJS transaction file to a PSBT without losing anything.
TxFileToPsbtOptionsinterface{ descriptors?, derivations? }Options for txFileToPsbt.
updatePsbtInputfunctionupdatePsbtInput(psbt: Psbt, index: number, update: PsbtInputUpdate): Psbt;Updater: adds data to input `index`. Data already present must be identical (PSBT_MISMATCH otherwise).
updatePsbtOutputfunctionupdatePsbtOutput(psbt: Psbt, index: number, update: PsbtOutputUpdate): Psbt;Updater: adds data to output `index`.
script31 exports
NameKindSignatureWhat it does
addressToScriptfunctionaddressToScript(address: string, network?: Network): Uint8Array;scriptPubKey for a P2PKH or P2SH address. The address must belong to `network` (default mainnet).
ClassifiedScripttypeClassifiedScript = { readonly type: 'pubkey'; readonly pubkey: Uint8Array; } | { readonly type: 'pubkeyhash'; readonly hash: Uint8Array; } | { readonly type: 'scripthash'; readonly hash: Uint8Array; } | { readonly type: 'multisig'; readonly m: number; readonly n: number; readonly pubkeys: readonly Uint8Array[]; } | { readonly type: 'nulldata'; } | { readonly type: 'witness_v0_keyhash'; readonly...A recognised standard scriptPubKey and its parts, as returned by classifyScript. `type` tells which fields are present.
classifyScriptfunctionclassifyScript(script: Uint8Array): ClassifiedScript;Classifies a scriptPubKey exactly as Core's Solver does. Like Core, pushes are matched by length only (a P2PKH template written with OP_PUSHDATA1 still matches; P2PK/multisig keys are 33..65-byte pushes that are not checked to be valid points). Witness programs are reported, but they are not standard on Dogecoin, where SegWit is not active (see isStandardScriptPubKey).
compileScriptfunctioncompileScript(elements: ReadonlyArray<number | Uint8Array | ScriptChunk>): Uint8Array;Serializes a script. Each element is either an opcode number (a non-push opcode, or OP_0), a Uint8Array (pushed minimally with encodePush), or a ScriptChunk (serialized with exactly its opcode, so that `compileScript(decompileScript(s))` reproduces `s` byte for byte).
decompileScriptfunctiondecompileScript(script: Uint8Array): ScriptChunk[];Parses a script into chunks. Throws INVALID_SCRIPT if a push runs past the end of the script (Core: GetOp fails, SCRIPT_ERR_BAD_OPCODE).
encodePushfunctionencodePush(data: Uint8Array): Uint8Array;Encodes `data` as a minimal script push (OP_0, OP_1..OP_16, a direct push, or OP_PUSHDATA1/2/4).
findAndDeletefunctionfindAndDelete(script: Uint8Array, pattern: Uint8Array): { script: Uint8Array; count: number; };Removes every op-aligned occurrence of `pattern` from a script (Core's FindAndDelete).
getSigOpCountfunctiongetSigOpCount(script: Uint8Array, accurate: boolean): number;Counts the signature operations of a script; `accurate` counts multisig by its key count.
hasMinimalPushesfunctionhasMinimalPushes(script: Uint8Array): boolean;True if every push in the script is minimal (and the script parses). Non-push ops are ignored.
isMinimalPushfunctionisMinimalPush(opcode: number, data: Uint8Array): boolean;True if `data` is pushed with the shortest possible opcode (SCRIPT_VERIFY_MINIMALDATA).
isP2shScriptfunctionisP2shScript(script: Uint8Array): boolean;True if the script is a P2SH scriptPubKey (`OP_HASH160 <20 bytes> OP_EQUAL`).
isPushOnlyfunctionisPushOnly(script: Uint8Array, start?: number): boolean;True if the script contains only data pushes and parses.
isStandardScriptPubKeyfunctionisStandardScriptPubKey(script: Uint8Array, options?: StandardScriptOptions): boolean;True if Dogecoin Core would relay an output with this scriptPubKey.
MAX_BARE_MULTISIG_KEYSconstMAX_BARE_MULTISIG_KEYS = 3Most keys in a standard bare multisig output (3).
MAX_OP_RETURN_RELAYconstMAX_OP_RETURN_RELAY = 83Largest standard OP_RETURN scriptPubKey in bytes (83).
MAX_P2SH_SIGOPSconstMAX_P2SH_SIGOPS = 15Most signature operations in a standard P2SH redeem script (15).
MAX_PUBKEYS_PER_MULTISIGconstMAX_PUBKEYS_PER_MULTISIG = 20Most keys in one CHECKMULTISIG, a consensus limit (20).
MAX_SCRIPT_ELEMENT_SIZEconstMAX_SCRIPT_ELEMENT_SIZE = 520Largest element a script can push, in bytes (520).
MAX_SCRIPT_SIZEconstMAX_SCRIPT_SIZE = 10000Largest script, in bytes (10,000).
MultisigOptionsinterface{ bare? }Options for multisigScript: `bare` makes a bare multisig scriptPubKey instead of a P2SH redeem script.
multisigScriptfunctionmultisigScript(m: number, publicKeys: readonly Uint8Array[], options?: MultisigOptions): Uint8Array;Builds an m-of-n multisig script (`OP_m <pubkeys> OP_n OP_CHECKMULTISIG`).
nullDataScriptfunctionnullDataScript(data: Uint8Array): Uint8Array;Builds an `OP_RETURN <data>` output script, a provably unspendable data output.
OPSconstOPS: Readonly<{ readonly OP_0: 0; readonly OP_FALSE: 0; readonly OP_PUSHDATA1: 76; readonly OP_PUSHDATA2: 77; readonly OP_PUSHDATA4: 78; readonly OP_1NEGATE: 79; readonly OP_RESERVED: 80; readonly OP_1: 81; readonly OP_TRUE: 81; readonly OP_2: 82; readonly OP_3: 83; readonly OP_4: 84; readonly OP_5: 85; readonly OP_6: 86; readonly OP_7: 87; readonly OP_8: 88; readonly OP_9: 89; readonly OP_10: ...Script opcodes by name (`OP_DUP`, `OP_CHECKSIG`, ...) with their byte values.
p2pkhScriptfunctionp2pkhScript(pubKeyHash: Uint8Array): Uint8Array;Builds a P2PKH scriptPubKey from a 20-byte public key hash.
p2pkScriptfunctionp2pkScript(publicKey: Uint8Array): Uint8Array;Builds a pay-to-public-key scriptPubKey from a public key.
p2shScriptfunctionp2shScript(scriptHash: Uint8Array): Uint8Array;Builds a P2SH scriptPubKey from a 20-byte script hash.
p2shScriptForRedeemScriptfunctionp2shScriptForRedeemScript(redeemScript: Uint8Array): Uint8Array;P2SH scriptPubKey for a redeem script (hash160 of the script).
ScriptChunkinterface{ opcode, data? }One parsed script element: an opcode and, for push opcodes (0x00..0x4e), the pushed data.
scriptToAddressfunctionscriptToAddress(script: Uint8Array, network?: Network): string;Address of a canonical P2PKH or P2SH scriptPubKey. Throws INVALID_SCRIPT for anything else, including P2PK and multisig (Core's ExtractDestination maps P2PK to the key's P2PKH address; DogeJS does not, because paying that address would create a different script) and non-canonical encodings.
ScriptTypetypeScriptType = 'pubkey' | 'pubkeyhash' | 'scripthash' | 'multisig' | 'nulldata' | 'witness_v0_keyhash' | 'witness_v0_scripthash' | 'nonstandard';Kind of standard script, named like Core's txnouttype.
StandardScriptOptionsinterface{ acceptDataCarrier?, maxDataCarrierBytes? }Core's relay settings for standard scripts (`-datacarrier`, `-datacarriersize`), used by isStandardScriptPubKey.
sighash6 exports
NameKindSignatureWhat it does
legacySighashfunctionlegacySighash(tx: Transaction, inputIndex: number, scriptCode: Uint8Array, hashType: number): Uint8Array;Legacy signature hash of input `inputIndex` for `hashType`.
SIGHASH_ALLconstSIGHASH_ALL = 1Hash type 1 (the default): the signature covers all inputs and all outputs.
SIGHASH_ANYONECANPAYconstSIGHASH_ANYONECANPAY = 128Hash-type flag (0x80): the signature covers only its own input. Combine with ALL, NONE or SINGLE using `|`.
SIGHASH_NONEconstSIGHASH_NONE = 2Hash type 2: the signature covers all inputs and no outputs. Anyone can change the outputs; use with care.
SIGHASH_SINGLEconstSIGHASH_SINGLE = 3Hash type 3: the signature covers all inputs and only the output with the same index as the input.
sighashToHexfunctionsighashToHex(hash: Uint8Array): string;Hex of a sighash in Core's display order (byte-reversed).
sign19 exports
NameKindSignatureWhat it does
combineMultisigInputfunctioncombineMultisigInput(tx: Transaction, inputIndex: number, scriptSigs: readonly Uint8Array[], redeemScript: Uint8Array, prevScript: Uint8Array): Transaction;Merges the signatures of several cosigners' copies of one multisig input into a transaction.
createSignaturefunctioncreateSignature(tx: Transaction, inputIndex: number, scriptCode: Uint8Array, privateKey: Uint8Array, hashType?: number): Uint8Array;Low-level: signs one input and returns `DER(r, s) || hashType`.
inspectMultisigInputfunctioninspectMultisigInput(tx: Transaction, inputIndex: number, redeemScript: Uint8Array, prevScript: Uint8Array, options?: VerifyOptions): MultisigInputStatus;Lists which public keys have validly signed P2SH multisig input `inputIndex`, and which are still missing. `prevScript` must be the P2SH scriptPubKey of `redeemScript` (INVALID_SCRIPT otherwise). An empty scriptSig means nothing is signed yet; a scriptSig that is not a multisig scriptSig for this redeem script throws INVALID_SCRIPT. Each signature is checked against every key with verifyInputSignature; `complete` comes from verifyInput, so it also requires Core's in-order matching and the OP_0 dummy.
isValidSignatureEncodingfunctionisValidSignatureEncoding(sig: Uint8Array): boolean;True if `sig` is a strict DER signature followed by one hash-type byte (BIP66).
MultisigInputStatusinterface{ m, n, publicKeys, signed, missing, invalid, complete }Result of inspectMultisigInput: m, n, the script's keys and which of them have a valid signature so far.
multisigSignatureCountfunctionmultisigSignatureCount(tx: Transaction, inputIndex: number, redeemScript: Uint8Array, prevScript: Uint8Array): { have: number; need: number; };Number of signatures present and required in a P2SH multisig input.
MultisigSignerinterface{ keyIndex, publicKey, signature, hashType }One signature found in a P2SH multisig input, matched to its key.
Prevoutinterface{ script, value?, redeemScript? }The previous output an input spends.
PrivateKeyInputtypePrivateKeyInput = Uint8Array | string;A private key: 32 raw bytes, or a WIF string (which also says whether the public key is compressed).
signInputsfunctionsignInputs(tx: Transaction, prevouts: readonly Prevout[], keys: readonly PrivateKeyInput[], options?: { hashType?: number; }): Transaction;Signs every input of `tx` with the matching keys. `prevouts[i]` describes the output spent by input i (for example `BuiltTransaction.prevouts`).
SignMultisigOptionsinterface{ hashType? }Options for signP2shMultisigInput.
signP2pkhInputfunctionsignP2pkhInput(tx: Transaction, inputIndex: number, key: PrivateKeyInput, prevScript: Uint8Array, options?: SignP2pkhOptions): Transaction;Signs P2PKH input `inputIndex`, which spends an output with scriptPubKey `prevScript`. Throws if the key does not match the script's public-key hash. Returns a new transaction; the input's scriptSig becomes `<sig> <pubkey>`.
SignP2pkhOptionsinterface{ hashType?, compressed? }Options for signP2pkhInput.
signP2shMultisigInputfunctionsignP2shMultisigInput(tx: Transaction, inputIndex: number, key: PrivateKeyInput, redeemScript: Uint8Array, prevScript: Uint8Array, options?: SignMultisigOptions): Transaction;Adds one signature to P2SH multisig input `inputIndex`. `prevScript` must be the P2SH scriptPubKey of `redeemScript`. Existing signatures in the input's scriptSig are kept; the result is always in Core's format (key order, OP_0 dummy, OP_0 placeholders while incomplete), so it can be passed to another signer, to combineMultisigInput, or to Core's signrawtransaction.
verifyInputfunctionverifyInput(tx: Transaction, inputIndex: number, prevScript: Uint8Array, options?: VerifyOptions): VerifyResult;Checks the signatures of input `inputIndex` against `prevScript`, the scriptPubKey of the output it spends. Supports P2PKH, P2PK, bare multisig and P2SH wrapping any of those. Never throws for bad signatures or scripts; see the module notes for what this does not check.
verifyInputSignaturefunctionverifyInputSignature(tx: Transaction, inputIndex: number, scriptCode: Uint8Array, signature: Uint8Array, publicKey: Uint8Array, options?: VerifyOptions): boolean;Checks one signature against one public key for one input (a single CHECKSIG).
VerifyOptionsinterface{ requireLowS? }Options for verifyInput (and the functions that call it).
VerifyResulttypeVerifyResult = { readonly valid: true; readonly type: string; } | { readonly valid: false; readonly type: string; readonly reason: string; };Result of verifyInput: valid, or invalid with the reason. Verification returns a result; it does not throw for a bad signature.
verifyTransactionfunctionverifyTransaction(tx: Transaction, prevouts: readonly Prevout[], options?: VerifyOptions): { readonly valid: boolean; readonly inputs: readonly VerifyResult[]; };Checks every input; `prevouts[i]` is the output spent by input i.
transaction16 exports
NameKindSignatureWhat it does
checkTransactionfunctioncheckTransaction(tx: Transaction): void;Checks a transaction's structure like Core's CheckTransaction (no signatures, no UTXO set).
decodeTransactionfunctiondecodeTransaction(input: Uint8Array | string): Transaction;Parses a legacy transaction from bytes or hex. Strict: canonical CompactSize only (as Core), no trailing bytes, no truncation. The BIP144 witness encoding is rejected with INVALID_TRANSACTION (SegWit is not active on Dogecoin).
encodeTransactionfunctionencodeTransaction(tx: Transaction): Uint8Array;Serializes a transaction in the legacy (non-witness) format.
encodeTransactionHexfunctionencodeTransactionHex(tx: Transaction): string;Lowercase hex of encodeTransaction.
getTransactionSizefunctiongetTransactionSize(tx: Transaction): number;Serialized size in bytes. For legacy transactions this is also Core's virtual size used for fees.
getTxidfunctiongetTxid(tx: Transaction | Uint8Array): string;Transaction id: double SHA-256 of the serialization, displayed byte-reversed (Core uint256::GetHex).
isValidTransactionfunctionisValidTransaction(tx: Transaction): boolean;True if Core's CheckTransaction would accept `tx`. Never throws.
MAX_STANDARD_TX_VERSIONconstMAX_STANDARD_TX_VERSION = 2Highest transaction version Core relays as standard (2).
MAX_TX_SIZEconstMAX_TX_SIZE = 1000000Largest serialized transaction, in bytes (1,000,000), a consensus limit.
normalizeTxidfunctionnormalizeTxid(txid: string): string;Validates and normalizes a displayed txid (64 hex chars) to lowercase.
SEQUENCE_FINALconstSEQUENCE_FINAL = 4294967295Input sequence number 0xffffffff: the input is final and ignores locktime.
Transactioninterface{ version, inputs, outputs, locktime }A decoded legacy Dogecoin transaction (no SegWit). Amounts are koinu (bigint); txids are displayed hex.
TX_VERSION_DEFAULTconstTX_VERSION_DEFAULT = 1Default transaction version (1).
TxInputinterface{ txid, vout, scriptSig, sequence }A transaction input: the outpoint (previous txid and output index), the scriptSig and the sequence number.
TxOutputinterface{ value, script }A transaction output: value in koinu and scriptPubKey.
withScriptSigfunctionwithScriptSig(tx: Transaction, index: number, scriptSig: Uint8Array): Transaction;Returns a copy of `tx` with input `index`'s scriptSig replaced.
txfile35 exports
NameKindSignatureWhat it does
addTxFileSignaturesfunctionaddTxFileSignatures(file: TxFile, signed: Transaction): TxFile;Adds the signatures of a further-signed copy of the same transaction to a transaction file.
canonicalJsonfunctioncanonicalJson(value: unknown): string;Canonical JSON of a JSON value (see the module notes). Throws FILE_SCHEMA for anything that is not a JSON value these files allow (undefined, bigint, non-integer or unsafe numbers, functions, class instances, unpaired surrogates) and FILE_TOO_LARGE past 64 levels of nesting.
createMultisigDescriptorfunctioncreateMultisigDescriptor(params: { readonly network: Network; readonly m: number; readonly publicKeys: readonly Uint8Array[]; }): MultisigDescriptor;Creates a descriptor for an m-of-n P2SH multisig. Keys are used in the order given (sort them yourself, e.g. BIP67, if your group agreed to). Throws as multisigScript: INVALID_ARGUMENT, INVALID_PUBLIC_KEY, NON_STANDARD.
createTxFilefunctioncreateTxFile(params: CreateTxFileParams): TxFile;Creates a validated transaction file. Every check parseTxFile makes is applied, so a file you create always reads back. Throws the same errors.
CreateTxFileParamsinterface{ network, tx, prevouts, changeIndex?, feeRate?, created?, note?, requirePrevTx? }Input of createTxFile: the network, a transaction (unsigned or partly signed), the output each input spends, and optional change index, fee rate, time and note.
FileSourceinterface{ format, version, checksummed }Where a parsed file came from.
FORBIDDEN_JSON_KEYSconstFORBIDDEN_JSON_KEYS: readonly string[]Keys rejected anywhere in a file (prototype-pollution vectors in naive consumers).
jsonChecksumfunctionjsonChecksum(body: unknown): string;The checksum string (`sha256:` plus hex) of a file body's canonical JSON.
JsonLimitsinterface{ maxTextLength, maxDepth, maxStringLength, maxArrayLength, maxObjectKeys }Size limits for parseStrictJson. Text longer or nesting deeper than these is refused with a FILE_* error.
JsonValuetypeJsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue; };Any value JSON can hold (null, boolean, number, string, array, object).
MULTISIG_DESCRIPTOR_FORMATconstMULTISIG_DESCRIPTOR_FORMAT = "dogejs-multisig"The `format` string of a multisig descriptor file (`dogejs-multisig`).
MULTISIG_DESCRIPTOR_LIMITSconstMULTISIG_DESCRIPTOR_LIMITS: Readonly<JsonLimits>Limits for multisig descriptors (much smaller files).
MULTISIG_DESCRIPTOR_VERSIONconstMULTISIG_DESCRIPTOR_VERSION = 2Version written by serializeMultisigDescriptor.
MultisigDescriptorinterface{ source, network, m, n, publicKeys, redeemScript, scriptPubKey, address }A validated P2SH multisig descriptor.
MultisigDescriptorJsoninterface{ format, version, network, type, m, n, publicKeys, redeemScript, scriptPubKey, address, checksum }The JSON object of a version 2 multisig descriptor.
multisigDescriptorToJsonfunctionmultisigDescriptorToJson(d: MultisigDescriptor): MultisigDescriptorJson;Version 2 JSON object of a descriptor, with a fresh checksum.
parseMultisigDescriptorfunctionparseMultisigDescriptor(text: string, options?: { readonly network?: Network; }): MultisigDescriptor;Parses and validates a multisig descriptor from its text (limits: MULTISIG_DESCRIPTOR_LIMITS).
parseStrictJsonfunctionparseStrictJson(text: string, limits: JsonLimits): JsonValue;Parses `text` as strict JSON within `limits`. Objects in the result have a null prototype. See the module notes for what is rejected.
parseTxFilefunctionparseTxFile(text: string, options?: TxFileReadOptions): TxFile;Parses and validates a transaction file from its text. See validateTxFile and TX_FILE_LIMITS.
serializeMultisigDescriptorfunctionserializeMultisigDescriptor(d: MultisigDescriptor): string;Text of a version 2 descriptor (two-space indented JSON and a final line break).
serializeTxFilefunctionserializeTxFile(file: TxFile): string;The text of a version 2 file: JSON with two-space indentation and a final line break. Always writes version 2, also for a file read from version 1 (this is the migration). Round-trip: `parseTxFile(serializeTxFile(f))` gives the same file.
TX_FILE_FORMATconstTX_FILE_FORMAT = "dogejs-tx"The `format` string of a transaction file (`dogejs-tx`).
TX_FILE_LIMITSconstTX_FILE_LIMITS: Readonly<JsonLimits & { maxInputs: number; maxOutputs: number; maxNoteLength: number; }>Limits enforced on every file read (and on files created). Derivations: - a standard transaction is under 100,000 bytes (MAX_STANDARD_TX_WEIGHT / 4, src/policy/policy.h:34) and an input is at least 41 bytes, so it has fewer than 2,440 inputs: `maxInputs` 2,500; an output is at least 9 bytes: `maxOutputs` 10,000; - one previous transaction is at most 1,000,000 bytes (MAX_BLOCK_BASE_SIZE, src/consensus/consensus.h:17), 2,000,000 hex characters: `maxStringLength`; - `maxTextLength` 16,000,000 characters bounds the whole file; - the transaction itself must be smaller than a standard transaction (100,000 bytes): a node would not relay a larger one, and this bounds the signature checks.
TX_FILE_VERSIONconstTX_FILE_VERSION = 2Version written by serializeTxFile.
TxFileinterface{ source, network, created?, note?, state, unsignedTx, tx, inputs, changeIndex, feeRate, fee, estimatedSize, summary }A validated transaction file.
TxFileInputinterface{ value, kind, required, signatures, complete }An input of a transaction file; usable directly as a prevout for signInputs / verifyTransaction / checkTransactionFee.
TxFileJsoninterface{ format, version, network, created?, note?, state, unsignedTx, inputs, summary, checksum }The JSON object of a version 2 transaction file.
TxFilePrevoutinterface{ value, script, redeemScript?, compressed?, prevTxHex? }What createTxFile needs about each input's previous output (a builder's `prevouts` entry fits).
TxFileReadOptionsinterface{ network?, requirePrevTx? }Options for parseTxFile and validateTxFile: the network the file must be for and whether previous transactions are required.
TxFileSignatureinterface{ publicKey, signature }One collected signature: DER plus hash-type byte, and the public key it is for.
TxFileStatetypeTxFileState = 'unsigned' | 'partial' | 'signed';How far a transaction file is signed: `unsigned`, `partial` (some signatures) or `signed` (every input complete).
TxFileSummaryinterface{ inputTotalKoinu, outputs, totalSentKoinu, feeKoinu, feeRateKoinuPerKb, estimatedSize }The human summary: every field is re-derived from the transaction when a file is read.
txFileToJsonfunctiontxFileToJson(file: TxFile): TxFileJson;The version 2 JSON object of a file, with a fresh checksum.
validateMultisigDescriptorfunctionvalidateMultisigDescriptor(value: unknown, options?: { readonly network?: Network; }): MultisigDescriptor;Validates a parsed descriptor: version 2, the command-line tool's "dogejs-multisig" v1, or the browser tools' "dogejs-multisig-descriptor" v1. Everything is re-derived from m, the keys and the network; any difference is FILE_MISMATCH. Other errors: FILE_FORMAT, FILE_VERSION, FILE_SCHEMA, FILE_CHECKSUM, WRONG_NETWORK.
validateTxFilefunctionvalidateTxFile(value: unknown, options?: TxFileReadOptions): TxFile;Validates an already-parsed JSON value as a transaction file: version 2, or one of the legacy formats (see the module notes). Prefer parseTxFile, which also applies the size, depth and key rules to the text.

Self-hosting and source

Source: github.com/DogeJS-Dev/core (package @dogejs/core).

Shell
git clone https://github.com/DogeJS-Dev/core
cd core
npm install
npm run build
npm test

FAQ

Does it work in the browser?

Yes. It is plain TypeScript with no Node-only code; the examples above also run in Node 20+.

Why bigint?

Money is a bigint count of koinu (1 DOGE = 100,000,000 koinu), never a float, so no rounding error can change an amount.

Does it talk to the network?

No. It builds, signs and checks. Fetching coins and broadcasting is the job of backends.

Are the keys safe to paste into a web page?

Keep real keys on a machine you control. The browser tools run locally and send nothing, but a key in clipboard history or a screenshot is still exposed.