crypto-aio 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/CHANGELOG.md +151 -1
  2. package/README.md +32 -12
  3. package/dist/adapters/evm/builder.js +64 -4
  4. package/dist/adapters/evm/builder.js.map +1 -1
  5. package/dist/adapters/evm/decode.js +6 -1
  6. package/dist/adapters/evm/decode.js.map +1 -1
  7. package/dist/adapters/evm/ethers-client.js +4 -0
  8. package/dist/adapters/evm/ethers-client.js.map +1 -1
  9. package/dist/adapters/evm/fees.d.ts +24 -0
  10. package/dist/adapters/evm/fees.js +47 -4
  11. package/dist/adapters/evm/fees.js.map +1 -1
  12. package/dist/adapters/evm/index.d.ts +1 -1
  13. package/dist/adapters/evm/index.js +2 -1
  14. package/dist/adapters/evm/index.js.map +1 -1
  15. package/dist/adapters/evm/network.d.ts +5 -0
  16. package/dist/adapters/evm/network.js +21 -2
  17. package/dist/adapters/evm/network.js.map +1 -1
  18. package/dist/adapters/evm/plugin.d.ts +5 -6
  19. package/dist/adapters/evm/plugin.js +50 -2
  20. package/dist/adapters/evm/plugin.js.map +1 -1
  21. package/dist/adapters/evm/proofs.js +17 -5
  22. package/dist/adapters/evm/proofs.js.map +1 -1
  23. package/dist/adapters/evm/reader.d.ts +18 -0
  24. package/dist/adapters/evm/reader.js +34 -0
  25. package/dist/adapters/evm/reader.js.map +1 -1
  26. package/dist/adapters/evm/tokens.d.ts +3 -0
  27. package/dist/adapters/evm/tokens.js.map +1 -1
  28. package/dist/adapters/evm/types.d.ts +10 -0
  29. package/dist/adapters/evm/types.js.map +1 -1
  30. package/dist/adapters/evm/web3-client.d.ts +6 -3
  31. package/dist/adapters/evm/web3-client.js +19 -2
  32. package/dist/adapters/evm/web3-client.js.map +1 -1
  33. package/dist/adapters/solana/builder.js +29 -18
  34. package/dist/adapters/solana/builder.js.map +1 -1
  35. package/dist/adapters/solana/fees.d.ts +12 -3
  36. package/dist/adapters/solana/fees.js +13 -4
  37. package/dist/adapters/solana/fees.js.map +1 -1
  38. package/dist/adapters/solana/message.d.ts +15 -0
  39. package/dist/adapters/solana/message.js +120 -0
  40. package/dist/adapters/solana/message.js.map +1 -0
  41. package/dist/adapters/solana/plugin.js +4 -1
  42. package/dist/adapters/solana/plugin.js.map +1 -1
  43. package/dist/adapters/solana/types.d.ts +8 -5
  44. package/dist/adapters/solana/types.js.map +1 -1
  45. package/dist/adapters/solana/web3.js +10 -32
  46. package/dist/adapters/solana/web3.js.map +1 -1
  47. package/dist/adapters/ton/proofs.js +18 -76
  48. package/dist/adapters/ton/proofs.js.map +1 -1
  49. package/dist/adapters/ton/reader.d.ts +45 -4
  50. package/dist/adapters/ton/reader.js +200 -5
  51. package/dist/adapters/ton/reader.js.map +1 -1
  52. package/dist/adapters/ton/trace.d.ts +26 -0
  53. package/dist/adapters/ton/trace.js +35 -9
  54. package/dist/adapters/ton/trace.js.map +1 -1
  55. package/dist/adapters/tron/abi.d.ts +2 -0
  56. package/dist/adapters/tron/abi.js +2 -0
  57. package/dist/adapters/tron/abi.js.map +1 -1
  58. package/dist/adapters/tron/builder.js +20 -4
  59. package/dist/adapters/tron/builder.js.map +1 -1
  60. package/dist/adapters/tron/decode.d.ts +2 -0
  61. package/dist/adapters/tron/decode.js +1 -1
  62. package/dist/adapters/tron/decode.js.map +1 -1
  63. package/dist/adapters/tron/proofs.js +1 -0
  64. package/dist/adapters/tron/proofs.js.map +1 -1
  65. package/dist/adapters/tron/reader.d.ts +10 -0
  66. package/dist/adapters/tron/reader.js +17 -0
  67. package/dist/adapters/tron/reader.js.map +1 -1
  68. package/dist/adapters/tron/tokens.d.ts +2 -0
  69. package/dist/adapters/tron/tokens.js.map +1 -1
  70. package/dist/adapters/utxo/builder.js +1 -1
  71. package/dist/adapters/utxo/builder.js.map +1 -1
  72. package/dist/adapters/utxo/chains.js +2 -1
  73. package/dist/adapters/utxo/chains.js.map +1 -1
  74. package/dist/adapters/utxo/context.d.ts +6 -0
  75. package/dist/adapters/utxo/context.js +8 -1
  76. package/dist/adapters/utxo/context.js.map +1 -1
  77. package/dist/adapters/utxo/decode.d.ts +8 -0
  78. package/dist/adapters/utxo/decode.js +36 -0
  79. package/dist/adapters/utxo/decode.js.map +1 -1
  80. package/dist/adapters/utxo/driver.js +5 -0
  81. package/dist/adapters/utxo/driver.js.map +1 -1
  82. package/dist/adapters/utxo/esplora.d.ts +23 -2
  83. package/dist/adapters/utxo/esplora.js +49 -2
  84. package/dist/adapters/utxo/esplora.js.map +1 -1
  85. package/dist/adapters/utxo/proofs.d.ts +15 -6
  86. package/dist/adapters/utxo/proofs.js +185 -47
  87. package/dist/adapters/utxo/proofs.js.map +1 -1
  88. package/dist/adapters/utxo/rawblock.d.ts +46 -0
  89. package/dist/adapters/utxo/rawblock.js +159 -0
  90. package/dist/adapters/utxo/rawblock.js.map +1 -0
  91. package/dist/adapters/utxo/rawtx.d.ts +14 -0
  92. package/dist/adapters/utxo/rawtx.js +44 -14
  93. package/dist/adapters/utxo/rawtx.js.map +1 -1
  94. package/dist/core/blockchain/handle.d.ts +6 -27
  95. package/dist/core/blockchain/handle.js +112 -112
  96. package/dist/core/blockchain/handle.js.map +1 -1
  97. package/dist/core/config/types.d.ts +15 -0
  98. package/dist/core/config/types.js.map +1 -1
  99. package/dist/core/container/container.d.ts +1 -8
  100. package/dist/core/container/container.js +42 -8
  101. package/dist/core/container/container.js.map +1 -1
  102. package/dist/core/driver/types.d.ts +34 -1
  103. package/dist/core/driver/types.js.map +1 -1
  104. package/dist/core/errors/codes.d.ts +10 -0
  105. package/dist/core/errors/codes.js +4 -0
  106. package/dist/core/errors/codes.js.map +1 -1
  107. package/dist/core/lifecycle/engine-rules.d.ts +3 -4
  108. package/dist/core/lifecycle/engine-rules.js +16 -6
  109. package/dist/core/lifecycle/engine-rules.js.map +1 -1
  110. package/dist/core/lifecycle/engine.d.ts +2 -0
  111. package/dist/core/lifecycle/engine.js +19 -1
  112. package/dist/core/lifecycle/engine.js.map +1 -1
  113. package/dist/core/lifecycle/evaluate.js +9 -4
  114. package/dist/core/lifecycle/evaluate.js.map +1 -1
  115. package/dist/core/lifecycle/monitor.js +16 -6
  116. package/dist/core/lifecycle/monitor.js.map +1 -1
  117. package/dist/core/lifecycle/reconcile.d.ts +1 -1
  118. package/dist/core/lifecycle/reconcile.js +1 -1
  119. package/dist/core/lifecycle/reconcile.js.map +1 -1
  120. package/dist/core/lifecycle/workers.d.ts +9 -3
  121. package/dist/core/lifecycle/workers.js +32 -14
  122. package/dist/core/lifecycle/workers.js.map +1 -1
  123. package/dist/core/model/ids.d.ts +1 -0
  124. package/dist/core/model/ids.js +1 -0
  125. package/dist/core/model/ids.js.map +1 -1
  126. package/dist/core/model/ordering.d.ts +8 -0
  127. package/dist/core/model/ordering.js.map +1 -1
  128. package/dist/core/model/transaction.d.ts +7 -0
  129. package/dist/core/model/transaction.js.map +1 -1
  130. package/dist/core/observe/scanner.js +3 -0
  131. package/dist/core/observe/scanner.js.map +1 -1
  132. package/dist/core/signing/wallet.js +8 -0
  133. package/dist/core/signing/wallet.js.map +1 -1
  134. package/dist/core/store/format.d.ts +20 -0
  135. package/dist/core/store/format.js +86 -0
  136. package/dist/core/store/format.js.map +1 -0
  137. package/dist/core/store/memory.js +2 -2
  138. package/dist/core/store/memory.js.map +1 -1
  139. package/dist/core/store/types.d.ts +15 -3
  140. package/dist/core/store/types.js +2 -0
  141. package/dist/core/store/types.js.map +1 -1
  142. package/dist/core/transport/http-transport.js +21 -13
  143. package/dist/core/transport/http-transport.js.map +1 -1
  144. package/dist/core/transport/types.d.ts +16 -1
  145. package/dist/core/transport/types.js.map +1 -1
  146. package/dist/core/util/json.d.ts +7 -1
  147. package/dist/core/util/json.js +13 -4
  148. package/dist/core/util/json.js.map +1 -1
  149. package/dist/core/util/names.d.ts +6 -0
  150. package/dist/core/util/names.js +10 -0
  151. package/dist/core/util/names.js.map +1 -1
  152. package/dist/index.d.ts +2 -1
  153. package/dist/index.js +4 -2
  154. package/dist/index.js.map +1 -1
  155. package/dist/testing/contracts/operations.js +20 -1
  156. package/dist/testing/contracts/operations.js.map +1 -1
  157. package/dist/testing/env.d.ts +5 -0
  158. package/dist/testing/env.js +1 -1
  159. package/dist/testing/env.js.map +1 -1
  160. package/dist/testing/faulty-store.d.ts +2 -0
  161. package/dist/testing/faulty-store.js +5 -0
  162. package/dist/testing/faulty-store.js.map +1 -1
  163. package/package.json +17 -7
@@ -1 +1 @@
1
- {"version":3,"file":"proofs.js","sourceRoot":"","sources":["../../../src/adapters/tron/proofs.ts"],"names":[],"mappings":";;AAoKA,4CAsOC;AAED,4CA8CC;AAkBD,8CAmCC;AA3aD,mDAAqE;AAGrE,uCAA4C;AAC5C,qCAAwD;AACxD,iCAQgB;AAChB,uCAAyC;AAIzC,SAAS,SAAS;IAChB,OAAO,IAAI,qBAAa,CACtB,sBAAsB,EACtB,wCAAwC,CACzC,CAAC;AACJ,CAAC;AAED,6FAA6F;AAC7F,SAAS,aAAa,CAAC,IAAY;IACjC,OAAO,IAAI,qBAAa,CAAC,uBAAuB,EAAE,GAAG,IAAI,yBAAyB,EAAE;QAClF,SAAS,EAAE,IAAI;KAChB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,OAAO,GAAG,KAAK,CAAC;AACtB;;;GAGG;AACH,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB,6CAA6C;AAC7C,MAAM,SAAS,GAAG,EAAE,IAAI,GAAG,GAAG,EAAE,CAAC;AACjC,MAAM,KAAK,GAAG,gBAAgB,CAAC;AAC/B,oFAAoF;AACpF,MAAM,QAAQ,GAAG,gBAAgB,CAAC;AAClC;;;GAGG;AACH,MAAM,eAAe,GAAG,UAAU,CAAC;AAEnC,2FAA2F;AAC3F,SAAS,cAAc,CAAC,MAAe;IACrC,MAAM,GAAG,GAAI,MAA2E;QACtF,EAAE,YAAY,EAAE,QAAQ,CAAC;IAC3B,OAAO,OAAO,GAAG,EAAE,SAAS,KAAK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,EAAE,KAAK,EAAE,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;QAC5D,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Proofs, the block source and TronGrid history.\n *\n * Proofs: every read is a `proof` quorum\n * read, and each fact is attested at its own height, so no endpoint proposes a height:\n * - \"my solidified block's timestamp is at or past the expiration\" is a monotone predicate\n * quorum key on the latest solidified block; honest endpoints disagree only in the moment\n * it becomes true on one of them, which decides nothing;\n * - a block at a fixed height is read from the solidity node, which serves it only once it\n * is solidified there, keyed on its consensus facts;\n * - `finalizedHead` is the one unanchored read: one endpoint's view, trailed by\n * `PEER_SKEW` blocks, then attested at that height.\n * A stale or lagging answer is a retryable `PROVIDER_INCONSISTENT` or `PROVIDER_UNAVAILABLE`\n * and decides nothing.\n *\n * Which blocks can hold a transaction (java-tron GreatVoyage-v4.8.2.2 `d5c3d1d1`:\n * `Manager.processBlock` runs `processTransaction`, so `validateTapos` and `validateCommon`,\n * for each transaction, and only then records the block in the recent-block store and as\n * the head):\n * - expiry: a transaction is invalid in a block whose parent's timestamp is at or past\n * its expiration, and block timestamps strictly increase, so no block after the first one\n * at or past the expiration can hold it;\n * - TaPoS: only a block above the reference block, and at most `TAPOS_WINDOW` above it, can\n * hold it.\n *\n * \"Not included\": the solidity index (and TronGrid behind a load balancer) can lag, so an\n * empty index answer is never taken as absence: an expired verdict for a transfer the\n * index missed would let `rebuild` pay twice.\n * `includedFinal` answers `included: false` only once expiry is attested and a scan of every\n * block that could hold the transaction shows it absent, from the attested first block at or\n * past the SIGNED expiration (`expiresAtMs`, which `assemble` binds to the signed bytes) down\n * to just above the reference block. The floor is never a time derived from the expiration:\n * the build-time head and the local clock are claims, so the expiration can sit any distance\n * after the reference.\n * - The ordering (`TronExpiryOrdering`) carries the reference height the build-time head\n * claimed (`lastValidHeight − TAPOS_WINDOW`) and the signed `ref_block_hash`. Only the\n * height's low 16 bits are signed (`ref_block_bytes`), so the height is trusted only when\n * the attested solidified block there carries the signed hash: then the scan runs from the\n * top down to it.\n * - Otherwise (another block there, or a height at or above the top) the proof searches the\n * heights TaPoS can match: every block up to the top checks the reference against the latest\n * block at or below its parent with the signed low 16 bits, and its parent is at most 24 h\n * before the expiration (`MAXIMUM_TIME_UNTIL_EXPIRATION`). So the attested blocks at those\n * heights, from one TaPoS window below that 24 h mark up to the top, are the only possible\n * references. None carries the signed hash: no block can hold the transaction. One does:\n * the blocks in its TaPoS window (and not before the 24 h mark) are scanned.\n * - Either way, a block whose parent is more than 24 h before the expiration cannot hold the\n * transaction, so no scan goes below the first block at or past that mark.\n * - A missing or malformed stored hash decides nothing.\n * Each scanned block is read by hash under the quorum, its parent hash names the next, and the\n * walk must end on the attested block below the window. A scanned block that holds the\n * transaction while the index says nothing decides nothing.\n *\n * Read cost, each read a quorum read: the reference check is one; a scan is one per block in\n * the window (about 20 for a 60 s expiration). A reference older than a day (a build head that\n * named an old block), or the search below, adds a gallop and binary search for the block 24 h\n * before the expiration (a few reads, logarithmic in missed slots). The search, only when the\n * stored height is not the reference, adds one read per candidate height (two or three). A\n * scan never covers more than the blocks from that 24 h mark to the first block at or past the\n * expiration: at most a day of blocks (28,800 at one per 3-second slot, fewer when slots are\n * missed), and never more than one TaPoS window (65,536).\n */\nimport type {\n AddressHistorySource,\n BlockSource,\n DriverTransaction,\n ProofSource,\n} from '../../core/driver/types';\nimport { ConfigError, ProviderError } from '../../core/errors/error';\nimport type { OrderingData } from '../../core/model/ordering';\nimport type { Transport } from '../../core/transport/types';\nimport { toBase58Address } from './address';\nimport { decodeTransaction, verdictOf } from './decode';\nimport {\n MONITOR,\n PROOF,\n READ,\n historyPage,\n notServable,\n type RpcBlock,\n type TronBlockHeader,\n} from './http';\nimport { TAPOS_WINDOW } from './network';\nimport type { TronContext } from './reader';\nimport type { TronExpiryOrdering } from './types';\n\nfunction undecided(): ProviderError {\n return new ProviderError(\n 'PROVIDER_UNAVAILABLE',\n 'finalized state cannot decide this yet',\n );\n}\n\n/** Attested answers that the chain's own rules make impossible together: decides nothing. */\nfunction contradiction(what: string): ProviderError {\n return new ProviderError('PROVIDER_INCONSISTENT', `${what}, which decides nothing`, {\n retryable: true,\n });\n}\n\nconst SLOT_MS = 3_000;\n/**\n * How far `finalizedHead` trails one endpoint's solidified head: up to 6 s behind, and no\n * verdict reads it.\n */\nconst PEER_SKEW = 2n;\n/** java-tron's block heights are `long`s. */\nconst INT64_MAX = 2n ** 63n - 1n;\nconst TX_ID = /^[0-9a-f]{64}$/;\n/** A signed `ref_block_hash`: 8 bytes, lower-case hex, as the builder stores it. */\nconst REF_HASH = /^[0-9a-f]{16}$/;\n/**\n * java-tron's `MAXIMUM_TIME_UNTIL_EXPIRATION` (`Constant.java`): `validateCommon` refuses an\n * expiration more than 24 h after the parent block's time.\n */\nconst MAX_LIFETIME_MS = 86_400_000;\n\n/** The timestamp of a solidified-block answer, or -1 when it is not one (never agrees). */\nfunction solidTimestamp(answer: unknown): number {\n const raw = (answer as { block_header?: { raw_data?: { timestamp?: unknown } } } | null)\n ?.block_header?.raw_data;\n return typeof raw?.timestamp === 'number' ? raw.timestamp : -1;\n}\n\ninterface Bounds {\n /** The signed expiration. */\n readonly expiration: number;\n /** The reference height the build-time head claimed: only its low 16 bits are signed. */\n readonly reference: bigint;\n /** The signed `ref_block_hash`. */\n readonly refBlockHash: string;\n}\n\n/**\n * Where an Attempt can be, from its `TronExpiryOrdering`; null when a field is missing or\n * out of range, which decides nothing.\n */\nfunction attemptBounds(ordering: OrderingData): Bounds | null {\n if (ordering.kind !== 'expiry') return null;\n const { expiresAtMs, lastValidHeight, refBlockHash } =\n ordering as Partial<TronExpiryOrdering>;\n if (\n !Number.isSafeInteger(expiresAtMs) ||\n typeof lastValidHeight !== 'bigint' ||\n lastValidHeight < TAPOS_WINDOW ||\n lastValidHeight > INT64_MAX ||\n typeof refBlockHash !== 'string' ||\n !REF_HASH.test(refBlockHash)\n ) {\n return null;\n }\n return {\n expiration: expiresAtMs as number,\n reference: lastValidHeight - TAPOS_WINDOW,\n refBlockHash,\n };\n}\n\n/** Bytes 8..16 of a block id: what a transaction's `ref_block_hash` names. */\nconst hashBytes = (block: TronBlockHeader): string => block.id.slice(16, 32);\n\n/** Scanned blocks kept per driver: immutable chain data, so a retry is cheap. */\nconst SCAN_CACHE_SIZE = 1_024;\n\nexport function createTronProofs(ctx: TronContext): ProofSource {\n const { api } = ctx;\n // Only quorum-agreed blocks below an attested solidified block, keyed by hash: final.\n const scanned = new Map<string, RpcBlock>();\n\n /** The block `hash`, expected at `height`; cached only once its height checks out. */\n async function finalBlockByHash(\n hash: string,\n height: bigint,\n ): Promise<RpcBlock | null> {\n const cached = scanned.get(hash);\n if (cached) return cached;\n const block = await api.rpcBlock(hash, PROOF);\n if (block && block.number === height) {\n if (scanned.size >= SCAN_CACHE_SIZE) {\n scanned.delete(scanned.keys().next().value as string);\n }\n scanned.set(hash, block);\n }\n return block;\n }\n\n /** A block at a fixed height, attested as solidified on every quorum endpoint. */\n async function solidHeader(height: bigint): Promise<TronBlockHeader> {\n const header = await api.block('solid', height, PROOF);\n if (!header) throw undecided();\n return header;\n }\n\n /**\n * The latest solidified block when every quorum endpoint's solidified block is at or past\n * `expiration` (a monotone predicate), else null.\n */\n async function passedExpiry(expiration: number): Promise<TronBlockHeader | null> {\n const head = (await api.block('solid', undefined, {\n ...PROOF,\n quorumKey: (answer) => solidTimestamp(answer) >= expiration,\n })) as TronBlockHeader;\n return head.timestamp >= expiration ? head : null;\n }\n\n /**\n * The first solidified block at or past `time`, at or below `hi` (an attested block at or\n * past it). Block timestamps strictly increase, so \"at or past `time`\" is monotone in the\n * height: a gallop down from the slot estimate, then a binary search. Every probe is\n * an attested fixed-height read at or below `hi`, which every quorum endpoint has\n * solidified, so none can stall; the slot spacing only picks the first probe.\n */\n async function firstAtOrAfter(\n time: number,\n hi: TronBlockHeader,\n ): Promise<TronBlockHeader> {\n let high = hi;\n let low: TronBlockHeader | undefined;\n let step = BigInt(Math.max(1, Math.floor((hi.timestamp - time) / SLOT_MS)));\n while (low === undefined) {\n if (high.number === 0n) return high;\n const probe = await solidHeader(high.number > step ? high.number - step : 0n);\n if (probe.timestamp < time) {\n low = probe;\n } else {\n high = probe;\n step *= 2n;\n }\n }\n while (high.number - low.number > 1n) {\n const mid = await solidHeader((low.number + high.number) / 2n);\n if (mid.timestamp < time) low = mid;\n else high = mid;\n }\n return high;\n }\n\n /**\n * The first solidified block at or past `expiration`, or null while the quorum has not\n * solidified past it. Only the predicate is attested: the latest block's height and time\n * are one endpoint's word, so a block trailed by the peer skew is attested at its own height\n * (a freshest endpoint then stalls nothing), and the search runs at or below it\n * or, within the skew, up to the first block at the expiration, which every endpoint has\n * solidified (bounded, whatever the endpoint claimed).\n */\n async function expiryBlock(expiration: number): Promise<TronBlockHeader | null> {\n const seen = await passedExpiry(expiration);\n if (!seen) return null;\n let top = await solidHeader(seen.number > PEER_SKEW ? seen.number - PEER_SKEW : 0n);\n if (top.timestamp >= expiration) return firstAtOrAfter(expiration, top);\n while (top.timestamp < expiration) {\n if (top.number >= seen.number) throw undecided();\n top = await solidHeader(top.number + 1n);\n }\n return top;\n }\n\n /**\n * No block above the attested `floor`, at or below `last` and `top`, holds `id`: walked by\n * parent hash from the upper end, which must arrive at `floor`. Throws when anything cannot\n * be decided. Every height read is below `top`, which every quorum endpoint has solidified.\n */\n async function absentAbove(\n id: string,\n floor: TronBlockHeader,\n top: TronBlockHeader,\n last: bigint,\n ): Promise<void> {\n const end = last < top.number ? last : top.number;\n if (end <= floor.number) return;\n const start = end === top.number ? top : await solidHeader(end);\n let hash = start.id;\n for (let height = start.number; height > floor.number; height -= 1n) {\n const block = await finalBlockByHash(hash, height);\n // Missing, or not the block the parent chain leads to: an endpoint is behind or lying.\n if (!block || block.number !== height) throw undecided();\n // In a solidified block, yet the index said nothing: it lags. Decide later.\n if (block.transactions.includes(id)) throw undecided();\n hash = block.parentHash;\n }\n // The walk is bound at both ends: it must arrive at the attested block below the window.\n if (hash !== floor.id) {\n throw contradiction('the scanned blocks do not lead to the reference block');\n }\n }\n\n /**\n * Absence proven by scan; throws when anything cannot be decided. `top`\n * is the attested first block at or past the expiration: no block above it can hold `id`.\n */\n async function absent(id: string, bounds: Bounds, top: TronBlockHeader): Promise<void> {\n const { reference, refBlockHash } = bounds;\n /** The 24 h mark: only a block whose parent is at or after it can hold `id`. */\n const dayMark = bounds.expiration - MAX_LIFETIME_MS;\n // The stored height is the build-time head's claim: it bounds the scan only when the\n // attested block there carries the signed hash bytes.\n if (reference < top.number) {\n const named = await solidHeader(reference);\n if (hashBytes(named) === refBlockHash) {\n // A reference older than a day (a build head that named an old block) is\n // scanned only from the 24 h mark, as the search below does, never its whole window.\n const floor =\n named.timestamp < dayMark ? await firstAtOrAfter(dayMark, top) : named;\n await absentAbove(id, floor, top, reference + TAPOS_WINDOW);\n return;\n }\n }\n // Otherwise, the heights TaPoS can match: the signed low 16 bits, below the top, from one\n // TaPoS window below the first block within 24 h of the expiration (a block's parent is at\n // or after it). Every block up to the top checks the reference against one of them.\n const earliest = await firstAtOrAfter(dayMark, top);\n const low16 = reference % TAPOS_WINDOW;\n const from =\n earliest.number + 1n > TAPOS_WINDOW ? earliest.number + 1n - TAPOS_WINDOW : 0n;\n let height = from + ((low16 - (from % TAPOS_WINDOW) + TAPOS_WINDOW) % TAPOS_WINDOW);\n for (; height < top.number; height += TAPOS_WINDOW) {\n const candidate = await solidHeader(height);\n if (hashBytes(candidate) !== refBlockHash) continue;\n // Its TaPoS window, less the blocks whose parent is more than 24 h before the expiration.\n const floor = candidate.number >= earliest.number ? candidate : earliest;\n await absentAbove(id, floor, top, candidate.number + TAPOS_WINDOW);\n }\n }\n\n return {\n async finalizedHead() {\n // The unanchored exception: one endpoint's view, trailed by the peer skew, attested.\n const seen = (await api.block('solid', undefined, MONITOR)) as TronBlockHeader;\n const head = await solidHeader(\n seen.number > PEER_SKEW ? seen.number - PEER_SKEW : 0n,\n );\n return { height: head.number, hash: head.id, timestamp: head.timestamp };\n },\n\n async includedFinal(ref, ordering) {\n // Bounded before any work; our own Attempt's ref is always a txID.\n if (typeof ref.id !== 'string' || ref.id.length !== 64) throw undecided();\n const id = ref.id.toLowerCase();\n if (!TX_ID.test(id)) throw undecided();\n const info = await api.transactionInfo('solid', id, PROOF);\n if (info) {\n const [header, tx] = await Promise.all([\n api.block('solid', info.blockNumber, PROOF),\n api.transaction('solid', id, PROOF),\n ]);\n if (!header || !tx) throw undecided();\n // java-tron writes the block's time into each receipt (`blockTimeStamp`): a receipt\n // dated otherwise is not from the solidified block at its height.\n if (info.blockTimestamp !== header.timestamp) {\n throw contradiction('a receipt does not match its solidified block');\n }\n // `verdictOf` pairs the receipt with the transaction by id, reads the verdict\n // fields strictly and wants evidence that value moved; a contradiction decides\n // nothing.\n const verdict = verdictOf(ctx.codec, tx, info);\n return {\n included: true,\n success: verdict.success,\n blockHeight: info.blockNumber,\n blockHash: header.id,\n txHash: id,\n ...(verdict.reason !== undefined ? { reason: verdict.reason } : {}),\n };\n }\n const bounds = attemptBounds(ordering);\n if (!bounds) throw undecided();\n const top = await expiryBlock(bounds.expiration);\n if (!top) throw undecided();\n await absent(id, bounds, top);\n return { included: false };\n },\n\n async slotConsumed() {\n // Tron has no nonce or sequence: expiry is the only way an Attempt dies.\n return false;\n },\n\n async expired(ordering: OrderingData) {\n if (ordering.kind !== 'expiry' || !Number.isSafeInteger(ordering.expiresAtMs)) {\n return false;\n }\n return (await expiryBlock(ordering.expiresAtMs as number)) !== null;\n },\n\n async blockHash(height, level) {\n if (height < 0n || height > INT64_MAX) return null;\n const header = await api.block(\n level === 'finalized' ? 'solid' : 'full',\n height,\n PROOF,\n );\n return header?.id ?? null;\n },\n };\n}\n\nexport function createTronBlocks(ctx: TronContext): BlockSource {\n return {\n async header(height) {\n const header = await ctx.api.block('full', height, MONITOR);\n return header\n ? {\n height: header.number,\n hash: header.id,\n parentHash: header.parentId,\n timestamp: header.timestamp,\n }\n : null;\n },\n async transactions(block, filter) {\n // Genesis holds only the chain's initial allocations, which are not reported,\n // and java-tron answers `{}` for its receipts, which a scanner would retry for ever.\n if (block.height === 0n) return [];\n const read = await ctx.api.blockWithTransactions(block.height, MONITOR);\n if (!read || read.header.id !== block.hash) {\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n `block ${block.height} changed while scanning`,\n { retryable: true },\n );\n }\n // Receipts pair with transactions by id, never by position.\n const infos = new Map(read.infos.map((info) => [info.id, info]));\n const txs = read.transactions.map((tx) => {\n const info = infos.get(tx.id);\n if (!info) {\n throw new ProviderError(\n 'PROVIDER_UNAVAILABLE',\n 'a scanned block lacks a receipt',\n );\n }\n return decodeTransaction(ctx.codec, tx, info, block.hash);\n });\n if (!filter?.addresses?.length) return txs;\n const wanted = new Set(filter.addresses.map((a) => toBase58Address(a)));\n return txs.filter(\n (tx) =>\n wanted.has(String(tx.details.owner)) ||\n tx.transfers.some((t) => wanted.has(t.to) || t.from.some((f) => wanted.has(f))),\n );\n },\n };\n}\n\nconst CURSOR = /^([tx]):(.*)$/;\n/** The largest page TronGrid serves. */\nconst MAX_PAGE = 200;\n\n/**\n * TronGrid history, each entry re-read from the full node and decoded like any\n * transaction; confirmed (solidified) entries only (`historyPage`). Phase `t` is\n * `/transactions`: the account's own transactions, TRX sent to it and, for a contract\n * account, other accounts' calls to it. Phase `x` is `/transactions/trc20`: every TRC-20\n * transfer from or to it (a spender's `transferFrom` out of it included), less the account's\n * own calls, which phase `t` listed. A TRC-20 transfer a wallet only received is in phase `x`\n * alone (TronGrid, read-only on Nile, 2026-09-28), but a call to a contract account that moves\n * its own tokens comes in both phases, so callers dedupe on `transfer.id`.\n * Paging follows the raw page's fingerprint, never how many items survive the filter, and\n * an entry the node cannot serve yet decides nothing: dropping it would skip it for good.\n */\nexport function createTronHistory(\n ctx: TronContext,\n indexer: Transport,\n getTransaction: (id: string) => Promise<DriverTransaction | null>,\n): AddressHistorySource {\n return {\n async list(address, options) {\n const match = CURSOR.exec(options.cursor ?? 't:');\n if (!match) throw new ConfigError('CONFIG_INVALID', 'not a Tron history cursor');\n const phase = match[1] as 't' | 'x';\n const fingerprint = match[2] as string;\n const owner = toBase58Address(address);\n const page = await historyPage(\n indexer,\n owner,\n phase === 't' ? 'transactions' : 'trc20',\n {\n limit: Math.min(Math.max(Math.trunc(options.limit) || 1, 1), MAX_PAGE),\n ...(fingerprint ? { fingerprint } : {}),\n },\n READ,\n );\n const items: DriverTransaction[] = [];\n for (const id of page.ids) {\n const tx = await getTransaction(id);\n // The index lists it as confirmed: a node that serves nothing, or only its pool\n // copy, is behind; listing that copy would move the cursor past it for good.\n if (!tx || tx.observation.seen !== 'block') throw notServable();\n // Phase x skips the account's own calls: phase t listed them.\n if (!(phase === 'x' && tx.details.owner === owner)) items.push(tx);\n }\n const next = page.next ? `${phase}:${page.next}` : phase === 't' ? 'x:' : undefined;\n return { items, ...(next !== undefined ? { next } : {}) };\n },\n };\n}\n"]}
1
+ {"version":3,"file":"proofs.js","sourceRoot":"","sources":["../../../src/adapters/tron/proofs.ts"],"names":[],"mappings":";;AAoKA,4CAuOC;AAED,4CA8CC;AAkBD,8CAmCC;AA5aD,mDAAqE;AAGrE,uCAA4C;AAC5C,qCAAwD;AACxD,iCAQgB;AAChB,uCAAyC;AAIzC,SAAS,SAAS;IAChB,OAAO,IAAI,qBAAa,CACtB,sBAAsB,EACtB,wCAAwC,CACzC,CAAC;AACJ,CAAC;AAED,6FAA6F;AAC7F,SAAS,aAAa,CAAC,IAAY;IACjC,OAAO,IAAI,qBAAa,CAAC,uBAAuB,EAAE,GAAG,IAAI,yBAAyB,EAAE;QAClF,SAAS,EAAE,IAAI;KAChB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,OAAO,GAAG,KAAK,CAAC;AACtB;;;GAGG;AACH,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB,6CAA6C;AAC7C,MAAM,SAAS,GAAG,EAAE,IAA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E,IAAI,EAAE,CAAC,WAAW,CAAC,IAAI,KAAK,OAAO;oBAAE,MAAM,IAAA,kBAAW,GAAE,CAAC;gBAChE,8DAA8D;gBAC9D,IAAI,CAAC,CAAC,KAAK,KAAK,GAAG,IAAI,EAAE,CAAC,OAAO,CAAC,KAAK,KAAK,KAAK,CAAC;oBAAE,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACrE,CAAC;YACD,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,KAAK,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,KAAK,KAAK,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;YACpF,OAAO,EAAE,KAAK,EAAE,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;QAC5D,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Proofs, the block source and TronGrid history.\n *\n * Proofs: every read is a `proof` quorum\n * read, and each fact is attested at its own height, so no endpoint proposes a height:\n * - \"my solidified block's timestamp is at or past the expiration\" is a monotone predicate\n * quorum key on the latest solidified block; honest endpoints disagree only in the moment\n * it becomes true on one of them, which decides nothing;\n * - a block at a fixed height is read from the solidity node, which serves it only once it\n * is solidified there, keyed on its consensus facts;\n * - `finalizedHead` is the one unanchored read: one endpoint's view, trailed by\n * `PEER_SKEW` blocks, then attested at that height.\n * A stale or lagging answer is a retryable `PROVIDER_INCONSISTENT` or `PROVIDER_UNAVAILABLE`\n * and decides nothing.\n *\n * Which blocks can hold a transaction (java-tron GreatVoyage-v4.8.2.2 `d5c3d1d1`:\n * `Manager.processBlock` runs `processTransaction`, so `validateTapos` and `validateCommon`,\n * for each transaction, and only then records the block in the recent-block store and as\n * the head):\n * - expiry: a transaction is invalid in a block whose parent's timestamp is at or past\n * its expiration, and block timestamps strictly increase, so no block after the first one\n * at or past the expiration can hold it;\n * - TaPoS: only a block above the reference block, and at most `TAPOS_WINDOW` above it, can\n * hold it.\n *\n * \"Not included\": the solidity index (and TronGrid behind a load balancer) can lag, so an\n * empty index answer is never taken as absence: an expired verdict for a transfer the\n * index missed would let `rebuild` pay twice.\n * `includedFinal` answers `included: false` only once expiry is attested and a scan of every\n * block that could hold the transaction shows it absent, from the attested first block at or\n * past the SIGNED expiration (`expiresAtMs`, which `assemble` binds to the signed bytes) down\n * to just above the reference block. The floor is never a time derived from the expiration:\n * the build-time head and the local clock are claims, so the expiration can sit any distance\n * after the reference.\n * - The ordering (`TronExpiryOrdering`) carries the reference height the build-time head\n * claimed (`lastValidHeight − TAPOS_WINDOW`) and the signed `ref_block_hash`. Only the\n * height's low 16 bits are signed (`ref_block_bytes`), so the height is trusted only when\n * the attested solidified block there carries the signed hash: then the scan runs from the\n * top down to it.\n * - Otherwise (another block there, or a height at or above the top) the proof searches the\n * heights TaPoS can match: every block up to the top checks the reference against the latest\n * block at or below its parent with the signed low 16 bits, and its parent is at most 24 h\n * before the expiration (`MAXIMUM_TIME_UNTIL_EXPIRATION`). So the attested blocks at those\n * heights, from one TaPoS window below that 24 h mark up to the top, are the only possible\n * references. None carries the signed hash: no block can hold the transaction. One does:\n * the blocks in its TaPoS window (and not before the 24 h mark) are scanned.\n * - Either way, a block whose parent is more than 24 h before the expiration cannot hold the\n * transaction, so no scan goes below the first block at or past that mark.\n * - A missing or malformed stored hash decides nothing.\n * Each scanned block is read by hash under the quorum, its parent hash names the next, and the\n * walk must end on the attested block below the window. A scanned block that holds the\n * transaction while the index says nothing decides nothing.\n *\n * Read cost, each read a quorum read: the reference check is one; a scan is one per block in\n * the window (about 20 for a 60 s expiration). A reference older than a day (a build head that\n * named an old block), or the search below, adds a gallop and binary search for the block 24 h\n * before the expiration (a few reads, logarithmic in missed slots). The search, only when the\n * stored height is not the reference, adds one read per candidate height (two or three). A\n * scan never covers more than the blocks from that 24 h mark to the first block at or past the\n * expiration: at most a day of blocks (28,800 at one per 3-second slot, fewer when slots are\n * missed), and never more than one TaPoS window (65,536).\n */\nimport type {\n AddressHistorySource,\n BlockSource,\n DriverTransaction,\n ProofSource,\n} from '../../core/driver/types';\nimport { ConfigError, ProviderError } from '../../core/errors/error';\nimport type { OrderingData } from '../../core/model/ordering';\nimport type { Transport } from '../../core/transport/types';\nimport { toBase58Address } from './address';\nimport { decodeTransaction, verdictOf } from './decode';\nimport {\n MONITOR,\n PROOF,\n READ,\n historyPage,\n notServable,\n type RpcBlock,\n type TronBlockHeader,\n} from './http';\nimport { TAPOS_WINDOW } from './network';\nimport type { TronContext } from './reader';\nimport type { TronExpiryOrdering } from './types';\n\nfunction undecided(): ProviderError {\n return new ProviderError(\n 'PROVIDER_UNAVAILABLE',\n 'finalized state cannot decide this yet',\n );\n}\n\n/** Attested answers that the chain's own rules make impossible together: decides nothing. */\nfunction contradiction(what: string): ProviderError {\n return new ProviderError('PROVIDER_INCONSISTENT', `${what}, which decides nothing`, {\n retryable: true,\n });\n}\n\nconst SLOT_MS = 3_000;\n/**\n * How far `finalizedHead` trails one endpoint's solidified head: up to 6 s behind, and no\n * verdict reads it.\n */\nconst PEER_SKEW = 2n;\n/** java-tron's block heights are `long`s. */\nconst INT64_MAX = 2n ** 63n - 1n;\nconst TX_ID = /^[0-9a-f]{64}$/;\n/** A signed `ref_block_hash`: 8 bytes, lower-case hex, as the builder stores it. */\nconst REF_HASH = /^[0-9a-f]{16}$/;\n/**\n * java-tron's `MAXIMUM_TIME_UNTIL_EXPIRATION` (`Constant.java`): `validateCommon` refuses an\n * expiration more than 24 h after the parent block's time.\n */\nconst MAX_LIFETIME_MS = 86_400_000;\n\n/** The timestamp of a solidified-block answer, or -1 when it is not one (never agrees). */\nfunction solidTimestamp(answer: unknown): number {\n const raw = (answer as { block_header?: { raw_data?: { timestamp?: unknown } } } | null)\n ?.block_header?.raw_data;\n return typeof raw?.timestamp === 'number' ? raw.timestamp : -1;\n}\n\ninterface Bounds {\n /** The signed expiration. */\n readonly expiration: number;\n /** The reference height the build-time head claimed: only its low 16 bits are signed. */\n readonly reference: bigint;\n /** The signed `ref_block_hash`. */\n readonly refBlockHash: string;\n}\n\n/**\n * Where an Attempt can be, from its `TronExpiryOrdering`; null when a field is missing or\n * out of range, which decides nothing.\n */\nfunction attemptBounds(ordering: OrderingData): Bounds | null {\n if (ordering.kind !== 'expiry') return null;\n const { expiresAtMs, lastValidHeight, refBlockHash } =\n ordering as Partial<TronExpiryOrdering>;\n if (\n !Number.isSafeInteger(expiresAtMs) ||\n typeof lastValidHeight !== 'bigint' ||\n lastValidHeight < TAPOS_WINDOW ||\n lastValidHeight > INT64_MAX ||\n typeof refBlockHash !== 'string' ||\n !REF_HASH.test(refBlockHash)\n ) {\n return null;\n }\n return {\n expiration: expiresAtMs as number,\n reference: lastValidHeight - TAPOS_WINDOW,\n refBlockHash,\n };\n}\n\n/** Bytes 8..16 of a block id: what a transaction's `ref_block_hash` names. */\nconst hashBytes = (block: TronBlockHeader): string => block.id.slice(16, 32);\n\n/** Scanned blocks kept per driver: immutable chain data, so a retry is cheap. */\nconst SCAN_CACHE_SIZE = 1_024;\n\nexport function createTronProofs(ctx: TronContext): ProofSource {\n const { api } = ctx;\n // Only quorum-agreed blocks below an attested solidified block, keyed by hash: final.\n const scanned = new Map<string, RpcBlock>();\n\n /** The block `hash`, expected at `height`; cached only once its height checks out. */\n async function finalBlockByHash(\n hash: string,\n height: bigint,\n ): Promise<RpcBlock | null> {\n const cached = scanned.get(hash);\n if (cached) return cached;\n const block = await api.rpcBlock(hash, PROOF);\n if (block && block.number === height) {\n if (scanned.size >= SCAN_CACHE_SIZE) {\n scanned.delete(scanned.keys().next().value as string);\n }\n scanned.set(hash, block);\n }\n return block;\n }\n\n /** A block at a fixed height, attested as solidified on every quorum endpoint. */\n async function solidHeader(height: bigint): Promise<TronBlockHeader> {\n const header = await api.block('solid', height, PROOF);\n if (!header) throw undecided();\n return header;\n }\n\n /**\n * The latest solidified block when every quorum endpoint's solidified block is at or past\n * `expiration` (a monotone predicate), else null.\n */\n async function passedExpiry(expiration: number): Promise<TronBlockHeader | null> {\n const head = (await api.block('solid', undefined, {\n ...PROOF,\n quorumKey: (answer) => solidTimestamp(answer) >= expiration,\n })) as TronBlockHeader;\n return head.timestamp >= expiration ? head : null;\n }\n\n /**\n * The first solidified block at or past `time`, at or below `hi` (an attested block at or\n * past it). Block timestamps strictly increase, so \"at or past `time`\" is monotone in the\n * height: a gallop down from the slot estimate, then a binary search. Every probe is\n * an attested fixed-height read at or below `hi`, which every quorum endpoint has\n * solidified, so none can stall; the slot spacing only picks the first probe.\n */\n async function firstAtOrAfter(\n time: number,\n hi: TronBlockHeader,\n ): Promise<TronBlockHeader> {\n let high = hi;\n let low: TronBlockHeader | undefined;\n let step = BigInt(Math.max(1, Math.floor((hi.timestamp - time) / SLOT_MS)));\n while (low === undefined) {\n if (high.number === 0n) return high;\n const probe = await solidHeader(high.number > step ? high.number - step : 0n);\n if (probe.timestamp < time) {\n low = probe;\n } else {\n high = probe;\n step *= 2n;\n }\n }\n while (high.number - low.number > 1n) {\n const mid = await solidHeader((low.number + high.number) / 2n);\n if (mid.timestamp < time) low = mid;\n else high = mid;\n }\n return high;\n }\n\n /**\n * The first solidified block at or past `expiration`, or null while the quorum has not\n * solidified past it. Only the predicate is attested: the latest block's height and time\n * are one endpoint's word, so a block trailed by the peer skew is attested at its own height\n * (a freshest endpoint then stalls nothing), and the search runs at or below it\n * or, within the skew, up to the first block at the expiration, which every endpoint has\n * solidified (bounded, whatever the endpoint claimed).\n */\n async function expiryBlock(expiration: number): Promise<TronBlockHeader | null> {\n const seen = await passedExpiry(expiration);\n if (!seen) return null;\n let top = await solidHeader(seen.number > PEER_SKEW ? seen.number - PEER_SKEW : 0n);\n if (top.timestamp >= expiration) return firstAtOrAfter(expiration, top);\n while (top.timestamp < expiration) {\n if (top.number >= seen.number) throw undecided();\n top = await solidHeader(top.number + 1n);\n }\n return top;\n }\n\n /**\n * No block above the attested `floor`, at or below `last` and `top`, holds `id`: walked by\n * parent hash from the upper end, which must arrive at `floor`. Throws when anything cannot\n * be decided. Every height read is below `top`, which every quorum endpoint has solidified.\n */\n async function absentAbove(\n id: string,\n floor: TronBlockHeader,\n top: TronBlockHeader,\n last: bigint,\n ): Promise<void> {\n const end = last < top.number ? last : top.number;\n if (end <= floor.number) return;\n const start = end === top.number ? top : await solidHeader(end);\n let hash = start.id;\n for (let height = start.number; height > floor.number; height -= 1n) {\n const block = await finalBlockByHash(hash, height);\n // Missing, or not the block the parent chain leads to: an endpoint is behind or lying.\n if (!block || block.number !== height) throw undecided();\n // In a solidified block, yet the index said nothing: it lags. Decide later.\n if (block.transactions.includes(id)) throw undecided();\n hash = block.parentHash;\n }\n // The walk is bound at both ends: it must arrive at the attested block below the window.\n if (hash !== floor.id) {\n throw contradiction('the scanned blocks do not lead to the reference block');\n }\n }\n\n /**\n * Absence proven by scan; throws when anything cannot be decided. `top`\n * is the attested first block at or past the expiration: no block above it can hold `id`.\n */\n async function absent(id: string, bounds: Bounds, top: TronBlockHeader): Promise<void> {\n const { reference, refBlockHash } = bounds;\n /** The 24 h mark: only a block whose parent is at or after it can hold `id`. */\n const dayMark = bounds.expiration - MAX_LIFETIME_MS;\n // The stored height is the build-time head's claim: it bounds the scan only when the\n // attested block there carries the signed hash bytes.\n if (reference < top.number) {\n const named = await solidHeader(reference);\n if (hashBytes(named) === refBlockHash) {\n // A reference older than a day (a build head that named an old block) is\n // scanned only from the 24 h mark, as the search below does, never its whole window.\n const floor =\n named.timestamp < dayMark ? await firstAtOrAfter(dayMark, top) : named;\n await absentAbove(id, floor, top, reference + TAPOS_WINDOW);\n return;\n }\n }\n // Otherwise, the heights TaPoS can match: the signed low 16 bits, below the top, from one\n // TaPoS window below the first block within 24 h of the expiration (a block's parent is at\n // or after it). Every block up to the top checks the reference against one of them.\n const earliest = await firstAtOrAfter(dayMark, top);\n const low16 = reference % TAPOS_WINDOW;\n const from =\n earliest.number + 1n > TAPOS_WINDOW ? earliest.number + 1n - TAPOS_WINDOW : 0n;\n let height = from + ((low16 - (from % TAPOS_WINDOW) + TAPOS_WINDOW) % TAPOS_WINDOW);\n for (; height < top.number; height += TAPOS_WINDOW) {\n const candidate = await solidHeader(height);\n if (hashBytes(candidate) !== refBlockHash) continue;\n // Its TaPoS window, less the blocks whose parent is more than 24 h before the expiration.\n const floor = candidate.number >= earliest.number ? candidate : earliest;\n await absentAbove(id, floor, top, candidate.number + TAPOS_WINDOW);\n }\n }\n\n return {\n async finalizedHead() {\n // The unanchored exception: one endpoint's view, trailed by the peer skew, attested.\n const seen = (await api.block('solid', undefined, MONITOR)) as TronBlockHeader;\n const head = await solidHeader(\n seen.number > PEER_SKEW ? seen.number - PEER_SKEW : 0n,\n );\n return { height: head.number, hash: head.id, timestamp: head.timestamp };\n },\n\n async includedFinal(ref, ordering) {\n // Bounded before any work; our own Attempt's ref is always a txID.\n if (typeof ref.id !== 'string' || ref.id.length !== 64) throw undecided();\n const id = ref.id.toLowerCase();\n if (!TX_ID.test(id)) throw undecided();\n const info = await api.transactionInfo('solid', id, PROOF);\n if (info) {\n const [header, tx] = await Promise.all([\n api.block('solid', info.blockNumber, PROOF),\n api.transaction('solid', id, PROOF),\n ]);\n if (!header || !tx) throw undecided();\n // java-tron writes the block's time into each receipt (`blockTimeStamp`): a receipt\n // dated otherwise is not from the solidified block at its height.\n if (info.blockTimestamp !== header.timestamp) {\n throw contradiction('a receipt does not match its solidified block');\n }\n // `verdictOf` pairs the receipt with the transaction by id, reads the verdict\n // fields strictly and wants evidence that value moved; a contradiction decides\n // nothing.\n const verdict = verdictOf(ctx.codec, tx, info);\n return {\n included: true,\n success: verdict.success,\n blockHeight: info.blockNumber,\n blockHash: header.id,\n txHash: id,\n ...(verdict.reason !== undefined ? { reason: verdict.reason } : {}),\n ...(verdict.failure !== undefined ? { failure: verdict.failure } : {}),\n };\n }\n const bounds = attemptBounds(ordering);\n if (!bounds) throw undecided();\n const top = await expiryBlock(bounds.expiration);\n if (!top) throw undecided();\n await absent(id, bounds, top);\n return { included: false };\n },\n\n async slotConsumed() {\n // Tron has no nonce or sequence: expiry is the only way an Attempt dies.\n return false;\n },\n\n async expired(ordering: OrderingData) {\n if (ordering.kind !== 'expiry' || !Number.isSafeInteger(ordering.expiresAtMs)) {\n return false;\n }\n return (await expiryBlock(ordering.expiresAtMs as number)) !== null;\n },\n\n async blockHash(height, level) {\n if (height < 0n || height > INT64_MAX) return null;\n const header = await api.block(\n level === 'finalized' ? 'solid' : 'full',\n height,\n PROOF,\n );\n return header?.id ?? null;\n },\n };\n}\n\nexport function createTronBlocks(ctx: TronContext): BlockSource {\n return {\n async header(height) {\n const header = await ctx.api.block('full', height, MONITOR);\n return header\n ? {\n height: header.number,\n hash: header.id,\n parentHash: header.parentId,\n timestamp: header.timestamp,\n }\n : null;\n },\n async transactions(block, filter) {\n // Genesis holds only the chain's initial allocations, which are not reported,\n // and java-tron answers `{}` for its receipts, which a scanner would retry for ever.\n if (block.height === 0n) return [];\n const read = await ctx.api.blockWithTransactions(block.height, MONITOR);\n if (!read || read.header.id !== block.hash) {\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n `block ${block.height} changed while scanning`,\n { retryable: true },\n );\n }\n // Receipts pair with transactions by id, never by position.\n const infos = new Map(read.infos.map((info) => [info.id, info]));\n const txs = read.transactions.map((tx) => {\n const info = infos.get(tx.id);\n if (!info) {\n throw new ProviderError(\n 'PROVIDER_UNAVAILABLE',\n 'a scanned block lacks a receipt',\n );\n }\n return decodeTransaction(ctx.codec, tx, info, block.hash);\n });\n if (!filter?.addresses?.length) return txs;\n const wanted = new Set(filter.addresses.map((a) => toBase58Address(a)));\n return txs.filter(\n (tx) =>\n wanted.has(String(tx.details.owner)) ||\n tx.transfers.some((t) => wanted.has(t.to) || t.from.some((f) => wanted.has(f))),\n );\n },\n };\n}\n\nconst CURSOR = /^([tx]):(.*)$/;\n/** The largest page TronGrid serves. */\nconst MAX_PAGE = 200;\n\n/**\n * TronGrid history, each entry re-read from the full node and decoded like any\n * transaction; confirmed (solidified) entries only (`historyPage`). Phase `t` is\n * `/transactions`: the account's own transactions, TRX sent to it and, for a contract\n * account, other accounts' calls to it. Phase `x` is `/transactions/trc20`: every TRC-20\n * transfer from or to it (a spender's `transferFrom` out of it included), less the account's\n * own calls, which phase `t` listed. A TRC-20 transfer a wallet only received is in phase `x`\n * alone (TronGrid, read-only on Nile, 2026-09-28), but a call to a contract account that moves\n * its own tokens comes in both phases, so callers dedupe on `transfer.id`.\n * Paging follows the raw page's fingerprint, never how many items survive the filter, and\n * an entry the node cannot serve yet decides nothing: dropping it would skip it for good.\n */\nexport function createTronHistory(\n ctx: TronContext,\n indexer: Transport,\n getTransaction: (id: string) => Promise<DriverTransaction | null>,\n): AddressHistorySource {\n return {\n async list(address, options) {\n const match = CURSOR.exec(options.cursor ?? 't:');\n if (!match) throw new ConfigError('CONFIG_INVALID', 'not a Tron history cursor');\n const phase = match[1] as 't' | 'x';\n const fingerprint = match[2] as string;\n const owner = toBase58Address(address);\n const page = await historyPage(\n indexer,\n owner,\n phase === 't' ? 'transactions' : 'trc20',\n {\n limit: Math.min(Math.max(Math.trunc(options.limit) || 1, 1), MAX_PAGE),\n ...(fingerprint ? { fingerprint } : {}),\n },\n READ,\n );\n const items: DriverTransaction[] = [];\n for (const id of page.ids) {\n const tx = await getTransaction(id);\n // The index lists it as confirmed: a node that serves nothing, or only its pool\n // copy, is behind; listing that copy would move the cursor past it for good.\n if (!tx || tx.observation.seen !== 'block') throw notServable();\n // Phase x skips the account's own calls: phase t listed them.\n if (!(phase === 'x' && tx.details.owner === owner)) items.push(tx);\n }\n const next = page.next ? `${phase}:${page.next}` : phase === 't' ? 'x:' : undefined;\n return { items, ...(next !== undefined ? { next } : {}) };\n },\n };\n}\n"]}
@@ -36,6 +36,16 @@ export declare function trc20Contract(ref: AssetRef): string;
36
36
  export declare function tokenCall(ctx: TronContext, owner: string, contract: string, data: string, tags: TronCallTags): Promise<string>;
37
37
  /** A holder's TRC-20 balance. */
38
38
  export declare function trc20Balance(ctx: TronContext, contract: string, holder: string, tags?: TronCallTags): Promise<bigint>;
39
+ /**
40
+ * Whether a token answers `deprecated()` with `true`, as Tether's `TetherToken` (USDT on
41
+ * Tron) does once its owner deprecates it for an upgraded contract (`upgradedAddress`).
42
+ * Only a definitive answer decides: a contract without the method (a revert or VM failure,
43
+ * an answer that is not one ABI `bool`, or a node's "no contract", which the balance read
44
+ * beside it settles) is not deprecated. A node refusal or a malformed answer throws
45
+ * retryable, so a failed read is never taken for either answer. The contract's own
46
+ * account is the caller: it always exists.
47
+ */
48
+ export declare function trc20Deprecated(ctx: TronContext, contract: string, tags: TronCallTags): Promise<boolean>;
39
49
  /**
40
50
  * An included transaction's observation. `guard` applies the verdict guard (on-chain
41
51
  * evidence that value moved) to our own Attempts; without it (a status lookup by id,
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.trc20Contract = trc20Contract;
4
4
  exports.tokenCall = tokenCall;
5
5
  exports.trc20Balance = trc20Balance;
6
+ exports.trc20Deprecated = trc20Deprecated;
6
7
  exports.observeIncluded = observeIncluded;
7
8
  exports.createTronReader = createTronReader;
8
9
  exports.createTronExt = createTronExt;
@@ -73,6 +74,21 @@ async function trc20Balance(ctx, contract, holder, tags = http_1.READ) {
73
74
  throw tokenProblem('balanceOf returned no uint256');
74
75
  }
75
76
  }
77
+ /** An ABI `bool` that is `true`: one word, exactly 1 (constant results are lower-case). */
78
+ const TRUE_WORD = /^0{63}1$/;
79
+ /**
80
+ * Whether a token answers `deprecated()` with `true`, as Tether's `TetherToken` (USDT on
81
+ * Tron) does once its owner deprecates it for an upgraded contract (`upgradedAddress`).
82
+ * Only a definitive answer decides: a contract without the method (a revert or VM failure,
83
+ * an answer that is not one ABI `bool`, or a node's "no contract", which the balance read
84
+ * beside it settles) is not deprecated. A node refusal or a malformed answer throws
85
+ * retryable, so a failed read is never taken for either answer. The contract's own
86
+ * account is the caller: it always exists.
87
+ */
88
+ async function trc20Deprecated(ctx, contract, tags) {
89
+ const answer = await ctx.api.constantCall(contract, contract, abi_1.SELECTORS.deprecated, tags);
90
+ return answer.kind === 'ok' && TRUE_WORD.test(answer.result);
91
+ }
76
92
  /**
77
93
  * An included transaction's observation. `guard` applies the verdict guard (on-chain
78
94
  * evidence that value moved) to our own Attempts; without it (a status lookup by id,
@@ -100,6 +116,7 @@ async function observeIncluded(ctx, id, tags, guard) {
100
116
  blockHash: header.id,
101
117
  success: verdict.success,
102
118
  ...(verdict.reason ? { reason: verdict.reason } : {}),
119
+ ...(verdict.failure ? { failure: verdict.failure } : {}),
103
120
  };
104
121
  }
105
122
  function createTronReader(ctx) {
@@ -1 +1 @@
1
- {"version":3,"file":"reader.js","sourceRoot":"","sources":["../../../src/adapters/tron/reader.ts"],"names":[],"mappings":";;AAkEA,sCASC;AASD,8BAoBC;AAGD,oCAkBC;AAOD,0CA0BC;AAED,4CAmGC;AAGD,sCAOC;AAjQD,mDAIiC;AAKjC,+BAAgF;AAChF,uCAAyE;AACzE,qCAAsE;AACtE,iCAAmF;AAcnF,MAAM,KAAK,GAAG,gBAAgB,CAAC;AAC/B,6CAA6C;AAC7C,MAAM,SAAS,GAAG,EAAE,IAAI,GAAG,GAAG,EAAE,CAAC;AAEjC,wFAAwF;AACxF,SAAS,IAAI,CAAC,KAAa;IACzB,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,KAAK,EAAE;QAAE,OAAO,IAAI,CAAC;IAClE,MAAM,EAAE,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC;IAC/B,OAAO,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACpC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,QAAQ,GAAiB,EAAE,GAAG,WAAI,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC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AAG,IAAA,kBAAY,EAAC,UAAU,CAAC,CAAC;YACpC,CAAC;YAAC,MAAM,CAAC;gBACP,MAAM,YAAY,CAAC,+BAA+B,CAAC,CAAC;YACtD,CAAC;YACD,IAAI,QAAQ,GAAG,IAAI,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC3C,MAAM,YAAY,CAAC,iCAAiC,CAAC,CAAC;YACxD,CAAC;YACD,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;QAChD,CAAC;QACD,iBAAiB,CAAC,GAAa;YAC7B,IAAI,GAAG,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;gBAC7B,MAAM,IAAI,uBAAe,CACvB,kBAAkB,EAClB,oCAAoC,CACrC,CAAC;YACJ,CAAC;YACD,IAAI,CAAC,IAAA,uBAAa,EAAC,GAAG,CAAC,QAAQ,CAAC;gBAAE,MAAM,YAAY,CAAC,6BAA6B,CAAC,CAAC;YACpF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAA,yBAAe,EAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;QACxE,CAAC;KACF,CAAC;AACJ,CAAC;AAED,6CAA6C;AAC7C,SAAgB,aAAa,CAAC,GAAgB;IAC5C,OAAO;QACL,IAAI,EAAE;YACJ,YAAY,EAAE,CAAC,OAAe,EAA0B,EAAE,CACxD,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,IAAA,sBAAY,EAAC,OAAO,CAAC,EAAE,WAAI,CAAC;SACjD;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The Tron `ChainReader` and `ext.tron`. Tags follow the `ChainDriver` contract table:\n * reads `read`, heights and `observe` `monitor`. Addresses reach the node as `41…` hex.\n * A transaction the node holds but cannot serve whole yet (its receipt, its block) is a\n * retryable `PROVIDER_UNAVAILABLE`, never \"not seen\".\n */\nimport type {\n ChainReader,\n DriverBlock,\n DriverTransaction,\n DriverTxObservation,\n} from '../../core/driver/types';\nimport {\n ProviderError,\n UnsupportedCapabilityError,\n ValidationError,\n} from '../../core/errors/error';\nimport type { Logger } from '../../core/events/logger';\nimport type { AssetMetadata, AssetRef, TokenRef } from '../../core/model/asset';\nimport type { ChainInfo, NetworkInfo } from '../../core/model/chain';\nimport type { Clock } from '../../core/util/clock';\nimport { SELECTORS, decodeString, decodeUint256, encodeBalanceOf } from './abi';\nimport { isTronAddress, toBase58Address, toHexAddress } from './address';\nimport { chainVerdict, decodeTransaction, verdictOf } from './decode';\nimport { MONITOR, READ, notServable, type TronApi, type TronTxJson } from './http';\nimport type { TronNetworkConfig } from './network';\nimport type { TronCallTags, TronCodec, TronExt, TronResources } from './types';\n\nexport interface TronContext {\n readonly api: TronApi;\n readonly codec: TronCodec;\n readonly chain: ChainInfo;\n readonly network: NetworkInfo;\n readonly config: TronNetworkConfig;\n readonly clock: Clock;\n readonly log: Logger;\n}\n\nconst TX_ID = /^[0-9a-f]{64}$/;\n/** java-tron's block heights are `long`s. */\nconst INT64_MAX = 2n ** 63n - 1n;\n\n/** A lower-case transaction or block id, or `null` (length checked before any work). */\nfunction idOf(value: string): string | null {\n if (typeof value !== 'string' || value.length !== 64) return null;\n const id = value.toLowerCase();\n return TX_ID.test(id) ? id : null;\n}\n\n/**\n * Token metadata is read under the proof quorum: the core caches a token's decimals,\n * symbol and \"no such token\" for the container's life, so one lagging or buggy endpoint\n * must not decide them. The constant call's quorum key compares the verdict only, since\n * honest nodes never agree on its whole answer; endpoints that disagree throw retryable\n * `PROVIDER_INCONSISTENT`.\n */\nconst METADATA: TronCallTags = { ...READ, quorum: 'proof' };\n\nfunction tokenProblem(reason: string): ValidationError {\n return new ValidationError('ASSET_RESOLUTION', `TRC-20 token unusable: ${reason}`);\n}\n\n/**\n * The `41…` hex contract of a TRC-20 ref. `UNSUPPORTED_CAPABILITY` for TRX or another token\n * standard; `ASSET_RESOLUTION` for a contract that is not a Tron address.\n */\nexport function trc20Contract(ref: AssetRef): string {\n if (ref === 'native' || ref.standard !== 'trc20') {\n throw new UnsupportedCapabilityError(\n 'UNSUPPORTED_CAPABILITY',\n 'Tron supports TRX and TRC-20 tokens only',\n );\n }\n if (!isTronAddress(ref.contract)) throw tokenProblem('not a Tron contract address');\n return toHexAddress(ref.contract);\n}\n\n/**\n * A constant call on a token: a revert, a VM failure or no contract is the\n * token's own permanent problem (`ASSET_RESOLUTION`, cached by the core); node refusals stay\n * retryable and every other error propagates unchanged. \"No contract\" is a node's text, so\n * it counts only once `/wallet/getcontract` confirms it structurally with the same tags; a\n * node that shows a contract there decides nothing.\n */\nexport async function tokenCall(\n ctx: TronContext,\n owner: string,\n contract: string,\n data: string,\n tags: TronCallTags,\n): Promise<string> {\n const answer = await ctx.api.constantCall(owner, contract, data, tags);\n if (answer.kind === 'no-contract') {\n if (await ctx.api.contractExists(contract, tags)) {\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n 'the node both holds and lacks this contract',\n { retryable: true },\n );\n }\n throw tokenProblem('no contract at this address');\n }\n if (answer.kind === 'failed') throw tokenProblem('the call failed');\n return answer.result;\n}\n\n/** A holder's TRC-20 balance. */\nexport async function trc20Balance(\n ctx: TronContext,\n contract: string,\n holder: string,\n tags: TronCallTags = READ,\n): Promise<bigint> {\n const result = await tokenCall(\n ctx,\n toHexAddress(holder),\n contract,\n encodeBalanceOf(holder),\n tags,\n );\n try {\n return decodeUint256(result);\n } catch {\n throw tokenProblem('balanceOf returned no uint256');\n }\n}\n\n/**\n * An included transaction's observation. `guard` applies the verdict guard (on-chain\n * evidence that value moved) to our own Attempts; without it (a status lookup by id,\n * `ordering === undefined`), the chain's own view is reported.\n */\nexport async function observeIncluded(\n ctx: TronContext,\n id: string,\n tags: TronCallTags,\n guard: boolean,\n): Promise<DriverTxObservation | null> {\n const info = await ctx.api.transactionInfo('full', id, tags);\n if (!info) return null;\n const [tx, header] = await Promise.all([\n ctx.api.transaction('full', id, tags),\n ctx.api.block('full', info.blockNumber, tags),\n ]);\n // The node indexed the info but cannot serve the transaction or its block yet: decide\n // nothing now (the core keeps its current observation on a retryable error).\n if (!tx || !header) throw notServable();\n const verdict = guard\n ? verdictOf(ctx.codec, tx, info)\n : chainVerdict(ctx.codec, tx, info);\n return {\n seen: 'block',\n txHash: id,\n blockHeight: info.blockNumber,\n blockHash: header.id,\n success: verdict.success,\n ...(verdict.reason ? { reason: verdict.reason } : {}),\n };\n}\n\nexport function createTronReader(ctx: TronContext): ChainReader {\n const { api } = ctx;\n\n async function getTransaction(id: string): Promise<DriverTransaction | null> {\n const txId = idOf(id);\n if (txId === null) return null;\n const tx = await api.transaction('full', txId, READ);\n if (!tx) {\n const pending: TronTxJson | null = await api.pending(txId, READ);\n return pending\n ? decodeTransaction(ctx.codec, pending, null, undefined, true)\n : null;\n }\n // java-tron serves only included transactions here: without its receipt or its block\n // the answer is \"not yet\", never \"not seen\".\n const info = await api.transactionInfo('full', txId, READ);\n if (!info) throw notServable();\n const header = await api.block('full', info.blockNumber, READ);\n if (!header) throw notServable();\n return decodeTransaction(ctx.codec, tx, info, header.id);\n }\n\n return {\n async getBalance(address, asset) {\n if (asset === 'native')\n return (await api.account(toHexAddress(address), READ)).balance;\n return trc20Balance(ctx, trc20Contract(asset), address);\n },\n async getBlockHeight() {\n return ((await api.block('full', undefined, MONITOR)) as { number: bigint }).number;\n },\n async getFinalizedHeight() {\n return ((await api.block('solid', undefined, MONITOR)) as { number: bigint })\n .number;\n },\n async getBlock(ref): Promise<DriverBlock | null> {\n const key = typeof ref === 'string' ? idOf(ref) : ref;\n if (key === null || (typeof key === 'bigint' && (key < 0n || key > INT64_MAX))) {\n return null;\n }\n const header = await api.block('full', key, READ);\n return header\n ? {\n height: header.number,\n hash: header.id,\n parentHash: header.parentId,\n timestamp: header.timestamp,\n }\n : null;\n },\n getTransaction,\n async observe(ref, ordering) {\n const id = idOf(ref.id);\n if (id === null) return { seen: 'none' };\n const included = await observeIncluded(ctx, id, MONITOR, ordering !== undefined);\n if (included) return included;\n return (await api.pending(id, MONITOR)) ? { seen: 'mempool' } : { seen: 'none' };\n },\n async getTokenMetadata(ref: TokenRef): Promise<AssetMetadata> {\n const contract = trc20Contract(ref);\n // The contract's own account is the caller: it always exists.\n const decimalsWord = await tokenCall(\n ctx,\n contract,\n contract,\n SELECTORS.decimals,\n METADATA,\n );\n const symbolWord = await tokenCall(\n ctx,\n contract,\n contract,\n SELECTORS.symbol,\n METADATA,\n );\n let decimals: bigint;\n let symbol: string;\n try {\n decimals = decodeUint256(decimalsWord);\n symbol = decodeString(symbolWord);\n } catch {\n throw tokenProblem('unreadable decimals or symbol');\n }\n if (decimals > 255n || symbol.length === 0) {\n throw tokenProblem('decimals or symbol out of range');\n }\n return { symbol, decimals: Number(decimals) };\n },\n normalizeTokenRef(ref: TokenRef): TokenRef {\n if (ref.standard !== 'trc20') {\n throw new ValidationError(\n 'ASSET_RESOLUTION',\n 'Tron tokens use the trc20 standard',\n );\n }\n if (!isTronAddress(ref.contract)) throw tokenProblem('not a Tron contract address');\n return { standard: 'trc20', contract: toBase58Address(ref.contract) };\n },\n };\n}\n\n/** `ext.tron`, the Tron family extension. */\nexport function createTronExt(ctx: TronContext): TronExt {\n return {\n tron: {\n getResources: (address: string): Promise<TronResources> =>\n ctx.api.resources(toHexAddress(address), READ),\n },\n };\n}\n"]}
1
+ {"version":3,"file":"reader.js","sourceRoot":"","sources":["../../../src/adapters/tron/reader.ts"],"names":[],"mappings":";;AAkEA,sCASC;AASD,8BAoBC;AAGD,oCAkBC;AAcD,0CAYC;AAOD,0CA2BC;AAED,4CAmGC;AAGD,sCAOC;AA5RD,mDAIiC;AAKjC,+BAAgF;AAChF,uCAAyE;AACzE,qCAAsE;AACtE,iCAAmF;AAcnF,MAAM,KAAK,GAAG,gBAAgB,CAAC;AAC/B,6CAA6C;AAC7C,MAAM,SAAS,GAAG,EAAE,IAAI,GAAG,GAAG,EAAE,CAAC;AAEjC,wFAAwF;AACxF,SAAS,I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AChD,CAAC;QACD,iBAAiB,CAAC,GAAa;YAC7B,IAAI,GAAG,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;gBAC7B,MAAM,IAAI,uBAAe,CACvB,kBAAkB,EAClB,oCAAoC,CACrC,CAAC;YACJ,CAAC;YACD,IAAI,CAAC,IAAA,uBAAa,EAAC,GAAG,CAAC,QAAQ,CAAC;gBAAE,MAAM,YAAY,CAAC,6BAA6B,CAAC,CAAC;YACpF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAA,yBAAe,EAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;QACxE,CAAC;KACF,CAAC;AACJ,CAAC;AAED,6CAA6C;AAC7C,SAAgB,aAAa,CAAC,GAAgB;IAC5C,OAAO;QACL,IAAI,EAAE;YACJ,YAAY,EAAE,CAAC,OAAe,EAA0B,EAAE,CACxD,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,IAAA,sBAAY,EAAC,OAAO,CAAC,EAAE,WAAI,CAAC;SACjD;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The Tron `ChainReader` and `ext.tron`. Tags follow the `ChainDriver` contract table:\n * reads `read`, heights and `observe` `monitor`. Addresses reach the node as `41…` hex.\n * A transaction the node holds but cannot serve whole yet (its receipt, its block) is a\n * retryable `PROVIDER_UNAVAILABLE`, never \"not seen\".\n */\nimport type {\n ChainReader,\n DriverBlock,\n DriverTransaction,\n DriverTxObservation,\n} from '../../core/driver/types';\nimport {\n ProviderError,\n UnsupportedCapabilityError,\n ValidationError,\n} from '../../core/errors/error';\nimport type { Logger } from '../../core/events/logger';\nimport type { AssetMetadata, AssetRef, TokenRef } from '../../core/model/asset';\nimport type { ChainInfo, NetworkInfo } from '../../core/model/chain';\nimport type { Clock } from '../../core/util/clock';\nimport { SELECTORS, decodeString, decodeUint256, encodeBalanceOf } from './abi';\nimport { isTronAddress, toBase58Address, toHexAddress } from './address';\nimport { chainVerdict, decodeTransaction, verdictOf } from './decode';\nimport { MONITOR, READ, notServable, type TronApi, type TronTxJson } from './http';\nimport type { TronNetworkConfig } from './network';\nimport type { TronCallTags, TronCodec, TronExt, TronResources } from './types';\n\nexport interface TronContext {\n readonly api: TronApi;\n readonly codec: TronCodec;\n readonly chain: ChainInfo;\n readonly network: NetworkInfo;\n readonly config: TronNetworkConfig;\n readonly clock: Clock;\n readonly log: Logger;\n}\n\nconst TX_ID = /^[0-9a-f]{64}$/;\n/** java-tron's block heights are `long`s. */\nconst INT64_MAX = 2n ** 63n - 1n;\n\n/** A lower-case transaction or block id, or `null` (length checked before any work). */\nfunction idOf(value: string): string | null {\n if (typeof value !== 'string' || value.length !== 64) return null;\n const id = value.toLowerCase();\n return TX_ID.test(id) ? id : null;\n}\n\n/**\n * Token metadata is read under the proof quorum: the core caches a token's decimals,\n * symbol and \"no such token\" for the container's life, so one lagging or buggy endpoint\n * must not decide them. The constant call's quorum key compares the verdict only, since\n * honest nodes never agree on its whole answer; endpoints that disagree throw retryable\n * `PROVIDER_INCONSISTENT`.\n */\nconst METADATA: TronCallTags = { ...READ, quorum: 'proof' };\n\nfunction tokenProblem(reason: string): ValidationError {\n return new ValidationError('ASSET_RESOLUTION', `TRC-20 token unusable: ${reason}`);\n}\n\n/**\n * The `41…` hex contract of a TRC-20 ref. `UNSUPPORTED_CAPABILITY` for TRX or another token\n * standard; `ASSET_RESOLUTION` for a contract that is not a Tron address.\n */\nexport function trc20Contract(ref: AssetRef): string {\n if (ref === 'native' || ref.standard !== 'trc20') {\n throw new UnsupportedCapabilityError(\n 'UNSUPPORTED_CAPABILITY',\n 'Tron supports TRX and TRC-20 tokens only',\n );\n }\n if (!isTronAddress(ref.contract)) throw tokenProblem('not a Tron contract address');\n return toHexAddress(ref.contract);\n}\n\n/**\n * A constant call on a token: a revert, a VM failure or no contract is the\n * token's own permanent problem (`ASSET_RESOLUTION`, cached by the core); node refusals stay\n * retryable and every other error propagates unchanged. \"No contract\" is a node's text, so\n * it counts only once `/wallet/getcontract` confirms it structurally with the same tags; a\n * node that shows a contract there decides nothing.\n */\nexport async function tokenCall(\n ctx: TronContext,\n owner: string,\n contract: string,\n data: string,\n tags: TronCallTags,\n): Promise<string> {\n const answer = await ctx.api.constantCall(owner, contract, data, tags);\n if (answer.kind === 'no-contract') {\n if (await ctx.api.contractExists(contract, tags)) {\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n 'the node both holds and lacks this contract',\n { retryable: true },\n );\n }\n throw tokenProblem('no contract at this address');\n }\n if (answer.kind === 'failed') throw tokenProblem('the call failed');\n return answer.result;\n}\n\n/** A holder's TRC-20 balance. */\nexport async function trc20Balance(\n ctx: TronContext,\n contract: string,\n holder: string,\n tags: TronCallTags = READ,\n): Promise<bigint> {\n const result = await tokenCall(\n ctx,\n toHexAddress(holder),\n contract,\n encodeBalanceOf(holder),\n tags,\n );\n try {\n return decodeUint256(result);\n } catch {\n throw tokenProblem('balanceOf returned no uint256');\n }\n}\n\n/** An ABI `bool` that is `true`: one word, exactly 1 (constant results are lower-case). */\nconst TRUE_WORD = /^0{63}1$/;\n\n/**\n * Whether a token answers `deprecated()` with `true`, as Tether's `TetherToken` (USDT on\n * Tron) does once its owner deprecates it for an upgraded contract (`upgradedAddress`).\n * Only a definitive answer decides: a contract without the method (a revert or VM failure,\n * an answer that is not one ABI `bool`, or a node's \"no contract\", which the balance read\n * beside it settles) is not deprecated. A node refusal or a malformed answer throws\n * retryable, so a failed read is never taken for either answer. The contract's own\n * account is the caller: it always exists.\n */\nexport async function trc20Deprecated(\n ctx: TronContext,\n contract: string,\n tags: TronCallTags,\n): Promise<boolean> {\n const answer = await ctx.api.constantCall(\n contract,\n contract,\n SELECTORS.deprecated,\n tags,\n );\n return answer.kind === 'ok' && TRUE_WORD.test(answer.result);\n}\n\n/**\n * An included transaction's observation. `guard` applies the verdict guard (on-chain\n * evidence that value moved) to our own Attempts; without it (a status lookup by id,\n * `ordering === undefined`), the chain's own view is reported.\n */\nexport async function observeIncluded(\n ctx: TronContext,\n id: string,\n tags: TronCallTags,\n guard: boolean,\n): Promise<DriverTxObservation | null> {\n const info = await ctx.api.transactionInfo('full', id, tags);\n if (!info) return null;\n const [tx, header] = await Promise.all([\n ctx.api.transaction('full', id, tags),\n ctx.api.block('full', info.blockNumber, tags),\n ]);\n // The node indexed the info but cannot serve the transaction or its block yet: decide\n // nothing now (the core keeps its current observation on a retryable error).\n if (!tx || !header) throw notServable();\n const verdict = guard\n ? verdictOf(ctx.codec, tx, info)\n : chainVerdict(ctx.codec, tx, info);\n return {\n seen: 'block',\n txHash: id,\n blockHeight: info.blockNumber,\n blockHash: header.id,\n success: verdict.success,\n ...(verdict.reason ? { reason: verdict.reason } : {}),\n ...(verdict.failure ? { failure: verdict.failure } : {}),\n };\n}\n\nexport function createTronReader(ctx: TronContext): ChainReader {\n const { api } = ctx;\n\n async function getTransaction(id: string): Promise<DriverTransaction | null> {\n const txId = idOf(id);\n if (txId === null) return null;\n const tx = await api.transaction('full', txId, READ);\n if (!tx) {\n const pending: TronTxJson | null = await api.pending(txId, READ);\n return pending\n ? decodeTransaction(ctx.codec, pending, null, undefined, true)\n : null;\n }\n // java-tron serves only included transactions here: without its receipt or its block\n // the answer is \"not yet\", never \"not seen\".\n const info = await api.transactionInfo('full', txId, READ);\n if (!info) throw notServable();\n const header = await api.block('full', info.blockNumber, READ);\n if (!header) throw notServable();\n return decodeTransaction(ctx.codec, tx, info, header.id);\n }\n\n return {\n async getBalance(address, asset) {\n if (asset === 'native')\n return (await api.account(toHexAddress(address), READ)).balance;\n return trc20Balance(ctx, trc20Contract(asset), address);\n },\n async getBlockHeight() {\n return ((await api.block('full', undefined, MONITOR)) as { number: bigint }).number;\n },\n async getFinalizedHeight() {\n return ((await api.block('solid', undefined, MONITOR)) as { number: bigint })\n .number;\n },\n async getBlock(ref): Promise<DriverBlock | null> {\n const key = typeof ref === 'string' ? idOf(ref) : ref;\n if (key === null || (typeof key === 'bigint' && (key < 0n || key > INT64_MAX))) {\n return null;\n }\n const header = await api.block('full', key, READ);\n return header\n ? {\n height: header.number,\n hash: header.id,\n parentHash: header.parentId,\n timestamp: header.timestamp,\n }\n : null;\n },\n getTransaction,\n async observe(ref, ordering) {\n const id = idOf(ref.id);\n if (id === null) return { seen: 'none' };\n const included = await observeIncluded(ctx, id, MONITOR, ordering !== undefined);\n if (included) return included;\n return (await api.pending(id, MONITOR)) ? { seen: 'mempool' } : { seen: 'none' };\n },\n async getTokenMetadata(ref: TokenRef): Promise<AssetMetadata> {\n const contract = trc20Contract(ref);\n // The contract's own account is the caller: it always exists.\n const decimalsWord = await tokenCall(\n ctx,\n contract,\n contract,\n SELECTORS.decimals,\n METADATA,\n );\n const symbolWord = await tokenCall(\n ctx,\n contract,\n contract,\n SELECTORS.symbol,\n METADATA,\n );\n let decimals: bigint;\n let symbol: string;\n try {\n decimals = decodeUint256(decimalsWord);\n symbol = decodeString(symbolWord);\n } catch {\n throw tokenProblem('unreadable decimals or symbol');\n }\n if (decimals > 255n || symbol.length === 0) {\n throw tokenProblem('decimals or symbol out of range');\n }\n return { symbol, decimals: Number(decimals) };\n },\n normalizeTokenRef(ref: TokenRef): TokenRef {\n if (ref.standard !== 'trc20') {\n throw new ValidationError(\n 'ASSET_RESOLUTION',\n 'Tron tokens use the trc20 standard',\n );\n }\n if (!isTronAddress(ref.contract)) throw tokenProblem('not a Tron contract address');\n return { standard: 'trc20', contract: toBase58Address(ref.contract) };\n },\n };\n}\n\n/** `ext.tron`, the Tron family extension. */\nexport function createTronExt(ctx: TronContext): TronExt {\n return {\n tron: {\n getResources: (address: string): Promise<TronResources> =>\n ctx.api.resources(toHexAddress(address), READ),\n },\n };\n}\n"]}
@@ -2,6 +2,8 @@
2
2
  * Well-known tokens: USDT, which Tether deploys natively on Tron mainnet
3
3
  * (Tether's supported-protocols page); decimals and symbol read from the contract. Circle
4
4
  * lists no Tron USDC, so there is none. The contract is the base58 form, the canonical one.
5
+ * USDT is Tether's `TetherToken`, which can deprecate itself for an upgraded contract; the
6
+ * builder then refuses its transfers (`ASSET_RESOLUTION`) until the alias moves.
5
7
  */
6
8
  import type { AssetRegistration } from '../../core/registry/assets';
7
9
  export declare const TRON_TOKENS: readonly AssetRegistration[];
@@ -1 +1 @@
1
- {"version":3,"file":"tokens.js","sourceRoot":"","sources":["../../../src/adapters/tron/tokens.ts"],"names":[],"mappings":";;;AAMA,mDAAoD;AAEvC,QAAA,WAAW,GAAiC,IAAA,mBAAU,EAAC;IAClE;QACE,KAAK,EAAE,MAAM;QACb,OAAO,EAAE,SAAS;QAClB,GAAG,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,oCAAoC,EAAE;QAC1E,QAAQ,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,EAAE;QACzC,OAAO,EAAE,CAAC,MAAM,CAAC;KAClB;CACF,CAAC,CAAC","sourcesContent":["/**\n * Well-known tokens: USDT, which Tether deploys natively on Tron mainnet\n * (Tether's supported-protocols page); decimals and symbol read from the contract. Circle\n * lists no Tron USDC, so there is none. The contract is the base58 form, the canonical one.\n */\nimport type { AssetRegistration } from '../../core/registry/assets';\nimport { deepFreeze } from '../../core/util/freeze';\n\nexport const TRON_TOKENS: readonly AssetRegistration[] = deepFreeze([\n {\n chain: 'tron',\n network: 'mainnet',\n ref: { standard: 'trc20', contract: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t' },\n metadata: { symbol: 'USDT', decimals: 6 },\n aliases: ['USDT'],\n },\n]);\n"]}
1
+ {"version":3,"file":"tokens.js","sourceRoot":"","sources":["../../../src/adapters/tron/tokens.ts"],"names":[],"mappings":";;;AAQA,mDAAoD;AAEvC,QAAA,WAAW,GAAiC,IAAA,mBAAU,EAAC;IAClE;QACE,KAAK,EAAE,MAAM;QACb,OAAO,EAAE,SAAS;QAClB,GAAG,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,oCAAoC,EAAE;QAC1E,QAAQ,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,EAAE;QACzC,OAAO,EAAE,CAAC,MAAM,CAAC;KAClB;CACF,CAAC,CAAC","sourcesContent":["/**\n * Well-known tokens: USDT, which Tether deploys natively on Tron mainnet\n * (Tether's supported-protocols page); decimals and symbol read from the contract. Circle\n * lists no Tron USDC, so there is none. The contract is the base58 form, the canonical one.\n * USDT is Tether's `TetherToken`, which can deprecate itself for an upgraded contract; the\n * builder then refuses its transfers (`ASSET_RESOLUTION`) until the alias moves.\n */\nimport type { AssetRegistration } from '../../core/registry/assets';\nimport { deepFreeze } from '../../core/util/freeze';\n\nexport const TRON_TOKENS: readonly AssetRegistration[] = deepFreeze([\n {\n chain: 'tron',\n network: 'mainnet',\n ref: { standard: 'trc20', contract: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t' },\n metadata: { symbol: 'USDT', decimals: 6 },\n aliases: ['USDT'],\n },\n]);\n"]}
@@ -129,7 +129,7 @@ async function unsignedFor(scope, build, sender, selection, outputs, changeScrip
129
129
  const built = builtFor(scope, wallet, inputs, all);
130
130
  const signingRequests = built.digests.map((digest, index) => ({
131
131
  id: `in:${index}`,
132
- scheme: wallet.type === 'p2tr' ? 'secp256k1-schnorr' : 'secp256k1-ecdsa',
132
+ scheme: (0, context_1.signingScheme)(wallet.type),
133
133
  payload: digest,
134
134
  payloadKind: 'digest',
135
135
  publicKey: wallet.type === 'p2tr' ? wallet.outputKey : wallet.publicKey,
@@ -1 +1 @@
1
- {"version":3,"file":"builder.js","sourceRoot":"","sources":["../../../src/adapters/utxo/builder.ts"],"names":[],"mappings":";;;AAmVA,kCAwIC;AAqBD,0CAwDC;AAQD,0CAiGC;AApnBD,mDAOiC;AACjC,kDAAiD;AAKjD,uCAAmF;AACnF,mCAaiB;AACjB,6CAOsB;AACtB,uCAA+E;AAC/E,qCAAgE;AAChE,qCAA2C;AAC3C,mCAAkD;AAClD,iCAAgE;AAEhE,mCASiB;AAGjB,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IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,EAC/D,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,EAC/B,GAAG,CAAC,MAAM,EACV,IAAI,EACJ,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,EAC3C;gBACE,KAAK,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK;gBAC7B,OAAO,EAAE,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC;aAC3D,EACD,EAAE,IAAI,EAAE,IAAI,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,cAAc,EAAE,KAAK,EAAE,CAC7E,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The UTXO builder, broadcaster and RBF replacement policy.\n *\n * - `build` spends only outputs not held by another live Operation (`ctx.excludeInputs`),\n * pays change to the wallet's change address, and records the spent outpoints as the\n * `inputs` ordering. The fee is `exact` once built; the absurd-fee guard runs first.\n * - Every input a build, a replacement or a cancel spends is authenticated against its\n * previous transaction first: the indexer's value and script count only when the\n * bytes that hash to the outpoint's txid say the same. A lied value could burn the\n * difference as fee, or make our own signed bytes invalid for good and stall the\n * Operation with its inputs held.\n * - Replacements and cancels keep EVERY input of the Attempt they replace (and may add\n * confirmed ones), so each new Attempt conflicts with every earlier one (exclusion is\n * not transitive). Neither ever raises a fee on its own: a fee below the\n * replacement floor is `FEE_TOO_LOW`.\n * - A cancel pays everything back to the sending address itself.\n * - Broadcast answers are classified by `errors.ts`; an ambiguous transport failure is\n * rethrown unclassified. A node's rejection is a claim: it stands only when its reason\n * holds for the bytes that were sent, checked here; else `refused`. A terminal\n * `rejected` frees the inputs, so a lying endpoint that relayed our valid bytes would\n * let the caller's retry spend other coins, and both transactions could confirm.\n */\nimport type {\n BroadcastResult,\n Broadcaster,\n BuildContext,\n ReplacementPolicy,\n TxBuilder,\n} from '../../core/driver/types';\nimport {\n ChainError,\n ProviderError,\n SigningError,\n UnsupportedCapabilityError,\n ValidationError,\n isCryptoAioError,\n} from '../../core/errors/error';\nimport { assetId } from '../../core/model/asset';\nimport type { FeeEstimateDraft, FeeOverride, FeeSpeed } from '../../core/model/fee';\nimport type { DriverIntent, IntentSummary } from '../../core/model/intent';\nimport type { RawTx, SignedTx, UnsignedTx } from '../../core/model/transaction';\nimport type { SignatureBundle, SigningRequest } from '../../core/signing/types';\nimport { dustThreshold, type DecodedAddress, type WalletAddress } from './address';\nimport {\n assembleTx,\n assertPrevious,\n buildTx,\n isPreviousTxRefusal,\n previousTxOf,\n signaturesFromPsbt,\n viewPsbt,\n SEQUENCE_FINAL_LOCKTIME,\n SEQUENCE_RBF,\n type BuiltTx,\n type PlannedInput,\n type PreviousTx,\n} from './codec';\nimport {\n selectCoins,\n txWeight,\n vsizeOf,\n type PlannedOutput,\n type Selection,\n type Spendable,\n} from './coinselect';\nimport { READ, forEachBounded, withSignal, type UtxoContext } from './context';\nimport { classifyOwnBroadcast, parseNodeError } from './errors';\nimport { assertConfirmed } from './proofs';\nimport { MAX_TX_BYTES, readTxHex } from './rawtx';\nimport { assertSaneFee, feeAt, replacementFloor } from './fees';\nimport type { Network } from './sdk';\nimport {\n assertNative,\n changeAddressOf,\n plannedOutputs,\n rateOf,\n senderOf,\n spendable,\n walletOf,\n type Sender,\n} from './spend';\nimport type { UtxoFeeDetails } from './types';\n\nconst speedOf = (fee: FeeSpeed | FeeOverride): FeeSpeed | 'custom' =>\n typeof fee === 'string' ? fee : 'custom';\n\nconst paidOf = (fee: FeeEstimateDraft): bigint =>\n fee.charges.reduce((sum, charge) => sum + charge.amount, 0n);\n\nfunction draft(\n from: string,\n speed: FeeSpeed | 'custom',\n fee: bigint,\n details: UtxoFeeDetails,\n bound: 'exact' | 'expected',\n): FeeEstimateDraft {\n return {\n kind: 'utxo',\n speed,\n charges: [{ asset: 'native', amount: fee, label: 'network' }],\n bound,\n payer: from,\n details: { ...details },\n };\n}\n\n/** `UtxoFeeDetails` of a stored fee, checked (it is our own plain data). */\nfunction detailsOf(fee: FeeEstimateDraft): UtxoFeeDetails {\n const d = fee.details as Partial<UtxoFeeDetails>;\n if (\n fee.kind !== 'utxo' ||\n typeof d.satPerKvB !== 'bigint' ||\n !Number.isSafeInteger(d.vsize) ||\n (d.vsize as number) < 1 ||\n typeof d.change !== 'bigint' ||\n !Number.isSafeInteger(d.changeIndex)\n ) {\n throw new ValidationError('INVALID_INTENT', 'the fee is not a UTXO fee estimate');\n }\n return d as UtxoFeeDetails;\n}\n\n/** Everything that builds a transaction; shared by the builder and the replacement policy. */\ninterface Scope {\n readonly ctx: UtxoContext;\n readonly network: Network;\n readonly sequence: number;\n}\n\nconst scopeOf = (ctx: UtxoContext, network: Network): Scope => ({\n ctx,\n network,\n sequence: ctx.config.rbf ? SEQUENCE_RBF : SEQUENCE_FINAL_LOCKTIME,\n});\n\nconst changeOf = (scope: Scope, build: BuildContext, sender: Sender): DecodedAddress =>\n changeAddressOf(scope.ctx, build.wallet, sender, build.keys);\n\n/**\n * The message is a fixed text, so no amount reaches a log line; the amounts go only in\n * the details, as decimal strings, as in every family.\n */\nconst insufficient = (\n what: 'this transfer' | 'the replacement' | 'a cancel',\n required: bigint,\n available: bigint,\n): ChainError =>\n new ChainError('INSUFFICIENT_FUNDS', `insufficient funds for ${what}`, {\n details: { required: required.toString(), available: available.toString() },\n });\n\n/** At most this many previous transactions are read at once for one build. */\nexport const PREVIOUS_TX_READS = 4;\n\n/**\n * A refusal of a previous transaction put on the provider: the inputs' outpoints and values\n * are the indexer's, and their previous transactions are bound to their txids, so authentic\n * bytes that disagree with the indexer's output decide nothing (retryable), never a user\n * error.\n */\nfunction onProvider<T>(work: () => T): T {\n try {\n return work();\n } catch (error) {\n if (!isPreviousTxRefusal(error)) throw error;\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n \"the indexer's unspent output disagrees with its previous transaction\",\n { retryable: true, cause: error },\n );\n }\n}\n\n/** The previous transaction of each txid, read at most `PREVIOUS_TX_READS` at a time. */\nasync function previousTxs(\n scope: Scope,\n txids: readonly string[],\n signal?: AbortSignal,\n): Promise<ReadonlyMap<string, PreviousTx>> {\n const found = new Map<string, PreviousTx>();\n await forEachBounded(txids, PREVIOUS_TX_READS, async (txid) => {\n const prev = await scope.ctx.esplora.previousTx(txid, withSignal(READ, signal));\n if (prev === null) {\n throw new ProviderError(\n 'PROVIDER_UNAVAILABLE',\n 'the previous transaction of an input is not available',\n );\n }\n found.set(txid, prev);\n });\n return found;\n}\n\n/** Which inputs of a build are new, and how their parents must be confirmed. */\ninterface NewInputs {\n /** The outpoints a replacement or cancel keeps: attested when their Attempt was built. */\n readonly kept: ReadonlySet<string>;\n /**\n * `minInputConfirmations: 0` on a transfer: an output of the wallet's own sent transaction\n * (its bytes known to this client) may be spent before a block holds it.\n */\n readonly ownUnconfirmed: boolean;\n}\n\n/**\n * Every input's value and script, authenticated against its previous transaction\n * (all wallet types, whatever `nonWitnessUtxo` says), so the node never judges bytes built\n * on an indexer's wrong value, and an outpoint its transaction does not have (a phantom\n * that nothing would ever spend, so never proven dead) is never built on. Either would\n * stall the Operation for good with its inputs held, since signed bytes cannot be\n * abandoned. A new input's previous transaction must also be in a block the proof quorum\n * attests, unless it is the wallet's own sent transaction and `minInputConfirmations` is\n * 0: a made-up parent would freeze the transfer the same way. p2pkh inputs carry it, and\n * segwit v0 ones while `nonWitnessUtxo` is on; taproot never does: BIP341 commits to\n * every amount, and `signed-psbt.ts` refuses one on a taproot input.\n */\nasync function authenticated(\n scope: Scope,\n wallet: WalletAddress,\n inputs: readonly Spendable[],\n fresh: NewInputs,\n signal?: AbortSignal,\n): Promise<PlannedInput[]> {\n const { esplora, config } = scope.ctx;\n // First, each new input's parent must be in a block the proof quorum attests,\n // at its own height; only then are its bytes read. Self-authenticating bytes prove what a\n // transaction is, never that a chain holds it.\n const parents = inputs\n .filter((input) => !fresh.kept.has(input.outpoint))\n .map((input) => input.txid)\n .filter((txid) => !(fresh.ownUnconfirmed && esplora.isOwn(txid)));\n await assertConfirmed(scope.ctx, parents, config.minInputConfirmations, signal);\n const embed =\n wallet.type === 'p2pkh' ||\n (wallet.type !== 'p2tr' && scope.ctx.config.nonWitnessUtxo);\n const txs = await previousTxs(scope, [...new Set(inputs.map((i) => i.txid))], signal);\n return inputs.map((input) => {\n const prevTx = txs.get(input.txid) as PreviousTx;\n onProvider(() => assertPrevious(prevTx, input, wallet.script));\n return embed ? { ...input, prevTx } : { ...input };\n });\n}\n\n/** `buildTx`, with its refusal of a previous transaction put on the provider. */\nfunction builtFor(\n scope: Scope,\n wallet: WalletAddress,\n inputs: readonly PlannedInput[],\n outputs: readonly PlannedOutput[],\n): BuiltTx {\n return onProvider(() =>\n buildTx(scope.network, wallet, inputs, outputs, scope.sequence),\n );\n}\n\n/** The unsigned transaction for a selection: PSBT, one request per input, exact fee, ordering. */\nasync function unsignedFor(\n scope: Scope,\n build: BuildContext,\n sender: Sender,\n selection: Selection,\n outputs: readonly PlannedOutput[],\n changeScript: Uint8Array,\n rate: bigint,\n speed: FeeSpeed | 'custom',\n summary: IntentSummary,\n fresh: NewInputs,\n): Promise<UnsignedTx> {\n const { wallet, key } = walletOf(scope.ctx, sender, build.keys);\n assertSaneFee(selection.fee, selection.vsize, scope.ctx.config);\n const all: PlannedOutput[] =\n selection.change > 0n\n ? [...outputs, { script: changeScript, value: selection.change }]\n : [...outputs];\n const inputs = await authenticated(\n scope,\n wallet,\n selection.inputs,\n fresh,\n build.signal,\n );\n const built = builtFor(scope, wallet, inputs, all);\n const signingRequests: SigningRequest[] = built.digests.map((digest, index) => ({\n id: `in:${index}`,\n scheme: wallet.type === 'p2tr' ? 'secp256k1-schnorr' : 'secp256k1-ecdsa',\n payload: digest,\n payloadKind: 'digest',\n publicKey:\n wallet.type === 'p2tr' ? (wallet.outputKey as Uint8Array) : wallet.publicKey,\n ...(key.keyRef ? { keyRef: key.keyRef } : {}),\n ...(wallet.tweak ? { params: { tweak: wallet.tweak } } : {}),\n }));\n return {\n payload: { encoding: 'base64', data: built.psbt },\n ...(built.txid !== undefined\n ? { expectedRef: { id: built.txid, idKind: 'txid', canonical: true } }\n : {}),\n signingRequests,\n ordering: { kind: 'inputs', inputs: selection.inputs.map((i) => i.outpoint).sort() },\n fee: draft(\n sender.from.canonical,\n speed,\n selection.fee,\n {\n satPerKvB: rate,\n vsize: selection.vsize,\n inputs: selection.inputs.length,\n outputs: all.length,\n change: selection.change,\n changeIndex: selection.change > 0n ? outputs.length : -1,\n },\n 'exact',\n ),\n summary,\n };\n}\n\n/** The replaced Attempt: its inputs (values from its PSBT), payments (no change) and fee. */\nfunction previousOf(scope: Scope, previous: UnsignedTx, sender: Sender) {\n const details = detailsOf(previous.fee);\n const view = viewPsbt(previous.payload.data, scope.network);\n const inputs: Spendable[] = view.inputs.map((i) => ({\n outpoint: i.outpoint,\n txid: i.txid,\n vout: i.vout,\n value: i.value,\n }));\n const outputs = view.outputs.filter((_, index) => index !== details.changeIndex);\n // A real signature may be a byte shorter than the worst case the estimate counts: a\n // full vbyte per legacy input, a quarter per witness input.\n const slack = sender.type === 'p2pkh' ? inputs.length : Math.ceil(inputs.length / 4);\n const minVsize = Math.max(1, details.vsize - slack);\n return { vsize: details.vsize, minVsize, inputs, outputs, paid: paidOf(previous.fee) };\n}\n\nexport interface UtxoBuilder extends TxBuilder {\n signaturesFrom(unsigned: UnsignedTx, signed: RawTx): readonly SignatureBundle[];\n}\n\nexport function utxoBuilder(ctx: UtxoContext, network: Network): UtxoBuilder {\n const scope = scopeOf(ctx, network);\n const { config } = ctx;\n const native = assetId(ctx.chain.id, ctx.network.id, 'native');\n\n const plan = async (intent: DriverIntent, rate: bigint, build: BuildContext) => {\n assertNative(intent.asset);\n // Defence in depth behind the network's capability check: nothing here writes a memo,\n // and the core would otherwise accept one this builder drops.\n if (intent.memo !== undefined) {\n throw new UnsupportedCapabilityError(\n 'UNSUPPORTED_CAPABILITY',\n 'Bitcoin transfers carry no memo (OP_RETURN is not supported)',\n );\n }\n const sender = senderOf(ctx, intent.from);\n const outputs = plannedOutputs(ctx, intent.outputs);\n const changeScript = changeOf(scope, build, sender).script;\n const candidates = await spendable(\n ctx,\n sender.from.canonical,\n build.excludeInputs,\n config.minInputConfirmations,\n build.signal,\n );\n const selection = selectCoins({\n candidates,\n outputs,\n changeScript,\n inputType: sender.type,\n rate,\n dustRelayFee: config.dustRelayFee,\n strategy: config.coinSelection,\n });\n return { sender, outputs, changeScript, selection };\n };\n\n return {\n async estimateFee(intent, build) {\n const rate = await rateOf(ctx, intent.fee, build.signal);\n const { sender, selection } = await plan(intent, rate, build);\n const change = selection.ok ? selection.change : 0n;\n return draft(\n sender.from.canonical,\n speedOf(intent.fee),\n selection.fee,\n {\n satPerKvB: rate,\n vsize: selection.vsize,\n inputs: selection.ok ? selection.inputs.length : 0,\n outputs: intent.outputs.length + (change > 0n ? 1 : 0),\n change,\n changeIndex: change > 0n ? intent.outputs.length : -1,\n },\n 'expected',\n );\n },\n\n async checkFunds(intent, fee, build) {\n assertNative(intent.asset);\n const candidates = await spendable(\n ctx,\n senderOf(ctx, intent.from).from.canonical,\n build.excludeInputs,\n config.minInputConfirmations,\n build.signal,\n );\n const available = candidates.reduce((sum, c) => sum + c.value, 0n);\n const required =\n intent.outputs.reduce((sum, o) => sum + o.amount, 0n) + paidOf(fee);\n return available >= required\n ? { ok: true }\n : { ok: false, asset: 'native', required, available };\n },\n\n async build(intent, fee, build) {\n const rate = detailsOf(fee).satPerKvB;\n const { sender, outputs, changeScript, selection } = await plan(\n intent,\n rate,\n build,\n );\n if (!selection.ok) {\n throw insufficient('this transfer', selection.required, selection.available);\n }\n return unsignedFor(\n scope,\n build,\n sender,\n selection,\n outputs,\n changeScript,\n rate,\n fee.speed,\n {\n asset: native,\n outputs: intent.outputs.map((o) => ({ to: o.to, amount: o.amount.toString() })),\n },\n { kept: new Set(), ownUnconfirmed: config.minInputConfirmations === 0 },\n );\n },\n\n async assemble(unsigned, signatures) {\n const { hex, txid } = assembleTx(\n unsigned.payload.data,\n network,\n unsigned.signingRequests,\n signatures,\n );\n if (unsigned.expectedRef && unsigned.expectedRef.id !== txid) {\n throw new SigningError(\n 'SIGNING_FAILED',\n 'the signed transaction id differs from the prepared one',\n );\n }\n return {\n raw: { encoding: 'hex', data: hex },\n ref: { id: txid, idKind: 'txid', canonical: true },\n };\n },\n\n signaturesFrom(unsigned, signed) {\n if (signed.encoding !== 'base64') {\n throw new ValidationError(\n 'INVALID_INTENT',\n 'a signed PSBT is expected, as base64',\n );\n }\n return signaturesFromPsbt(\n unsigned.payload.data,\n signed.data,\n network,\n unsigned.signingRequests,\n );\n },\n };\n}\n\n/**\n * Twice Bitcoin Core's `MAX_BLOCK_SERIALIZED_SIZE`: no transaction's hex is longer, so\n * the untrusted text is capped before any decoding. A flat character class, never a\n * repeated group: V8's regexp stack overflows on a repeated group of a few million\n * matches, which a valid transaction can have.\n */\nconst MAX_TX_HEX = 8_000_000;\nconst HEX = /^[0-9a-fA-F]+$/;\n\n/**\n * An Attempt's bytes a node took (accepted, or already holds) are this wallet's\n * own sent transaction: its client keeps them. A bare broadcast (no ref) is not an Attempt.\n */\nfunction rememberOwn(ctx: UtxoContext, signed: SignedTx, hex: string): void {\n if (signed.ref.id === '') return;\n const tx = previousTxOf(hex);\n if (tx?.txid === signed.ref.id) ctx.esplora.rememberOwn(tx);\n}\n\nexport function utxoBroadcaster(ctx: UtxoContext): Broadcaster {\n return {\n async broadcast(signed: SignedTx, options = {}): Promise<BroadcastResult> {\n const { encoding, data } = signed.raw;\n if (\n encoding !== 'hex' ||\n data.length > MAX_TX_HEX ||\n data.length % 2 !== 0 ||\n !HEX.test(data)\n ) {\n throw new ValidationError('INVALID_INTENT', 'a raw Bitcoin transaction is hex');\n }\n const hex = data.toLowerCase();\n try {\n const txid = await ctx.esplora.broadcast(hex, {\n purpose: 'broadcast',\n retry: 'ambiguous-on-failure',\n ...(options.fanout !== undefined ? { fanout: options.fanout } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n // A bare broadcast (no ref) is checked against the bytes' own txid.\n const expected =\n signed.ref.id !== ''\n ? signed.ref.id\n : readTxHex(hex, { maxStripped: MAX_TX_BYTES })?.txid;\n if (txid !== expected) {\n // The node accepted something under another id: the outcome is unknown.\n throw new ProviderError(\n 'PROVIDER_UNAVAILABLE',\n 'the node answered another txid',\n {\n ambiguous: true,\n },\n );\n }\n rememberOwn(ctx, signed, hex);\n return { kind: 'accepted' };\n } catch (error) {\n // A definitive 400 is bitcoind's answer; anything else is rethrown. A rejection\n // stands only when its reason holds for these bytes, checked here.\n if (\n isCryptoAioError(error, 'RPC_ERROR') &&\n !error.ambiguous &&\n error.details?.status === 400\n ) {\n const result = classifyOwnBroadcast(\n parseNodeError(String(error.details.body ?? '')),\n hex,\n );\n if (result.kind === 'already-known') rememberOwn(ctx, signed, hex);\n return result;\n }\n throw error;\n }\n },\n };\n}\n\nconst tooLow = (): ChainError =>\n new ChainError(\n 'FEE_TOO_LOW',\n 'a replacement must pay the replaced fee plus the incremental relay fee, at a higher rate',\n );\n\nexport function utxoReplacement(ctx: UtxoContext, network: Network): ReplacementPolicy {\n const scope = scopeOf(ctx, network);\n const { config } = ctx;\n return {\n replace: true,\n cancel: true,\n\n async buildReplacement(previous, fee, build) {\n const sender = senderOf(ctx, build.from);\n const prev = previousOf(scope, previous, sender);\n const rate = await rateOf(ctx, fee, build.signal);\n const changeScript = changeOf(scope, build, sender).script;\n // BIP125 rule 2: an input it adds must be confirmed; it never takes a held one.\n const candidates = await spendable(\n ctx,\n sender.from.canonical,\n [...(build.excludeInputs ?? []), ...prev.inputs.map((i) => i.outpoint)],\n Math.max(1, config.minInputConfirmations),\n build.signal,\n );\n const selection = selectCoins({\n candidates,\n required: prev.inputs,\n outputs: prev.outputs,\n changeScript,\n inputType: sender.type,\n rate,\n dustRelayFee: config.dustRelayFee,\n strategy: 'accumulative',\n });\n if (!selection.ok) {\n throw insufficient('the replacement', selection.required, selection.available);\n }\n const floor = replacementFloor(\n { fee: prev.paid, vsize: prev.vsize, minVsize: prev.minVsize },\n selection.vsize,\n config.incrementalRelayFee,\n );\n if (selection.fee < floor) throw tooLow();\n return unsignedFor(\n scope,\n build,\n sender,\n selection,\n prev.outputs,\n changeScript,\n rate,\n speedOf(fee),\n previous.summary,\n { kept: new Set(prev.inputs.map((i) => i.outpoint)), ownUnconfirmed: false },\n );\n },\n\n async buildCancel(previous, build, fee) {\n const sender = senderOf(ctx, build.from);\n const prev = previousOf(scope, previous, sender);\n // A cancel pays everything back to the sending address itself, never to a\n // configured change address (under `allowExternalChangeAddress` an external one). A\n // misconfigured change address is still refused here, as on every path.\n changeOf(scope, build, sender);\n const own = sender.from;\n const total = prev.inputs.reduce((sum, i) => sum + i.value, 0n);\n const vsize = vsizeOf(\n txWeight(sender.type, prev.inputs.length, [own.script.length]),\n );\n const floor = replacementFloor(\n { fee: prev.paid, vsize: prev.vsize, minVsize: prev.minVsize },\n vsize,\n config.incrementalRelayFee,\n );\n let paid = floor;\n let rate = (floor * 1_000n + BigInt(vsize) - 1n) / BigInt(vsize);\n if (fee !== undefined) {\n rate = await rateOf(ctx, fee, build.signal);\n paid = feeAt(rate, vsize);\n if (paid < floor) throw tooLow();\n }\n const dust = dustThreshold(own.script, config.dustRelayFee);\n if (total - paid < dust) throw insufficient('a cancel', paid + dust, total);\n const value = total - paid;\n return unsignedFor(\n scope,\n build,\n sender,\n { ok: true, inputs: prev.inputs, change: 0n, fee: paid, vsize },\n [{ script: own.script, value }],\n own.script,\n rate,\n fee === undefined ? 'custom' : speedOf(fee),\n {\n asset: previous.summary.asset,\n outputs: [{ to: own.canonical, amount: value.toString() }],\n },\n { kept: new Set(prev.inputs.map((i) => i.outpoint)), ownUnconfirmed: false },\n );\n },\n };\n}\n"]}
1
+ {"version":3,"file":"builder.js","sourceRoot":"","sources":["../../../src/adapters/utxo/builder.ts"],"names":[],"mappings":";;;AAyVA,kCAwIC;AAqBD,0CAwDC;AAQD,0CAiGC;AA1nBD,mDAOiC;AACjC,kDAAiD;AAKjD,uCAAmF;AACnF,mCAaiB;AACjB,6CAOsB;AACtB,uCAMmB;AACnB,qCAAgE;AAChE,qCAA2C;AAC3C,mCAAkD;AAClD,iCAAgE;AAEhE,mCASiB;AAGjB,MAAM,OAAO,GAAG,CAAC,GAA2B,EAAuB,EAAE,CACnE,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC;AAE3C,MAAM,MAAM,GAAG,CAAC,GAAqB,EAAU,EAAE,CAC/C,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AAE/D,SAAS,KAAK,CACZ,IAAY,EACZ,KAA0B,EAC1B,GAAW,EACX,OAAuB,EACvB,KAA2B;IAE3B,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,KAAK;QACL,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;QAC7D,KAAK;QACL,KAAK,EAAE,IAAI;QACX,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE;KACxB,CAAC;AACJ,CAAC;AAED,4EAA4E;AAC5E,SAAS,SAAS,CAAC,GAAqB;IACtC,MAAM,CAAC,GAAG,GAAG,CAAC,OAAkC,CAAC;IACjD,IACE,GAAG,CAAC,IAAI,KAAK,MAAM;QACnB,OAAO,CAAC,CAAC,SAAS,KAAK,QAAQ;QAC/B,CAAC,M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AAa,EAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC;YAC5D,IAAI,KAAK,GAAG,IAAI,GAAG,IAAI;gBAAE,MAAM,YAAY,CAAC,UAAU,EAAE,IAAI,GAAG,IAAI,EAAE,KAAK,CAAC,CAAC;YAC5E,MAAM,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;YAC3B,OAAO,WAAW,CAChB,KAAK,EACL,KAAK,EACL,MAAM,EACN,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,EAC/D,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,EAC/B,GAAG,CAAC,MAAM,EACV,IAAI,EACJ,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,EAC3C;gBACE,KAAK,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK;gBAC7B,OAAO,EAAE,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC;aAC3D,EACD,EAAE,IAAI,EAAE,IAAI,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,cAAc,EAAE,KAAK,EAAE,CAC7E,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The UTXO builder, broadcaster and RBF replacement policy.\n *\n * - `build` spends only outputs not held by another live Operation (`ctx.excludeInputs`),\n * pays change to the wallet's change address, and records the spent outpoints as the\n * `inputs` ordering. The fee is `exact` once built; the absurd-fee guard runs first.\n * - Every input a build, a replacement or a cancel spends is authenticated against its\n * previous transaction first: the indexer's value and script count only when the\n * bytes that hash to the outpoint's txid say the same. A lied value could burn the\n * difference as fee, or make our own signed bytes invalid for good and stall the\n * Operation with its inputs held.\n * - Replacements and cancels keep EVERY input of the Attempt they replace (and may add\n * confirmed ones), so each new Attempt conflicts with every earlier one (exclusion is\n * not transitive). Neither ever raises a fee on its own: a fee below the\n * replacement floor is `FEE_TOO_LOW`.\n * - A cancel pays everything back to the sending address itself.\n * - Broadcast answers are classified by `errors.ts`; an ambiguous transport failure is\n * rethrown unclassified. A node's rejection is a claim: it stands only when its reason\n * holds for the bytes that were sent, checked here; else `refused`. A terminal\n * `rejected` frees the inputs, so a lying endpoint that relayed our valid bytes would\n * let the caller's retry spend other coins, and both transactions could confirm.\n */\nimport type {\n BroadcastResult,\n Broadcaster,\n BuildContext,\n ReplacementPolicy,\n TxBuilder,\n} from '../../core/driver/types';\nimport {\n ChainError,\n ProviderError,\n SigningError,\n UnsupportedCapabilityError,\n ValidationError,\n isCryptoAioError,\n} from '../../core/errors/error';\nimport { assetId } from '../../core/model/asset';\nimport type { FeeEstimateDraft, FeeOverride, FeeSpeed } from '../../core/model/fee';\nimport type { DriverIntent, IntentSummary } from '../../core/model/intent';\nimport type { RawTx, SignedTx, UnsignedTx } from '../../core/model/transaction';\nimport type { SignatureBundle, SigningRequest } from '../../core/signing/types';\nimport { dustThreshold, type DecodedAddress, type WalletAddress } from './address';\nimport {\n assembleTx,\n assertPrevious,\n buildTx,\n isPreviousTxRefusal,\n previousTxOf,\n signaturesFromPsbt,\n viewPsbt,\n SEQUENCE_FINAL_LOCKTIME,\n SEQUENCE_RBF,\n type BuiltTx,\n type PlannedInput,\n type PreviousTx,\n} from './codec';\nimport {\n selectCoins,\n txWeight,\n vsizeOf,\n type PlannedOutput,\n type Selection,\n type Spendable,\n} from './coinselect';\nimport {\n READ,\n forEachBounded,\n signingScheme,\n withSignal,\n type UtxoContext,\n} from './context';\nimport { classifyOwnBroadcast, parseNodeError } from './errors';\nimport { assertConfirmed } from './proofs';\nimport { MAX_TX_BYTES, readTxHex } from './rawtx';\nimport { assertSaneFee, feeAt, replacementFloor } from './fees';\nimport type { Network } from './sdk';\nimport {\n assertNative,\n changeAddressOf,\n plannedOutputs,\n rateOf,\n senderOf,\n spendable,\n walletOf,\n type Sender,\n} from './spend';\nimport type { UtxoFeeDetails } from './types';\n\nconst speedOf = (fee: FeeSpeed | FeeOverride): FeeSpeed | 'custom' =>\n typeof fee === 'string' ? fee : 'custom';\n\nconst paidOf = (fee: FeeEstimateDraft): bigint =>\n fee.charges.reduce((sum, charge) => sum + charge.amount, 0n);\n\nfunction draft(\n from: string,\n speed: FeeSpeed | 'custom',\n fee: bigint,\n details: UtxoFeeDetails,\n bound: 'exact' | 'expected',\n): FeeEstimateDraft {\n return {\n kind: 'utxo',\n speed,\n charges: [{ asset: 'native', amount: fee, label: 'network' }],\n bound,\n payer: from,\n details: { ...details },\n };\n}\n\n/** `UtxoFeeDetails` of a stored fee, checked (it is our own plain data). */\nfunction detailsOf(fee: FeeEstimateDraft): UtxoFeeDetails {\n const d = fee.details as Partial<UtxoFeeDetails>;\n if (\n fee.kind !== 'utxo' ||\n typeof d.satPerKvB !== 'bigint' ||\n !Number.isSafeInteger(d.vsize) ||\n (d.vsize as number) < 1 ||\n typeof d.change !== 'bigint' ||\n !Number.isSafeInteger(d.changeIndex)\n ) {\n throw new ValidationError('INVALID_INTENT', 'the fee is not a UTXO fee estimate');\n }\n return d as UtxoFeeDetails;\n}\n\n/** Everything that builds a transaction; shared by the builder and the replacement policy. */\ninterface Scope {\n readonly ctx: UtxoContext;\n readonly network: Network;\n readonly sequence: number;\n}\n\nconst scopeOf = (ctx: UtxoContext, network: Network): Scope => ({\n ctx,\n network,\n sequence: ctx.config.rbf ? SEQUENCE_RBF : SEQUENCE_FINAL_LOCKTIME,\n});\n\nconst changeOf = (scope: Scope, build: BuildContext, sender: Sender): DecodedAddress =>\n changeAddressOf(scope.ctx, build.wallet, sender, build.keys);\n\n/**\n * The message is a fixed text, so no amount reaches a log line; the amounts go only in\n * the details, as decimal strings, as in every family.\n */\nconst insufficient = (\n what: 'this transfer' | 'the replacement' | 'a cancel',\n required: bigint,\n available: bigint,\n): ChainError =>\n new ChainError('INSUFFICIENT_FUNDS', `insufficient funds for ${what}`, {\n details: { required: required.toString(), available: available.toString() },\n });\n\n/** At most this many previous transactions are read at once for one build. */\nexport const PREVIOUS_TX_READS = 4;\n\n/**\n * A refusal of a previous transaction put on the provider: the inputs' outpoints and values\n * are the indexer's, and their previous transactions are bound to their txids, so authentic\n * bytes that disagree with the indexer's output decide nothing (retryable), never a user\n * error.\n */\nfunction onProvider<T>(work: () => T): T {\n try {\n return work();\n } catch (error) {\n if (!isPreviousTxRefusal(error)) throw error;\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n \"the indexer's unspent output disagrees with its previous transaction\",\n { retryable: true, cause: error },\n );\n }\n}\n\n/** The previous transaction of each txid, read at most `PREVIOUS_TX_READS` at a time. */\nasync function previousTxs(\n scope: Scope,\n txids: readonly string[],\n signal?: AbortSignal,\n): Promise<ReadonlyMap<string, PreviousTx>> {\n const found = new Map<string, PreviousTx>();\n await forEachBounded(txids, PREVIOUS_TX_READS, async (txid) => {\n const prev = await scope.ctx.esplora.previousTx(txid, withSignal(READ, signal));\n if (prev === null) {\n throw new ProviderError(\n 'PROVIDER_UNAVAILABLE',\n 'the previous transaction of an input is not available',\n );\n }\n found.set(txid, prev);\n });\n return found;\n}\n\n/** Which inputs of a build are new, and how their parents must be confirmed. */\ninterface NewInputs {\n /** The outpoints a replacement or cancel keeps: attested when their Attempt was built. */\n readonly kept: ReadonlySet<string>;\n /**\n * `minInputConfirmations: 0` on a transfer: an output of the wallet's own sent transaction\n * (its bytes known to this client) may be spent before a block holds it.\n */\n readonly ownUnconfirmed: boolean;\n}\n\n/**\n * Every input's value and script, authenticated against its previous transaction\n * (all wallet types, whatever `nonWitnessUtxo` says), so the node never judges bytes built\n * on an indexer's wrong value, and an outpoint its transaction does not have (a phantom\n * that nothing would ever spend, so never proven dead) is never built on. Either would\n * stall the Operation for good with its inputs held, since signed bytes cannot be\n * abandoned. A new input's previous transaction must also be in a block the proof quorum\n * attests, unless it is the wallet's own sent transaction and `minInputConfirmations` is\n * 0: a made-up parent would freeze the transfer the same way. p2pkh inputs carry it, and\n * segwit v0 ones while `nonWitnessUtxo` is on; taproot never does: BIP341 commits to\n * every amount, and `signed-psbt.ts` refuses one on a taproot input.\n */\nasync function authenticated(\n scope: Scope,\n wallet: WalletAddress,\n inputs: readonly Spendable[],\n fresh: NewInputs,\n signal?: AbortSignal,\n): Promise<PlannedInput[]> {\n const { esplora, config } = scope.ctx;\n // First, each new input's parent must be in a block the proof quorum attests,\n // at its own height; only then are its bytes read. Self-authenticating bytes prove what a\n // transaction is, never that a chain holds it.\n const parents = inputs\n .filter((input) => !fresh.kept.has(input.outpoint))\n .map((input) => input.txid)\n .filter((txid) => !(fresh.ownUnconfirmed && esplora.isOwn(txid)));\n await assertConfirmed(scope.ctx, parents, config.minInputConfirmations, signal);\n const embed =\n wallet.type === 'p2pkh' ||\n (wallet.type !== 'p2tr' && scope.ctx.config.nonWitnessUtxo);\n const txs = await previousTxs(scope, [...new Set(inputs.map((i) => i.txid))], signal);\n return inputs.map((input) => {\n const prevTx = txs.get(input.txid) as PreviousTx;\n onProvider(() => assertPrevious(prevTx, input, wallet.script));\n return embed ? { ...input, prevTx } : { ...input };\n });\n}\n\n/** `buildTx`, with its refusal of a previous transaction put on the provider. */\nfunction builtFor(\n scope: Scope,\n wallet: WalletAddress,\n inputs: readonly PlannedInput[],\n outputs: readonly PlannedOutput[],\n): BuiltTx {\n return onProvider(() =>\n buildTx(scope.network, wallet, inputs, outputs, scope.sequence),\n );\n}\n\n/** The unsigned transaction for a selection: PSBT, one request per input, exact fee, ordering. */\nasync function unsignedFor(\n scope: Scope,\n build: BuildContext,\n sender: Sender,\n selection: Selection,\n outputs: readonly PlannedOutput[],\n changeScript: Uint8Array,\n rate: bigint,\n speed: FeeSpeed | 'custom',\n summary: IntentSummary,\n fresh: NewInputs,\n): Promise<UnsignedTx> {\n const { wallet, key } = walletOf(scope.ctx, sender, build.keys);\n assertSaneFee(selection.fee, selection.vsize, scope.ctx.config);\n const all: PlannedOutput[] =\n selection.change > 0n\n ? [...outputs, { script: changeScript, value: selection.change }]\n : [...outputs];\n const inputs = await authenticated(\n scope,\n wallet,\n selection.inputs,\n fresh,\n build.signal,\n );\n const built = builtFor(scope, wallet, inputs, all);\n const signingRequests: SigningRequest[] = built.digests.map((digest, index) => ({\n id: `in:${index}`,\n scheme: signingScheme(wallet.type),\n payload: digest,\n payloadKind: 'digest',\n publicKey:\n wallet.type === 'p2tr' ? (wallet.outputKey as Uint8Array) : wallet.publicKey,\n ...(key.keyRef ? { keyRef: key.keyRef } : {}),\n ...(wallet.tweak ? { params: { tweak: wallet.tweak } } : {}),\n }));\n return {\n payload: { encoding: 'base64', data: built.psbt },\n ...(built.txid !== undefined\n ? { expectedRef: { id: built.txid, idKind: 'txid', canonical: true } }\n : {}),\n signingRequests,\n ordering: { kind: 'inputs', inputs: selection.inputs.map((i) => i.outpoint).sort() },\n fee: draft(\n sender.from.canonical,\n speed,\n selection.fee,\n {\n satPerKvB: rate,\n vsize: selection.vsize,\n inputs: selection.inputs.length,\n outputs: all.length,\n change: selection.change,\n changeIndex: selection.change > 0n ? outputs.length : -1,\n },\n 'exact',\n ),\n summary,\n };\n}\n\n/** The replaced Attempt: its inputs (values from its PSBT), payments (no change) and fee. */\nfunction previousOf(scope: Scope, previous: UnsignedTx, sender: Sender) {\n const details = detailsOf(previous.fee);\n const view = viewPsbt(previous.payload.data, scope.network);\n const inputs: Spendable[] = view.inputs.map((i) => ({\n outpoint: i.outpoint,\n txid: i.txid,\n vout: i.vout,\n value: i.value,\n }));\n const outputs = view.outputs.filter((_, index) => index !== details.changeIndex);\n // A real signature may be a byte shorter than the worst case the estimate counts: a\n // full vbyte per legacy input, a quarter per witness input.\n const slack = sender.type === 'p2pkh' ? inputs.length : Math.ceil(inputs.length / 4);\n const minVsize = Math.max(1, details.vsize - slack);\n return { vsize: details.vsize, minVsize, inputs, outputs, paid: paidOf(previous.fee) };\n}\n\nexport interface UtxoBuilder extends TxBuilder {\n signaturesFrom(unsigned: UnsignedTx, signed: RawTx): readonly SignatureBundle[];\n}\n\nexport function utxoBuilder(ctx: UtxoContext, network: Network): UtxoBuilder {\n const scope = scopeOf(ctx, network);\n const { config } = ctx;\n const native = assetId(ctx.chain.id, ctx.network.id, 'native');\n\n const plan = async (intent: DriverIntent, rate: bigint, build: BuildContext) => {\n assertNative(intent.asset);\n // Defence in depth behind the network's capability check: nothing here writes a memo,\n // and the core would otherwise accept one this builder drops.\n if (intent.memo !== undefined) {\n throw new UnsupportedCapabilityError(\n 'UNSUPPORTED_CAPABILITY',\n 'Bitcoin transfers carry no memo (OP_RETURN is not supported)',\n );\n }\n const sender = senderOf(ctx, intent.from);\n const outputs = plannedOutputs(ctx, intent.outputs);\n const changeScript = changeOf(scope, build, sender).script;\n const candidates = await spendable(\n ctx,\n sender.from.canonical,\n build.excludeInputs,\n config.minInputConfirmations,\n build.signal,\n );\n const selection = selectCoins({\n candidates,\n outputs,\n changeScript,\n inputType: sender.type,\n rate,\n dustRelayFee: config.dustRelayFee,\n strategy: config.coinSelection,\n });\n return { sender, outputs, changeScript, selection };\n };\n\n return {\n async estimateFee(intent, build) {\n const rate = await rateOf(ctx, intent.fee, build.signal);\n const { sender, selection } = await plan(intent, rate, build);\n const change = selection.ok ? selection.change : 0n;\n return draft(\n sender.from.canonical,\n speedOf(intent.fee),\n selection.fee,\n {\n satPerKvB: rate,\n vsize: selection.vsize,\n inputs: selection.ok ? selection.inputs.length : 0,\n outputs: intent.outputs.length + (change > 0n ? 1 : 0),\n change,\n changeIndex: change > 0n ? intent.outputs.length : -1,\n },\n 'expected',\n );\n },\n\n async checkFunds(intent, fee, build) {\n assertNative(intent.asset);\n const candidates = await spendable(\n ctx,\n senderOf(ctx, intent.from).from.canonical,\n build.excludeInputs,\n config.minInputConfirmations,\n build.signal,\n );\n const available = candidates.reduce((sum, c) => sum + c.value, 0n);\n const required =\n intent.outputs.reduce((sum, o) => sum + o.amount, 0n) + paidOf(fee);\n return available >= required\n ? { ok: true }\n : { ok: false, asset: 'native', required, available };\n },\n\n async build(intent, fee, build) {\n const rate = detailsOf(fee).satPerKvB;\n const { sender, outputs, changeScript, selection } = await plan(\n intent,\n rate,\n build,\n );\n if (!selection.ok) {\n throw insufficient('this transfer', selection.required, selection.available);\n }\n return unsignedFor(\n scope,\n build,\n sender,\n selection,\n outputs,\n changeScript,\n rate,\n fee.speed,\n {\n asset: native,\n outputs: intent.outputs.map((o) => ({ to: o.to, amount: o.amount.toString() })),\n },\n { kept: new Set(), ownUnconfirmed: config.minInputConfirmations === 0 },\n );\n },\n\n async assemble(unsigned, signatures) {\n const { hex, txid } = assembleTx(\n unsigned.payload.data,\n network,\n unsigned.signingRequests,\n signatures,\n );\n if (unsigned.expectedRef && unsigned.expectedRef.id !== txid) {\n throw new SigningError(\n 'SIGNING_FAILED',\n 'the signed transaction id differs from the prepared one',\n );\n }\n return {\n raw: { encoding: 'hex', data: hex },\n ref: { id: txid, idKind: 'txid', canonical: true },\n };\n },\n\n signaturesFrom(unsigned, signed) {\n if (signed.encoding !== 'base64') {\n throw new ValidationError(\n 'INVALID_INTENT',\n 'a signed PSBT is expected, as base64',\n );\n }\n return signaturesFromPsbt(\n unsigned.payload.data,\n signed.data,\n network,\n unsigned.signingRequests,\n );\n },\n };\n}\n\n/**\n * Twice Bitcoin Core's `MAX_BLOCK_SERIALIZED_SIZE`: no transaction's hex is longer, so\n * the untrusted text is capped before any decoding. A flat character class, never a\n * repeated group: V8's regexp stack overflows on a repeated group of a few million\n * matches, which a valid transaction can have.\n */\nconst MAX_TX_HEX = 8_000_000;\nconst HEX = /^[0-9a-fA-F]+$/;\n\n/**\n * An Attempt's bytes a node took (accepted, or already holds) are this wallet's\n * own sent transaction: its client keeps them. A bare broadcast (no ref) is not an Attempt.\n */\nfunction rememberOwn(ctx: UtxoContext, signed: SignedTx, hex: string): void {\n if (signed.ref.id === '') return;\n const tx = previousTxOf(hex);\n if (tx?.txid === signed.ref.id) ctx.esplora.rememberOwn(tx);\n}\n\nexport function utxoBroadcaster(ctx: UtxoContext): Broadcaster {\n return {\n async broadcast(signed: SignedTx, options = {}): Promise<BroadcastResult> {\n const { encoding, data } = signed.raw;\n if (\n encoding !== 'hex' ||\n data.length > MAX_TX_HEX ||\n data.length % 2 !== 0 ||\n !HEX.test(data)\n ) {\n throw new ValidationError('INVALID_INTENT', 'a raw Bitcoin transaction is hex');\n }\n const hex = data.toLowerCase();\n try {\n const txid = await ctx.esplora.broadcast(hex, {\n purpose: 'broadcast',\n retry: 'ambiguous-on-failure',\n ...(options.fanout !== undefined ? { fanout: options.fanout } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n // A bare broadcast (no ref) is checked against the bytes' own txid.\n const expected =\n signed.ref.id !== ''\n ? signed.ref.id\n : readTxHex(hex, { maxStripped: MAX_TX_BYTES })?.txid;\n if (txid !== expected) {\n // The node accepted something under another id: the outcome is unknown.\n throw new ProviderError(\n 'PROVIDER_UNAVAILABLE',\n 'the node answered another txid',\n {\n ambiguous: true,\n },\n );\n }\n rememberOwn(ctx, signed, hex);\n return { kind: 'accepted' };\n } catch (error) {\n // A definitive 400 is bitcoind's answer; anything else is rethrown. A rejection\n // stands only when its reason holds for these bytes, checked here.\n if (\n isCryptoAioError(error, 'RPC_ERROR') &&\n !error.ambiguous &&\n error.details?.status === 400\n ) {\n const result = classifyOwnBroadcast(\n parseNodeError(String(error.details.body ?? '')),\n hex,\n );\n if (result.kind === 'already-known') rememberOwn(ctx, signed, hex);\n return result;\n }\n throw error;\n }\n },\n };\n}\n\nconst tooLow = (): ChainError =>\n new ChainError(\n 'FEE_TOO_LOW',\n 'a replacement must pay the replaced fee plus the incremental relay fee, at a higher rate',\n );\n\nexport function utxoReplacement(ctx: UtxoContext, network: Network): ReplacementPolicy {\n const scope = scopeOf(ctx, network);\n const { config } = ctx;\n return {\n replace: true,\n cancel: true,\n\n async buildReplacement(previous, fee, build) {\n const sender = senderOf(ctx, build.from);\n const prev = previousOf(scope, previous, sender);\n const rate = await rateOf(ctx, fee, build.signal);\n const changeScript = changeOf(scope, build, sender).script;\n // BIP125 rule 2: an input it adds must be confirmed; it never takes a held one.\n const candidates = await spendable(\n ctx,\n sender.from.canonical,\n [...(build.excludeInputs ?? []), ...prev.inputs.map((i) => i.outpoint)],\n Math.max(1, config.minInputConfirmations),\n build.signal,\n );\n const selection = selectCoins({\n candidates,\n required: prev.inputs,\n outputs: prev.outputs,\n changeScript,\n inputType: sender.type,\n rate,\n dustRelayFee: config.dustRelayFee,\n strategy: 'accumulative',\n });\n if (!selection.ok) {\n throw insufficient('the replacement', selection.required, selection.available);\n }\n const floor = replacementFloor(\n { fee: prev.paid, vsize: prev.vsize, minVsize: prev.minVsize },\n selection.vsize,\n config.incrementalRelayFee,\n );\n if (selection.fee < floor) throw tooLow();\n return unsignedFor(\n scope,\n build,\n sender,\n selection,\n prev.outputs,\n changeScript,\n rate,\n speedOf(fee),\n previous.summary,\n { kept: new Set(prev.inputs.map((i) => i.outpoint)), ownUnconfirmed: false },\n );\n },\n\n async buildCancel(previous, build, fee) {\n const sender = senderOf(ctx, build.from);\n const prev = previousOf(scope, previous, sender);\n // A cancel pays everything back to the sending address itself, never to a\n // configured change address (under `allowExternalChangeAddress` an external one). A\n // misconfigured change address is still refused here, as on every path.\n changeOf(scope, build, sender);\n const own = sender.from;\n const total = prev.inputs.reduce((sum, i) => sum + i.value, 0n);\n const vsize = vsizeOf(\n txWeight(sender.type, prev.inputs.length, [own.script.length]),\n );\n const floor = replacementFloor(\n { fee: prev.paid, vsize: prev.vsize, minVsize: prev.minVsize },\n vsize,\n config.incrementalRelayFee,\n );\n let paid = floor;\n let rate = (floor * 1_000n + BigInt(vsize) - 1n) / BigInt(vsize);\n if (fee !== undefined) {\n rate = await rateOf(ctx, fee, build.signal);\n paid = feeAt(rate, vsize);\n if (paid < floor) throw tooLow();\n }\n const dust = dustThreshold(own.script, config.dustRelayFee);\n if (total - paid < dust) throw insufficient('a cancel', paid + dust, total);\n const value = total - paid;\n return unsignedFor(\n scope,\n build,\n sender,\n { ok: true, inputs: prev.inputs, change: 0n, fee: paid, vsize },\n [{ script: own.script, value }],\n own.script,\n rate,\n fee === undefined ? 'custom' : speedOf(fee),\n {\n asset: previous.summary.asset,\n outputs: [{ to: own.canonical, amount: value.toString() }],\n },\n { kept: new Set(prev.inputs.map((i) => i.outpoint)), ownUnconfirmed: false },\n );\n },\n };\n}\n"]}
@@ -90,7 +90,8 @@ exports.BITCOIN_CHAIN = (0, freeze_1.deepFreeze)({
90
90
  family: 'utxo',
91
91
  model: 'utxo',
92
92
  ordering: 'inputs',
93
- // keys[0] (the ECDSA key) defines the address; p2tr wallets also sign with Schnorr.
93
+ // keys[0] (the ECDSA key) defines the address. A p2tr wallet signs with Schnorr only, so
94
+ // its signer must declare it (the driver's `signingSchemes`).
94
95
  schemes: ['secp256k1-ecdsa', 'secp256k1-schnorr'],
95
96
  nativeAsset: { symbol: 'BTC', decimals: 8, name: 'Bitcoin' },
96
97
  defaultNetwork: 'mainnet',
@@ -1 +1 @@
1
- {"version":3,"file":"chains.js","sourceRoot":"","sources":["../../../src/adapters/utxo/chains.ts"],"names":[],"mappings":";;;AAeA,mDAAoD;AAcpD,MAAM,QAAQ,GAA2B;IACvC;QACE,EAAE,EAAE,SAAS;QACb,OAAO,EAAE,kEAAkE;QAC3E,OAAO,EAAE,KAAK;QACd,MAAM,EAAE,IAAI;QACZ,UAAU,EAAE,IAAI;QAChB,UAAU,EAAE,IAAI;QAChB,QAAQ,EAAE,0BAA0B;QACpC,YAAY,EAAE,CAAC;KAChB;IACD;QACE,EAAE,EAAE,SAAS;QACb,OAAO,EAAE,kEAAkE;QAC3E,OAAO,EAAE,IAAI;QACb,MAAM,EAAE,IAAI;QACZ,UAAU,EA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B,CAAC,CAAC;gBACE,QAAQ,EAAE;oBACR,EAAE,EAAE,GAAG,IAAI,CAAC,QAAQ,UAAU;oBAC9B,OAAO,EAAE,GAAG,IAAI,CAAC,QAAQ,oBAAoB;iBAC9C;aACF;YACH,CAAC,CAAC,EAAE,CAAC;QACP,MAAM,EAAE;YACN,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,YAAY,EAAE,KAAM;YACpB,WAAW,EAAE,KAAM;YACnB,mBAAmB,EAAE,KAAM;YAC3B,GAAG,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC7E;KACF,CAAC;AACJ,CAAC;AAED,0EAA0E;AAC7D,QAAA,aAAa,GAAc,IAAA,mBAAU,EAAC;IACjD,EAAE,EAAE,SAAS;IACb,MAAM,EAAE,MAAM;IACd,KAAK,EAAE,MAAM;IACb,QAAQ,EAAE,QAAQ;IAClB,oFAAoF;IACpF,OAAO,EAAE,CAAC,iBAAiB,EAAE,mBAAmB,CAAC;IACjD,WAAW,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE;IAC5D,cAAc,EAAE,SAAS;IACzB,QAAQ,EAAE,MAAM,CAAC,WAAW,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;CAC/E,CAAC,CAAC","sourcesContent":["/**\n * The built-in Bitcoin chain and networks. Genesis hashes and address prefixes are\n * verified against Bitcoin Core's `src/kernel/chainparams.cpp`, and relay-policy numbers\n * against its `src/policy/policy.h` and `policy.cpp`; the rest is library policy:\n * - `finality: 6 confirmations` on every network, `defaultConfirmations: 1`\n * (`waitForConfirmation` waits for inclusion by default; credit deposits on `final`).\n * - `reorgWindow: 24` (four times the finality depth).\n * - `maxLagBlocks`: 2 on mainnet and signet, 6 on the testnets (their 20-minute\n * minimum-difficulty rule produces bursts of blocks), the transport default on regtest.\n * - `minRelayFee` and `incrementalRelayFee` 1,000 sat/kvB (1 sat/vB): the defaults of\n * Bitcoin Core before v30, so older nodes relay what this library builds.\n * - `feeFallback`: the rate used when a test network's estimator has no data (never on\n * mainnet, where a missing estimate fails the read instead).\n */\nimport type { ChainInfo, NetworkInfo } from '../../core/model/chain';\nimport { deepFreeze } from '../../core/util/freeze';\n\ninterface NetworkSpec {\n readonly id: string;\n readonly genesis: string;\n readonly testnet: boolean;\n readonly bech32: string;\n readonly pubKeyHash: number;\n readonly scriptHash: number;\n readonly explorer?: string;\n readonly maxLagBlocks?: number;\n readonly feeFallback?: bigint;\n}\n\nconst NETWORKS: readonly NetworkSpec[] = [\n {\n id: 'mainnet',\n genesis: '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f',\n testnet: false,\n bech32: 'bc',\n pubKeyHash: 0x00,\n scriptHash: 0x05,\n explorer: 'https://blockstream.info',\n maxLagBlocks: 2,\n },\n {\n id: 'testnet',\n genesis: '000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943',\n testnet: true,\n bech32: 'tb',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n explorer: 'https://blockstream.info/testnet',\n maxLagBlocks: 6,\n feeFallback: 1_000n,\n },\n {\n id: 'testnet4',\n genesis: '00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043',\n testnet: true,\n bech32: 'tb',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n maxLagBlocks: 6,\n feeFallback: 1_000n,\n },\n {\n id: 'signet',\n genesis: '00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6',\n testnet: true,\n bech32: 'tb',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n explorer: 'https://blockstream.info/signet',\n maxLagBlocks: 2,\n feeFallback: 1_000n,\n },\n {\n id: 'regtest',\n genesis: '0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206',\n testnet: true,\n bech32: 'bcrt',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n feeFallback: 1_000n,\n },\n];\n\nfunction network(spec: NetworkSpec): NetworkInfo {\n return {\n id: spec.id,\n identity: spec.genesis,\n testnet: spec.testnet,\n feeModel: 'utxo',\n finality: { kind: 'confirmations', confirmations: 6 },\n defaultConfirmations: 1,\n reorgWindow: 24,\n ...(spec.maxLagBlocks !== undefined ? { maxLagBlocks: spec.maxLagBlocks } : {}),\n ...(spec.explorer !== undefined\n ? {\n explorer: {\n tx: `${spec.explorer}/tx/{id}`,\n address: `${spec.explorer}/address/{address}`,\n },\n }\n : {}),\n params: {\n bech32: spec.bech32,\n pubKeyHash: spec.pubKeyHash,\n scriptHash: spec.scriptHash,\n dustRelayFee: 3_000n,\n minRelayFee: 1_000n,\n incrementalRelayFee: 1_000n,\n ...(spec.feeFallback !== undefined ? { feeFallback: spec.feeFallback } : {}),\n },\n };\n}\n\n/** Deep-frozen, so no caller can change a network another handle uses. */\nexport const BITCOIN_CHAIN: ChainInfo = deepFreeze({\n id: 'bitcoin',\n family: 'utxo',\n model: 'utxo',\n ordering: 'inputs',\n // keys[0] (the ECDSA key) defines the address; p2tr wallets also sign with Schnorr.\n schemes: ['secp256k1-ecdsa', 'secp256k1-schnorr'],\n nativeAsset: { symbol: 'BTC', decimals: 8, name: 'Bitcoin' },\n defaultNetwork: 'mainnet',\n networks: Object.fromEntries(NETWORKS.map((spec) => [spec.id, network(spec)])),\n});\n"]}
1
+ {"version":3,"file":"chains.js","sourceRoot":"","sources":["../../../src/adapters/utxo/chains.ts"],"names":[],"mappings":";;;AAeA,mDAAoD;AAcpD,MAAM,QAAQ,GAA2B;IACvC;Q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AAQ,EAAE,MAAM,CAAC,WAAW,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;CAC/E,CAAC,CAAC","sourcesContent":["/**\n * The built-in Bitcoin chain and networks. Genesis hashes and address prefixes are\n * verified against Bitcoin Core's `src/kernel/chainparams.cpp`, and relay-policy numbers\n * against its `src/policy/policy.h` and `policy.cpp`; the rest is library policy:\n * - `finality: 6 confirmations` on every network, `defaultConfirmations: 1`\n * (`waitForConfirmation` waits for inclusion by default; credit deposits on `final`).\n * - `reorgWindow: 24` (four times the finality depth).\n * - `maxLagBlocks`: 2 on mainnet and signet, 6 on the testnets (their 20-minute\n * minimum-difficulty rule produces bursts of blocks), the transport default on regtest.\n * - `minRelayFee` and `incrementalRelayFee` 1,000 sat/kvB (1 sat/vB): the defaults of\n * Bitcoin Core before v30, so older nodes relay what this library builds.\n * - `feeFallback`: the rate used when a test network's estimator has no data (never on\n * mainnet, where a missing estimate fails the read instead).\n */\nimport type { ChainInfo, NetworkInfo } from '../../core/model/chain';\nimport { deepFreeze } from '../../core/util/freeze';\n\ninterface NetworkSpec {\n readonly id: string;\n readonly genesis: string;\n readonly testnet: boolean;\n readonly bech32: string;\n readonly pubKeyHash: number;\n readonly scriptHash: number;\n readonly explorer?: string;\n readonly maxLagBlocks?: number;\n readonly feeFallback?: bigint;\n}\n\nconst NETWORKS: readonly NetworkSpec[] = [\n {\n id: 'mainnet',\n genesis: '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f',\n testnet: false,\n bech32: 'bc',\n pubKeyHash: 0x00,\n scriptHash: 0x05,\n explorer: 'https://blockstream.info',\n maxLagBlocks: 2,\n },\n {\n id: 'testnet',\n genesis: '000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943',\n testnet: true,\n bech32: 'tb',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n explorer: 'https://blockstream.info/testnet',\n maxLagBlocks: 6,\n feeFallback: 1_000n,\n },\n {\n id: 'testnet4',\n genesis: '00000000da84f2bafbbc53dee25a72ae507ff4914b867c565be350b0da8bf043',\n testnet: true,\n bech32: 'tb',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n maxLagBlocks: 6,\n feeFallback: 1_000n,\n },\n {\n id: 'signet',\n genesis: '00000008819873e925422c1ff0f99f7cc9bbb232af63a077a480a3633bee1ef6',\n testnet: true,\n bech32: 'tb',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n explorer: 'https://blockstream.info/signet',\n maxLagBlocks: 2,\n feeFallback: 1_000n,\n },\n {\n id: 'regtest',\n genesis: '0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206',\n testnet: true,\n bech32: 'bcrt',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n feeFallback: 1_000n,\n },\n];\n\nfunction network(spec: NetworkSpec): NetworkInfo {\n return {\n id: spec.id,\n identity: spec.genesis,\n testnet: spec.testnet,\n feeModel: 'utxo',\n finality: { kind: 'confirmations', confirmations: 6 },\n defaultConfirmations: 1,\n reorgWindow: 24,\n ...(spec.maxLagBlocks !== undefined ? { maxLagBlocks: spec.maxLagBlocks } : {}),\n ...(spec.explorer !== undefined\n ? {\n explorer: {\n tx: `${spec.explorer}/tx/{id}`,\n address: `${spec.explorer}/address/{address}`,\n },\n }\n : {}),\n params: {\n bech32: spec.bech32,\n pubKeyHash: spec.pubKeyHash,\n scriptHash: spec.scriptHash,\n dustRelayFee: 3_000n,\n minRelayFee: 1_000n,\n incrementalRelayFee: 1_000n,\n ...(spec.feeFallback !== undefined ? { feeFallback: spec.feeFallback } : {}),\n },\n };\n}\n\n/** Deep-frozen, so no caller can change a network another handle uses. */\nexport const BITCOIN_CHAIN: ChainInfo = deepFreeze({\n id: 'bitcoin',\n family: 'utxo',\n model: 'utxo',\n ordering: 'inputs',\n // keys[0] (the ECDSA key) defines the address. A p2tr wallet signs with Schnorr only, so\n // its signer must declare it (the driver's `signingSchemes`).\n schemes: ['secp256k1-ecdsa', 'secp256k1-schnorr'],\n nativeAsset: { symbol: 'BTC', decimals: 8, name: 'Bitcoin' },\n defaultNetwork: 'mainnet',\n networks: Object.fromEntries(NETWORKS.map((spec) => [spec.id, network(spec)])),\n});\n"]}