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":"reader.js","sourceRoot":"","sources":["../../../src/adapters/ton/reader.ts"],"names":[],"mappings":";;;AA+HA,oBAGC;AAED,4CAqBC;AAgFD,kDA2BC;AAMD,sCAiBC;AAuBD,8CA4BC;AASD,gDAgBC;AAuOD,oCASC;AAED,sCAOC;AA6BD,wCAYC;AAiBD,kCAkCC;AAGD,gCAEC;AAqCD,8CAyBC;AAKD,0CA6EC;AA8CD,kCAMC;AA+CD,kCAwBC;AAaD,sCAkBC;AAyDD,8CAWC;AAED,oCAgBC;AAjkCD;;;;;GAKG;AACH,oCAA+D;AAC/D,6CAAyC;AASzC,mDAMiC;AAMjC,uCAAkD;AAClD,+BAgBe;AACf,qCAMkB;AAClB,yCAMoB;AAEpB,mCAMiB;AAEjB,uCAAyE;AAkDzE,0FAA0F;AAC7E,QAAA,UAAU,GAAG,KAAK,CAAC;AAChC,sFAAsF;AACzE,QAAA,cAAc,GAAG,MAAM,CAAC;AACrC,4FAA4F;AAC/E,QAAA,cAAc,GAAG,KAAK,CAAC;AAEpC,gFAAgF;AAChF,SAAgB,IAAI,CAAO,IAAe,EAAE,GAAM,EAAE,KAAQ,EAAE,IAAY;IACxE,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACrB,IAAI,IAAI,CAAC,IAAI,GAAG,IAAI;QAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAU,CAAC,CAAC;A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AACJ,CAAC","sourcesContent":["/**\n * TON addresses, reads, seqnos, jetton lookups and the `ext.ton` API. Every call carries the\n * tags of the `ChainDriver` contract table (`src/core/driver/types.ts`): `read` for point\n * queries, `monitor` for heights, observations and seqnos. Jetton metadata, which the\n * core caches for the container's life, is a `read` under the proof quorum.\n */\nimport { Cell, Dictionary, type Transaction } from '@ton/core';\nimport { createHash } from 'node:crypto';\nimport type {\n AddressCodec,\n ChainReader,\n DriverBlock,\n DriverTxObservation,\n SequenceSource,\n WalletOptions,\n} from '../../core/driver/types';\nimport {\n ChainError,\n ProviderError,\n ValidationError,\n isCryptoAioError,\n withContext,\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 { AttemptRef } from '../../core/model/transaction';\nimport type { Clock } from '../../core/util/clock';\nimport { createTonAddressCodec } from './address';\nimport {\n MASTERCHAIN_SHARD,\n MONITOR,\n PROOF,\n READ,\n jettonDataOf,\n runResultOf,\n sameBlock,\n type AccountState,\n type BlockHeader,\n type BlockId,\n type BoundRunResult,\n type RunResult,\n type TonApi,\n type V3Trace,\n type V3Transaction,\n} from './api';\nimport {\n decodeTransaction,\n executed,\n jettonWalletToVerify,\n ran,\n type VerifiedJettonWallet,\n} from './decode';\nimport {\n addressArgument,\n addressFromBoc,\n decodeWalletRequest,\n messageBody,\n type WalletRequest,\n} from './messages';\nimport type { TonNetworkConfig } from './network';\nimport {\n REASONS,\n attemptVerdict,\n consumesSeqno,\n isOwnAttempt,\n type Verdict,\n} from './trace';\nimport type { TonCallTags, TonExt } from './types';\nimport { requestIsOwn, resolveIdentity, walletAddress } from './wallets';\n\n/**\n * What every TON port is built from. Drivers are shared: the caches hold only immutable\n * chain data, values the proof quorum attested or transactions bound to their own hash\n * (`chainTxs`); a single `read` or `monitor` answer is used once and never cached. The one\n * record of anything else is `assembled`, for the replay guard: what this driver itself\n * built and sent.\n */\nexport interface TonContext {\n readonly api: TonApi;\n readonly chain: ChainInfo;\n readonly network: NetworkInfo;\n readonly config: TonNetworkConfig;\n readonly log: Logger;\n readonly clock: Clock;\n readonly codec: AddressCodec;\n /** `master|owner` → the jetton wallet the master names, as the quorum attested it. */\n readonly jettonWallets: Map<string, string>;\n /** jetton wallet → its owner and master, verified under the quorum. */\n readonly verified: Map<string, VerifiedJettonWallet>;\n /**\n * Wallet transactions the chain walk authenticated, by `lt:hash`. A\n * transaction is immutable and its cell hashes to its id, so a kept one is as good as one\n * fetched again; each walk fetches only what it has not seen (bounded, `CHAIN_MEMO`).\n */\n readonly chainTxs: Map<string, Transaction>;\n /**\n * The external messages this driver assembled, by TEP-467 hash: the build's recorded\n * chain time and whether they were ever handed to a send (bounded, `ASSEMBLED_MEMO`).\n * Known gap: the `Broadcaster` port carries only the bytes, never the Attempt's\n * ordering, so the replay guard keeps this memo; bytes this driver did not assemble, or\n * has evicted, are guarded with the widest window (one day).\n */\n readonly assembled: Map<string, AssembledMessage>;\n}\n\n/** What `assemble` recorded about a message it made. */\nexport interface AssembledMessage {\n /** `TonSeqnoOrdering.validFrom`, as the ordering bound to the signed bytes holds it. */\n readonly validFrom: number;\n /**\n * The driver's clock when `assemble` ran, in ms: a first send skips the replay guard only\n * within `FIRST_SEND_MS` of it.\n */\n readonly assembledAt: number;\n /** Set before the first send; never cleared. */\n sent: boolean;\n}\n\n/** The most authenticated transactions a driver keeps (each at most `MEMO_TX_LENGTH`). */\nexport const CHAIN_MEMO = 4_096;\n/** The longest transaction BOC text kept: a wallet transaction takes about 1-2 KB. */\nexport const MEMO_TX_LENGTH = 16_384;\n/** The most assembled messages a driver remembers; an evicted one is guarded as foreign. */\nexport const ASSEMBLED_MEMO = 4_096;\n\n/** Keeps `value` in a bounded memo, dropping the oldest entry beyond `size`. */\nexport function keep<K, V>(memo: Map<K, V>, key: K, value: V, size: number): void {\n memo.set(key, value);\n if (memo.size > size) memo.delete(memo.keys().next().value as K);\n}\n\nexport function createTonContext(args: {\n readonly api: TonApi;\n readonly chain: ChainInfo;\n readonly network: NetworkInfo;\n readonly config: TonNetworkConfig;\n readonly log: Logger;\n readonly clock: Clock;\n}): TonContext {\n const codec = createTonAddressCodec({\n testnet: args.config.testnet,\n fromPublicKey: (publicKey: Uint8Array, wallet?: WalletOptions) =>\n walletAddress(resolveIdentity(wallet, args.config.globalId), publicKey),\n });\n return {\n ...args,\n codec,\n jettonWallets: new Map(),\n verified: new Map(),\n chainTxs: new Map(),\n assembled: new Map(),\n };\n}\n\nconst assetError = (reason: string) => new ValidationError('ASSET_RESOLUTION', reason);\n\nconst notYet = (reason: string) =>\n new ProviderError('PROVIDER_UNAVAILABLE', reason, { retryable: true });\n\n/**\n * Metadata the indexer does not have, for a token read anywhere (`jettonMetadata`):\n * non-retryable, so the core reports a transfer of it unresolved instead of failing the\n * read, and not `ASSET_RESOLUTION`, so the core never caches it.\n */\nconst unresolvable = (reason: string) =>\n new ProviderError('PROVIDER_UNAVAILABLE', reason, { retryable: false });\n\n/**\n * The core caches a token's metadata,\n * and its \"no such token\", for the container's life, so one lagging or buggy endpoint must\n * never decide it. Balances stay plain reads.\n */\nconst METADATA: TonCallTags = { ...READ, quorum: 'proof' };\n\n/**\n * A token's own failure (a missing account, a TVM exit code, content that does\n * not parse) is `ASSET_RESOLUTION`; `PROVIDER_MISCONFIGURED` and already retryable errors\n * propagate unchanged; any other definitive node answer is made retryable.\n */\nfunction asRetryable(error: unknown): unknown {\n if (\n isCryptoAioError(error) &&\n error.category === 'provider' &&\n !error.retryable &&\n error.code !== 'PROVIDER_MISCONFIGURED'\n ) {\n return withContext(error, {}, { retryable: true });\n }\n return error;\n}\n\nasync function tokenCall<T>(work: () => Promise<T>): Promise<T> {\n try {\n return await work();\n } catch (error) {\n throw asRetryable(error);\n }\n}\n\nconst cellStack = (entry: RunResult['stack'][number] | undefined): string | undefined =>\n entry?.type === 'cell' ? entry.boc : undefined;\n\n/** A lookup id (a 32-byte hash in hex, either case) in lower case; undefined otherwise. */\nconst hashId = (id: string): string | undefined =>\n typeof id === 'string' && /^[0-9a-fA-F]{64}$/.test(id) ? id.toLowerCase() : undefined;\n\n/** The wallet address a `get_wallet_address` answer names; null when it names none. */\nfunction namedWallet(result: RunResult): string | null {\n const boc = result.exitCode === 0 ? cellStack(result.stack[0]) : undefined;\n return boc ? addressFromBoc(boc) : null;\n}\n\n/**\n * What endpoints must agree on for `get_wallet_address`: the exit code and the\n * address it names, never the slice's serialization. It never throws: an answer that does\n * not parse is itself a fact, which the parse then refuses (retryable).\n */\nfunction walletAddressKey(body: unknown): unknown {\n try {\n const result = runResultOf(body);\n return { exitCode: result.exitCode, wallet: namedWallet(result) };\n } catch {\n return 'malformed';\n }\n}\n\n/**\n * The jetton wallet `master` assigns to `owner` (`get_wallet_address`), at masterchain\n * block `block` when given. Cached only when the proof quorum attested it: the builder\n * sends jettons to it and the verdict checks it, so one endpoint's answer must never stick.\n * Under a quorum the endpoints agree on the address itself (`walletAddressKey`).\n */\nexport async function jettonWalletAddress(\n ctx: TonContext,\n master: string,\n owner: string,\n tags: TonCallTags,\n block?: number,\n): Promise<string> {\n const key = `${master}|${owner}`;\n const cached = ctx.jettonWallets.get(key);\n if (cached) return cached;\n const keyed =\n tags.quorum !== undefined && tags.quorumKey === undefined\n ? { ...tags, quorumKey: walletAddressKey }\n : tags;\n const result = await tokenCall(() =>\n ctx.api.runGetMethod(\n master,\n 'get_wallet_address',\n [['tvm.Slice', addressArgument(owner)]],\n keyed,\n block,\n ),\n );\n const address = namedWallet(result);\n if (!address) throw assetError('the jetton master gives no wallet address');\n if (tags.quorum !== undefined) ctx.jettonWallets.set(key, address);\n return address;\n}\n\n/**\n * `owner`'s jetton balance; 0 while its jetton wallet is not deployed. The state and the\n * balance are read at one block, so a load-balanced endpoint never mixes two views.\n */\nexport async function jettonBalance(\n ctx: TonContext,\n master: string,\n owner: string,\n tags: TonCallTags,\n): Promise<bigint> {\n const wallet = await jettonWalletAddress(ctx, master, owner, tags);\n const state = await tokenCall(() => ctx.api.account(wallet, tags));\n if (state.status === 'uninitialized') return 0n;\n const data = await tokenCall(() =>\n ctx.api.runGetMethod(wallet, 'get_wallet_data', [], tags, state.blockSeqno),\n );\n const first = data.stack[0];\n if (data.exitCode === 0 && first?.type === 'num' && first.value >= 0n) {\n return first.value;\n }\n throw assetError('the jetton wallet gives no balance');\n}\n\n/**\n * What the get-methods at masterchain block `block` say about a jetton wallet:\n * - `verified`: it names an owner and a master, and that master names it for that owner;\n * - `foreign`: it names an owner and a master that parse, and that master names another\n * wallet for that owner: positive evidence that it is not the master's;\n * - `unknown`: no evidence either way. `get_wallet_data` exited with `exitCode` (toncenter\n * answers -13 for an account it holds no state for at that block), or named no owner\n * or master that parses, or the master named no wallet.\n * Both get-methods run at `block`, one at which the wallet had already run a transaction\n * (a fact at its own height): an endpoint that lags behind it refuses\n * (retryable), where a read at its own head would take a wallet it has not seen yet for a\n * fake. Cached once verified under the quorum.\n */\nexport type JettonWalletFacts =\n | { readonly kind: 'verified'; readonly wallet: VerifiedJettonWallet }\n | { readonly kind: 'foreign' }\n | { readonly kind: 'unknown'; readonly exitCode?: number };\n\n/** toncenter's exit code for an account it holds no state for at the block asked. */\nexport const NO_STATE_EXIT = -13;\n\nexport async function jettonWalletFacts(\n ctx: TonContext,\n address: string,\n tags: TonCallTags,\n block: number,\n): Promise<JettonWalletFacts> {\n const known = ctx.verified.get(address);\n if (known) return { kind: 'verified', wallet: known };\n const data = await tokenCall(() =>\n ctx.api.runGetMethod(address, 'get_wallet_data', [], tags, block),\n );\n if (data.exitCode !== 0) return { kind: 'unknown', exitCode: data.exitCode };\n const ownerBoc = cellStack(data.stack[1]);\n const masterBoc = cellStack(data.stack[2]);\n const owner = ownerBoc ? addressFromBoc(ownerBoc) : null;\n const master = masterBoc ? addressFromBoc(masterBoc) : null;\n if (!owner || !master) return { kind: 'unknown' };\n let named: string;\n try {\n named = await jettonWalletAddress(ctx, master, owner, tags, block);\n } catch (error) {\n if (isCryptoAioError(error, 'ASSET_RESOLUTION')) return { kind: 'unknown' };\n throw error;\n }\n if (named !== address) return { kind: 'foreign' };\n const verified = { address, owner, master };\n if (tags.quorum !== undefined) ctx.verified.set(address, verified);\n return { kind: 'verified', wallet: verified };\n}\n\n/**\n * The lenient reading for history: a wallet the master names, else `undefined` (any\n * other contract; the transaction is then `partial`), so a fake contract never stalls a\n * page. One exception: \"no state at this block\" (exit -13) for the jetton\n * wallet whose own transaction this is (`ranHere`) contradicts the chain, which shows it\n * running there, so it is unavailable data (retryable), never a silent drop of a deposit.\n */\nexport async function verifyJettonWallet(\n ctx: TonContext,\n address: string,\n tags: TonCallTags,\n block: number,\n ranHere = false,\n memo?: PageMemo,\n): Promise<VerifiedJettonWallet | undefined> {\n const facts = await remembered(memo?.jettonWallets, address, () =>\n jettonWalletFacts(ctx, address, tags, block),\n );\n if (facts.kind === 'verified') return facts.wallet;\n if (ranHere && facts.kind === 'unknown' && facts.exitCode === NO_STATE_EXIT) {\n throw notYet('the jetton wallet state is not available at its block');\n }\n return undefined;\n}\n\n// ---- jetton metadata (TEP-64) -------------------------------------------------------------\n\n/**\n * The most cells one on-chain content value is read to (at most 127 bytes each,\n * about 8 KB), snake or chunked alike; past them it is unreadable. A symbol or name takes a\n * few cells: the bound keeps an author's long texts readable while bounding the work on\n * content anyone can deploy.\n */\nconst MAX_VALUE_CELLS = 64;\n/** The longest symbol and name kept: the indexer's limits (`api.ts`). */\nconst MAX_SYMBOL_LENGTH = 256;\nconst MAX_NAME_LENGTH = 256;\n\ntype Slice = ReturnType<Cell['beginParse']>;\n\n/**\n * TEP-64 snake data, read in one pass (`@ton/core`'s `loadStringTail` recurses\n * per cell and concatenates at each level, quadratic in the chain); undefined for a cell that\n * is not whole bytes with at most one ref, or a chain past `MAX_VALUE_CELLS`.\n */\nfunction snakeBytes(first: Slice): Buffer | undefined {\n let slice = first;\n const chunks: Buffer[] = [];\n for (let cells = 1; ; cells += 1) {\n const bits = slice.remainingBits;\n if (cells > MAX_VALUE_CELLS || bits % 8 !== 0 || slice.remainingRefs > 1) {\n return undefined;\n }\n if (bits > 0) chunks.push(slice.loadBuffer(bits / 8));\n if (slice.remainingRefs === 0) return Buffer.concat(chunks);\n slice = slice.loadRef().beginParse();\n }\n}\n\n/**\n * TEP-64 chunked data (`chunks#01 data:ChunkedData`, `chunked_data#_ data:(HashmapE 32\n * ^(SnakeData ~0))`): its chunks in index order, from 0 without a gap, each one cell of\n * whole bytes and no refs; at most `MAX_VALUE_CELLS` of them. Undefined otherwise.\n */\nfunction chunkedBytes(slice: Slice): Buffer | undefined {\n const dict = slice.loadDict(Dictionary.Keys.Uint(32), Dictionary.Values.Cell());\n if (dict.size > MAX_VALUE_CELLS) return undefined;\n const chunks: Buffer[] = [];\n for (let index = 0; index < dict.size; index += 1) {\n const chunk = dict.get(index)?.beginParse();\n if (!chunk || chunk.remainingRefs !== 0 || chunk.remainingBits % 8 !== 0) {\n return undefined;\n }\n chunks.push(chunk.loadBuffer(chunk.remainingBits / 8));\n }\n return Buffer.concat(chunks);\n}\n\n/**\n * A TEP-64 `ContentData` value as text: snake data (prefix 0x00, which some masters omit) or\n * chunked data (prefix 0x01), both bounded by `MAX_VALUE_CELLS`. Undefined when it does not\n * read.\n */\nfunction contentText(value: Cell): string | undefined {\n try {\n const slice = value.beginParse();\n const prefix = slice.remainingBits >= 8 ? slice.preloadUint(8) : undefined;\n if (prefix === 0 || prefix === 1) slice.skip(8);\n const bytes = prefix === 1 ? chunkedBytes(slice) : snakeBytes(slice);\n return bytes?.toString('utf8');\n } catch {\n return undefined;\n }\n}\n\n/** The on-chain content fields read (null: present but unreadable). */\ninterface OnchainFields {\n readonly decimals?: string | null;\n readonly symbol?: string | null;\n readonly name?: string | null;\n}\n\ninterface JettonContent {\n readonly fields: OnchainFields;\n /**\n * Whether an off-chain JSON holds the fields the chain does not (TEP-64: off-chain\n * content, or on-chain content with a `uri`); only the indexer has read it.\n */\n readonly linked: boolean;\n}\n\nconst contentKey = (name: string): Buffer => createHash('sha256').update(name).digest();\n\n/**\n * TEP-64: a parsed content cell's layout and fields. A layout or dictionary that does not\n * read is the token's own content (`ASSET_RESOLUTION`).\n */\nfunction contentOf(cell: Cell): JettonContent {\n try {\n const slice = cell.beginParse();\n const prefix = slice.loadUint(8);\n if (prefix === 1) return { fields: {}, linked: true };\n if (prefix !== 0) throw new Error('layout');\n const dict = slice.loadDict(Dictionary.Keys.Buffer(32), Dictionary.Values.Cell());\n const fields: {\n decimals?: string | null;\n symbol?: string | null;\n name?: string | null;\n } = {};\n for (const key of ['decimals', 'symbol', 'name'] as const) {\n const value = dict.get(contentKey(key));\n if (value) fields[key] = contentText(value) ?? null;\n }\n return { fields, linked: dict.has(contentKey('uri')) };\n } catch {\n throw assetError('the jetton content is unreadable');\n }\n}\n\n/** A content BOC as a cell; undefined when it does not parse as one root. */\nfunction contentCell(boc: string): Cell | undefined {\n try {\n const cells = Cell.fromBoc(Buffer.from(boc, 'base64'));\n return cells.length === 1 ? cells[0] : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Content cells parsed once per metadata read: a state-sized content takes about 2 s to\n * decode (`MAX_STATE_BOC_LENGTH`), and the quorum's endpoints usually serve the same text.\n */\nfunction contentCells(): (boc: string) => Cell | undefined {\n const parsed = new Map<string, Cell | undefined>();\n return (boc) => {\n if (!parsed.has(boc)) parsed.set(boc, contentCell(boc));\n return parsed.get(boc);\n };\n}\n\n/**\n * The facts endpoints must agree on for jetton metadata: the exit code and the content\n * cell's hash, never the rest of the answer (a total supply that moves between two reads)\n * nor the cell's serialization. It never throws: an answer that does not parse\n * is itself a fact, which the parse then refuses (retryable).\n */\nfunction jettonDataKey(cellOf: (boc: string) => Cell | undefined) {\n return (body: unknown): unknown => {\n try {\n const { exitCode, content } = jettonDataOf(body);\n if (!content) return { exitCode };\n if (content.kind === 'oversized') return { exitCode, content: 'oversized' };\n const cell = cellOf(content.boc);\n return { exitCode, content: cell ? cell.hash().toString('hex') : 'unparseable' };\n } catch {\n return 'malformed';\n }\n };\n}\n\n/**\n * A jetton's metadata, under the proof quorum. The master's content decides what it can:\n * - no master, or content beyond an account state's limits (every quorum endpoint agreed\n * on it), or a layout or value that does not read: `ASSET_RESOLUTION`;\n * - a content BOC that does not parse: the endpoint's fault, retryable;\n * - content wholly on chain: its own symbol, and its decimals or TEP-64's default of 9;\n * - otherwise the off-chain JSON fills in what the chain does not state, as the indexer\n * fetched it, and only those fields are judged: one the indexer holds but is not one\n * (agreed by the quorum) is the token's own `ASSET_RESOLUTION`. Metadata the indexer\n * does not have (no usable entry: never indexed, not valid, an unfetchable JSON; or a\n * JSON that states no decimals) is never a default: an index that lags or drops its\n * filter would otherwise cache 9 decimals for the container's life, and a 6-decimal\n * token would be mis-scaled 1,000× (fund safety over liveness).\n *\n * That absence is `unresolvable`, a non-retryable `PROVIDER_UNAVAILABLE`. Anyone can send\n * a junk jetton to a deposit address, and a retryable answer would fail every history\n * page and `getTransaction` that holds it, forever. Non-retryable, the core reports the\n * transfer with its raw base-unit amount and the asset unresolved and reads the rest of\n * the page. Its code is not `ASSET_RESOLUTION`, the one failure the core caches for the\n * container's life, so it is never cached: once the indexer has the metadata, the next\n * read resolves the token. A transfer of such a token fails the same way, before anything\n * is signed.\n * Known gap: that refusal is not retryable, even for a jetton the indexer has simply not\n * indexed yet; it records nothing, so the same call succeeds later. A retryable refusal\n * needs the core to report a transfer unresolved on a retryable failure too, or the\n * history stall comes back. A jetton whose metadata states no decimals stays unresolved:\n * the only way to use it is to register its decimals in a plugin's `assets`.\n */\nasync function jettonMetadata(ctx: TonContext, master: string): Promise<AssetMetadata> {\n const cellOf = contentCells();\n const data = await tokenCall(() =>\n ctx.api.jettonData(master, { ...METADATA, quorumKey: jettonDataKey(cellOf) }),\n );\n if (data.exitCode !== 0 || !data.content) {\n throw assetError('no jetton master at this address');\n }\n if (data.content.kind === 'oversized')\n throw assetError('the jetton content is unreadable');\n const cell = cellOf(data.content.boc);\n if (!cell) throw notYet('malformed jetton content answer');\n const { fields, linked } = contentOf(cell);\n if (fields.decimals === null) throw assetError('the jetton decimals are unreadable');\n if (fields.symbol === null) throw assetError('the jetton symbol is unreadable');\n let decimals: string | null | undefined = fields.decimals;\n let symbol: string | null | undefined = fields.symbol;\n let name = fields.name ?? undefined;\n if (!linked) {\n decimals ??= '9';\n } else if (decimals === undefined || symbol === undefined) {\n const info = await tokenCall(() => ctx.api.tokenInfo(master, METADATA));\n if (!info) throw unresolvable('the jetton metadata is not indexed');\n if (decimals === undefined) decimals = info.decimals;\n if (symbol === undefined) symbol = info.symbol;\n name ??= info.name;\n if (decimals === null) throw assetError('the jetton decimals are unreadable');\n if (symbol === null) throw assetError('the jetton symbol is unreadable');\n if (decimals === undefined)\n throw unresolvable('the jetton metadata states no decimals');\n }\n if (!/^\\d{1,3}$/.test(decimals) || Number(decimals) > 255) {\n throw assetError('the jetton decimals are unreadable');\n }\n if (!symbol) throw assetError('the jetton has no symbol');\n if (symbol.length > MAX_SYMBOL_LENGTH)\n throw assetError('the jetton symbol is unreadable');\n return {\n symbol,\n decimals: Number(decimals),\n ...(name && name.length <= MAX_NAME_LENGTH ? { name } : {}),\n };\n}\n\n/** The canonical master address of a jetton asset ref; `ASSET_RESOLUTION` otherwise. */\nexport function jettonMaster(ctx: TonContext, asset: AssetRef): string {\n if (asset === 'native' || asset.standard !== 'jetton') {\n throw assetError(`TON tokens use the 'jetton' standard`);\n }\n try {\n return ctx.codec.normalize(asset.contract).canonical;\n } catch {\n throw assetError('not a TON jetton master address');\n }\n}\n\nexport function toDriverBlock(header: BlockHeader): DriverBlock {\n return {\n height: BigInt(header.id.seqno),\n hash: header.id.rootHash,\n parentHash: header.prev[0]?.rootHash ?? '',\n timestamp: header.genUtime,\n };\n}\n\n// ---- transactions and Attempts -------------------------------------------------------------\n\n/**\n * The transaction a lookup id names (anyone's): by message hash, then by its own hash. An\n * external message can run more than once while it does not consume its seqno; the run\n * that consumed it is the one that took effect, so it is preferred.\n */\nasync function findTransaction(\n ctx: TonContext,\n id: string,\n tags: TonCallTags,\n): Promise<V3Transaction | null> {\n const hash = hashId(id);\n if (!hash) return null;\n const byMessage = await ctx.api.transactionsByMessage(hash, tags);\n const runs = byMessage.filter((tx) => tx.inMsg?.source === null);\n const found = runs.find(consumesSeqno) ?? runs[0] ?? byMessage[0];\n return found ?? ctx.api.transaction(hash, tags);\n}\n\n/**\n * Our own Attempt's wallet transaction, bound by account and a locally computed hash\n * (`isOwnAttempt`, never a first-result fallback). A run that did not consume its\n * seqno (a failed action phase, or a compute phase that failed before `commit()`) leaves the\n * same message valid, so it may run again; the run that consumed the seqno is preferred,\n * since only it decides.\n */\nexport async function findOwnAttempt(\n ctx: TonContext,\n ref: AttemptRef,\n from: string,\n tags: TonCallTags,\n): Promise<V3Transaction | undefined> {\n const hash = hashId(ref.id);\n if (!hash) return undefined;\n const own = (await ctx.api.transactionsByMessage(hash, tags)).filter((tx) =>\n isOwnAttempt(tx, from, hash),\n );\n return own.find(consumesSeqno) ?? own[0];\n}\n\n/**\n * Each jetton leg's wallets must be the master's own for the sender and the intended\n * recipient (the same master), as masterchain block `block` (the trace's last) records\n * them: a fake jetton wallet can \"accept\" a transfer that moves nothing. The verdict\n * unchanged when they are.\n *\n * Only positive evidence decides `failed`, never a missing\n * answer. The sender's jetton wallet is the one the proof quorum attested at build and the\n * trace shows both wallets running, so a leg that cannot be verified (no answer, exit -13\n * \"no state at this block\", nothing that parses), or a sender wallet that is not ours,\n * contradicts the chain: a retryable `PROVIDER_INCONSISTENT` (logged `JETTON_UNVERIFIED`),\n * never a terminal failure that a new key would pay again. `failed` only when the recipient\n * wallet answered, and it is not the master's for the intended recipient (another wallet\n * named, another owner, another master): the jettons went elsewhere.\n */\nexport async function confirmLegs(\n ctx: TonContext,\n verdict: Verdict,\n from: string,\n tags: TonCallTags,\n block: number,\n): Promise<Verdict> {\n if (verdict.kind !== 'success') return verdict;\n for (const leg of verdict.legs) {\n const sender = await jettonWalletFacts(ctx, leg.senderWallet, tags, block);\n const recipient = await jettonWalletFacts(ctx, leg.recipientWallet, tags, block);\n if (\n sender.kind !== 'verified' ||\n sender.wallet.owner !== from ||\n recipient.kind === 'unknown'\n ) {\n ctx.log.warn('a jetton wallet of the transfer could not be verified', {\n code: 'JETTON_UNVERIFIED',\n });\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n 'the jetton wallets of the transfer could not be verified at its block',\n { retryable: true },\n );\n }\n if (\n recipient.kind === 'foreign' ||\n recipient.wallet.owner !== leg.recipient ||\n recipient.wallet.master !== sender.wallet.master\n ) {\n return Object.freeze({ kind: 'failed', reason: REASONS.jettonUnverified });\n }\n }\n return verdict;\n}\n\n/** The newest masterchain block of a trace: every leg's wallet has run by then. */\nexport function traceBlock(root: V3Transaction, trace: V3Trace | null): number {\n return Math.max(root.mcSeqno, ...(trace?.transactions ?? []).map((tx) => tx.mcSeqno));\n}\n\n/**\n * What one history page reads once and uses for every transaction on it:\n * each masterchain block's header, and each jetton wallet's facts, read at the block of the\n * first (newest) transaction that needs them. The same answer reused, so it trusts nothing\n * more; a page reads from then on only what it has not read.\n */\nexport interface PageMemo {\n readonly headers: Map<number, Promise<BlockHeader>>;\n readonly jettonWallets: Map<string, Promise<JettonWalletFacts>>;\n}\n\nexport const pageMemo = (): PageMemo => ({\n headers: new Map(),\n jettonWallets: new Map(),\n});\n\n/** `read()` once per key in `memo` (none: read every time). */\nfunction remembered<K, V>(\n memo: Map<K, Promise<V>> | undefined,\n key: K,\n read: () => Promise<V>,\n): Promise<V> {\n if (!memo) return read();\n let pending = memo.get(key);\n if (!pending) {\n pending = read();\n memo.set(key, pending);\n }\n return pending;\n}\n\n/**\n * A transaction decoded with its jetton wallet verified at the transaction's own block\n * and its block's hash; `memo` shares both reads across one history page.\n */\nexport async function decodeWithJettons(\n ctx: TonContext,\n tx: V3Transaction,\n tags: TonCallTags,\n memo?: PageMemo,\n) {\n const candidate = jettonWalletToVerify(tx);\n // The arrival's own jetton wallet ran here; a notification's sender ran earlier.\n const jetton = candidate\n ? await verifyJettonWallet(\n ctx,\n candidate,\n tags,\n tx.mcSeqno,\n candidate === tx.account,\n memo,\n )\n : undefined;\n const header = await remembered(memo?.headers, tx.mcSeqno, () =>\n ctx.api.masterchainHeader(tx.mcSeqno, tags),\n );\n return decodeTransaction(tx, {\n blockHash: header.id.rootHash,\n ...(jetton ? { jetton } : {}),\n });\n}\n\n/** The highest masterchain seqno (a uint32). */\nconst MAX_BLOCK_SEQNO = 0xffff_ffffn;\n\nexport function createTonReader(ctx: TonContext): ChainReader {\n const { api } = ctx;\n return {\n getBalance: async (address, asset) => {\n const owner = ctx.codec.normalize(address).canonical;\n if (asset === 'native') return (await api.account(owner, READ)).balance;\n return jettonBalance(ctx, jettonMaster(ctx, asset), owner, READ);\n },\n getBlockHeight: async () => BigInt(await api.masterchainHead(MONITOR)),\n // Every masterchain block is final once it exists.\n getFinalizedHeight: async () => BigInt(await api.masterchainHead(MONITOR)),\n getBlock: async (ref) => {\n let seqno: number | null;\n let hash: string | undefined;\n if (typeof ref === 'bigint') {\n if (ref < 0n || ref > MAX_BLOCK_SEQNO) return null;\n seqno = Number(ref);\n } else {\n hash = hashId(ref);\n if (!hash) return null;\n seqno = await api.masterchainSeqnoOf(hash, READ);\n }\n if (seqno === null || seqno > (await api.masterchainHead(READ))) return null;\n const header = await api.masterchainHeader(seqno, READ);\n if (hash !== undefined && header.id.rootHash !== hash) {\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n 'the indexer and the liteserver name different blocks',\n { retryable: true },\n );\n }\n return toDriverBlock(header);\n },\n getTransaction: async (id) => {\n const tx = await findTransaction(ctx, id, READ);\n return tx ? decodeWithJettons(ctx, tx, READ) : null;\n },\n observe: async (ref, ordering, from): Promise<DriverTxObservation> => {\n const managed = ordering !== undefined && from !== undefined;\n const wallet = managed ? ctx.codec.normalize(from).canonical : undefined;\n // A managed Attempt is only ever our own wallet transaction (`isOwnAttempt`, before\n // any verdict), never a fallback.\n const tx =\n wallet !== undefined\n ? await findOwnAttempt(ctx, ref, wallet, MONITOR)\n : await findTransaction(ctx, ref.id, MONITOR);\n if (!tx) return { seen: 'none' };\n const header = await api.masterchainHeader(tx.mcSeqno, MONITOR);\n const seen = {\n seen: 'block' as const,\n txHash: tx.hash,\n blockHeight: BigInt(tx.mcSeqno),\n blockHash: header.id.rootHash,\n };\n // Anyone's transaction: its execution status as the chain reports it.\n if (wallet === undefined) return { ...seen, success: executed(tx) };\n // Our own Attempt: the verdict path.\n const trace = await api.trace(tx.hash, MONITOR);\n const verdict = await confirmLegs(\n ctx,\n attemptVerdict(tx, trace),\n wallet,\n MONITOR,\n traceBlock(tx, trace),\n );\n if (verdict.kind === 'pending') return seen;\n return verdict.kind === 'success'\n ? { ...seen, success: true }\n : { ...seen, success: false, reason: verdict.reason };\n },\n getTokenMetadata: async (ref: TokenRef) =>\n jettonMetadata(ctx, jettonMaster(ctx, ref)),\n normalizeTokenRef: (ref) => ({\n standard: 'jetton',\n contract: jettonMaster(ctx, ref),\n }),\n };\n}\n\n// ---- seqnos --------------------------------------------------------------------------------\n\n/** A live seqno read and the account state it was read at. */\ninterface LiveSeqno {\n readonly seqno: bigint;\n readonly state: AccountState;\n /** Whether the wallet is deployed at that block (it then has a public key there). */\n readonly deployed: boolean;\n}\n\n/**\n * A get-method's answer is the one run where it was asked: at `block` (the full id\n * when the caller has it, else the masterchain seqno), and on `state` when given, the\n * account's last transaction there. An endpoint that drops the block answers at its own\n * latest state, which decides nothing (a retryable `PROVIDER_INCONSISTENT`).\n */\nfunction assertRunAt(\n result: BoundRunResult,\n block: BlockId | number,\n state?: Pick<AccountState, 'lastLt' | 'lastHash'>,\n): void {\n const atBlock =\n typeof block === 'number'\n ? result.block.workchain === -1 &&\n result.block.shard === MASTERCHAIN_SHARD &&\n result.block.seqno === block\n : sameBlock(result.block, block);\n if (\n !atBlock ||\n (state !== undefined &&\n (result.lastTransaction.lt !== state.lastLt ||\n result.lastTransaction.hash !== state.lastHash))\n ) {\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n 'a get-method was answered at another state than the one asked',\n { retryable: true },\n );\n }\n}\n\nconst MAX_WALLET_SEQNO = 0xffff_ffffn;\n\n/** The wallet's seqno at the latest state: 0 while undeployed (its first message deploys it). */\nexport async function walletSeqno(\n ctx: TonContext,\n address: string,\n tags: TonCallTags,\n): Promise<bigint> {\n return (await liveSeqno(ctx, address, tags)).seqno;\n}\n\n/**\n * The seqno at the block the account state was read at, so both come from one view. A\n * frozen account is refused from its state alone, before any get-method: its deploy\n * `StateInit` would not revive it, and a message signed for it can never run.\n */\nasync function liveSeqno(\n ctx: TonContext,\n address: string,\n tags: TonCallTags,\n): Promise<LiveSeqno> {\n const state = await ctx.api.account(address, tags);\n if (state.status === 'uninitialized') {\n return { seqno: 0n, state, deployed: false };\n }\n if (state.status === 'frozen') {\n throw new ChainError('TX_REFUSED', 'the wallet account is frozen');\n }\n const result = await ctx.api.runGetMethodAt(\n address,\n 'seqno',\n [],\n tags,\n state.blockSeqno,\n );\n assertRunAt(result, state.block, state);\n const first = result.stack[0];\n if (\n result.exitCode !== 0 ||\n first?.type !== 'num' ||\n first.value < 0n ||\n first.value > MAX_WALLET_SEQNO\n ) {\n throw new ValidationError(\n 'INVALID_INTENT',\n 'the account is not a v4r2 or v5r1 wallet',\n );\n }\n return { seqno: first.value, state, deployed: true };\n}\n\n/**\n * The wallet's public key at masterchain block `block` (`get_public_key`), read once and\n * only when needed; undefined when the account has none there. The answer is bound to the\n * block asked and, when given, to the account state read there.\n */\nexport function publicKeyAt(\n ctx: TonContext,\n address: string,\n tags: TonCallTags,\n block: BlockId | number,\n state?: Pick<AccountState, 'lastLt' | 'lastHash'>,\n): () => Promise<Uint8Array | undefined> {\n let key: Promise<Uint8Array | undefined> | undefined;\n const seqno = typeof block === 'number' ? block : block.seqno;\n const read = async (): Promise<Uint8Array | undefined> => {\n const result = await ctx.api.runGetMethodAt(\n address,\n 'get_public_key',\n [],\n tags,\n seqno,\n );\n assertRunAt(result, block, state);\n const first = result.stack[0];\n if (result.exitCode !== 0 || first?.type !== 'num') return undefined;\n if (first.value < 0n || first.value >= 1n << 256n) return undefined;\n return Buffer.from(first.value.toString(16).padStart(64, '0'), 'hex');\n };\n return () => (key ??= read());\n}\n\n/**\n * The wallet request `tx` proves `from` consumed its seqno,\n * else null. Every request must be the wallet's own, signed by its key (`requestIsOwn`): a\n * lone lying indexer can make up an external one, and anyone can post a relayed W5 body for\n * a small fee (a v5r1 wallet ignores a forged one). And it must have consumed the seqno: an\n * external request only when `consumesSeqno` holds (its action phase succeeded, or W5\n * committed and then threw 137), a relayed one only when the wallet ran it to the end\n * (`ran`: with no `commit()` there, a failed action phase rolls the seqno back). A foreign\n * request signed with the same key whose action phase failed consumed nothing. `publicKey`\n * gives the wallet's key for `tx`; it is read only for a request that passed the rest.\n */\nexport async function provenRequest(\n ctx: TonContext,\n tx: V3Transaction,\n from: string,\n publicKey: (tx: V3Transaction) => Promise<Uint8Array | undefined>,\n): Promise<WalletRequest | null> {\n const inMsg = tx.inMsg;\n if (!inMsg || tx.account !== from) return null;\n const body = messageBody(inMsg);\n const request = body ? decodeWalletRequest(body) : null;\n if (!body || !request) return null;\n if (inMsg.source === null) {\n if (request.auth !== 'external' || !consumesSeqno(tx)) return null;\n } else if (request.auth !== 'internal' || !ran(tx)) {\n return null;\n }\n const key = await publicKey(tx);\n return key && requestIsOwn(from, body, key, ctx.config.globalId) ? request : null;\n}\n\n/** The history page the seqno floor reads, and how many pages before it gives up. */\nconst FLOOR_PAGE = 64;\nconst FLOOR_PAGES = 4;\n\n/**\n * The seqno after the newest wallet request the indexer has. Once the previous transfer\n * is `included`, the core hands out the next seqno; a lagging liteserver read could still\n * show the consumed one, and a message signed for it could only end `replaced`. Only a\n * proven request counts, and only one newer than the live read: the live read\n * already covers the rest. The history is paged on the indexer's own pages (a page\n * whose newest transactions are not final yet still leads to the older ones) until it\n * reaches the live read's block; more than `FLOOR_PAGES` pages since then decides nothing\n * (retryable) rather than guess, and so does a request dated after its own lifetime.\n */\nasync function indexedSeqnoFloor(\n ctx: TonContext,\n address: string,\n live: LiveSeqno,\n tags: TonCallTags,\n): Promise<bigint> {\n const liveKey = live.deployed\n ? publicKeyAt(ctx, address, tags, live.state.block, live.state)\n : async () => undefined;\n // An undeployed wallet at the live read has no key there: read it at the evidence's own\n // block, which a lagging endpoint refuses (retryable), so nothing is guessed meanwhile.\n const key = async (tx: V3Transaction) =>\n (await liveKey()) ?? publicKeyAt(ctx, address, tags, tx.mcSeqno)();\n let endLt: bigint | undefined;\n for (let page = 0; page < FLOOR_PAGES; page += 1) {\n const { transactions, next } = await ctx.api.accountTransactionsPage(\n address,\n { limit: FLOOR_PAGE, ...(endLt !== undefined ? { endLt } : {}) },\n tags,\n );\n for (const tx of transactions) {\n if (tx.mcSeqno <= live.state.blockSeqno) return 0n; // newest first: the rest is older still\n const request = await provenRequest(ctx, tx, address, key);\n if (!request) continue;\n // A request that ran after its own lifetime is a record the chain\n // cannot produce (the wallet refuses it), so it decides nothing, as in the proofs.\n if (request.validUntil <= tx.now) {\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n 'the seqno consumer ran after its request expired',\n { retryable: true },\n );\n }\n return BigInt(request.seqno) + 1n;\n }\n if (next === undefined) return 0n;\n endLt = next;\n }\n throw notYet('the wallet history since the live seqno read is too long to check');\n}\n\nexport function createTonSequence(ctx: TonContext): SequenceSource {\n return {\n pending: async (address) => {\n const wallet = ctx.codec.normalize(address).canonical;\n const live = await liveSeqno(ctx, wallet, MONITOR);\n const floor = await indexedSeqnoFloor(ctx, wallet, live, MONITOR);\n return live.seqno > floor ? live.seqno : floor;\n },\n latest: async (address) =>\n walletSeqno(ctx, ctx.codec.normalize(address).canonical, MONITOR),\n };\n}\n\nexport function createTonExt(ctx: TonContext): TonExt {\n return {\n ton: {\n getSeqno: async (address) =>\n walletSeqno(ctx, ctx.codec.normalize(address).canonical, READ),\n // A caller sends jettons to it, so the proof quorum attests it, and the attested\n // answer is kept.\n jettonWallet: async (owner, master) =>\n jettonWalletAddress(\n ctx,\n jettonMaster(ctx, { standard: 'jetton', contract: master }),\n ctx.codec.normalize(owner).canonical,\n PROOF,\n ),\n },\n };\n}\n"]}
1
+ {"version":3,"file":"reader.js","sourceRoot":"","sources":["../../../src/adapters/ton/reader.ts"],"names":[],"mappings":";;;AA4IA,oBAGC;AAED,4CAqBC;AAgFD,kDA2BC;AAMD,sCAiBC;AAuBD,8CA4BC;AASD,gDAgBC;AAuOD,oCASC;AAED,sCAOC;AA6BD,wCAYC;AAiBD,kCAuCC;AAGD,gCAEC;AAoBD,sCAwBC;AAOD,4BAQC;AAOD,wBAOC;AAkGD,sCAuDC;AAqCD,8CAyBC;AAKD,0CAyFC;AA8CD,kCAMC;AA+CD,kCAwBC;AAaD,sCAkBC;AAyDD,8CAWC;AAED,oCAgBC;AAj0CD;;;;;GAKG;AACH,oCAOmB;AACnB,6CAAyC;AASzC,mDAMiC;AAMjC,uCAAkD;AAClD,+BAkBe;AACf,qCAMkB;AAClB,yCAOoB;AAEpB,mCAQiB;AAEjB,uCAAyF;AAmDzF,0FAA0F;AAC7E,QAAA,UAAU,GAAG,KAAK,CAAC;AAChC,sFAAsF;AACzE,QAAA,cAAc,GAAG,MAAM,CAAC;AACrC,4FAA4F;AAC/E,QAAA,cAAc,GAAG,KAAK,CAAC;AAEpC,gFAAgF;AAChF,SAAgB,IAAI,CAAO,IAAe,EAAE,GAAM,EAAE,KAAQ,EAAE,IAAY;IACxE,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACrB,IAAI,IAAI,CAAC,IAAI,GAAG,IAAI;QAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAU,CAAC,CAAC;AACnE,CAAC;AAED,SAAgB,gBAAgB,CAAC,IAOhC;IACC,MAAM,KAAK,GAAG,IAAA,+BAAqB,EAAC;QAClC,O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AS,EACpC,WAAK,CACN;SACJ;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * TON addresses, reads, seqnos, jetton lookups and the `ext.ton` API. Every call carries the\n * tags of the `ChainDriver` contract table (`src/core/driver/types.ts`): `read` for point\n * queries, `monitor` for heights, observations and seqnos. Jetton metadata, which the\n * core caches for the container's life, is a `read` under the proof quorum.\n */\nimport {\n Cell,\n Dictionary,\n loadMessage,\n loadTransaction,\n type DictionaryValue,\n type Transaction,\n} from '@ton/core';\nimport { createHash } from 'node:crypto';\nimport type {\n AddressCodec,\n ChainReader,\n DriverBlock,\n DriverTxObservation,\n SequenceSource,\n WalletOptions,\n} from '../../core/driver/types';\nimport {\n ChainError,\n ProviderError,\n ValidationError,\n isCryptoAioError,\n withContext,\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 { AttemptRef } from '../../core/model/transaction';\nimport type { Clock } from '../../core/util/clock';\nimport { createTonAddressCodec } from './address';\nimport {\n MASTERCHAIN_SHARD,\n MONITOR,\n PROOF,\n READ,\n jettonDataOf,\n runResultOf,\n sameBlock,\n type AccountState,\n type BlockHeader,\n type BlockId,\n type BoundRunResult,\n type RawTransaction,\n type RunResult,\n type TonApi,\n type TransactionId,\n type V3Trace,\n type V3Transaction,\n} from './api';\nimport {\n decodeTransaction,\n executed,\n jettonWalletToVerify,\n ran,\n type VerifiedJettonWallet,\n} from './decode';\nimport {\n addressArgument,\n addressFromBoc,\n decodeJettonInternalTransfer,\n decodeWalletRequest,\n messageBody,\n type WalletRequest,\n} from './messages';\nimport type { TonNetworkConfig } from './network';\nimport {\n REASONS,\n attemptVerdict,\n consumesSeqno,\n isOwnAttempt,\n type BounceEvidence,\n type ChainTxId,\n type Verdict,\n} from './trace';\nimport type { TonCallTags, TonExt } from './types';\nimport { externalHashOf, requestIsOwn, resolveIdentity, walletAddress } from './wallets';\n\n/**\n * What every TON port is built from. Drivers are shared: the caches hold only immutable\n * chain data, values the proof quorum attested or transactions bound to their own hash\n * (`chainTxs`); a single `read` or `monitor` answer is used once and never cached. The one\n * record of anything else is `assembled`, for the replay guard: what this driver itself\n * built and sent.\n */\nexport interface TonContext {\n readonly api: TonApi;\n readonly chain: ChainInfo;\n readonly network: NetworkInfo;\n readonly config: TonNetworkConfig;\n readonly log: Logger;\n readonly clock: Clock;\n readonly codec: AddressCodec;\n /** `master|owner` → the jetton wallet the master names, as the quorum attested it. */\n readonly jettonWallets: Map<string, string>;\n /** jetton wallet → its owner and master, verified under the quorum. */\n readonly verified: Map<string, VerifiedJettonWallet>;\n /**\n * Transactions authenticated under the proof quorum (the chain walk's wallet\n * transactions, a bounce's deliveries), by `lt:hash`. A transaction is immutable and its\n * cell hashes to its id, so a kept one is as good as one fetched again; each walk fetches\n * only what it has not seen (bounded, `CHAIN_MEMO`).\n */\n readonly chainTxs: Map<string, Transaction>;\n /**\n * The external messages this driver assembled, by TEP-467 hash: the build's recorded\n * chain time and whether they were ever handed to a send (bounded, `ASSEMBLED_MEMO`).\n * Known gap: the `Broadcaster` port carries only the bytes, never the Attempt's\n * ordering, so the replay guard keeps this memo; bytes this driver did not assemble, or\n * has evicted, are guarded with the widest window (one day).\n */\n readonly assembled: Map<string, AssembledMessage>;\n}\n\n/** What `assemble` recorded about a message it made. */\nexport interface AssembledMessage {\n /** `TonSeqnoOrdering.validFrom`, as the ordering bound to the signed bytes holds it. */\n readonly validFrom: number;\n /**\n * The driver's clock when `assemble` ran, in ms: a first send skips the replay guard only\n * within `FIRST_SEND_MS` of it.\n */\n readonly assembledAt: number;\n /** Set before the first send; never cleared. */\n sent: boolean;\n}\n\n/** The most authenticated transactions a driver keeps (each at most `MEMO_TX_LENGTH`). */\nexport const CHAIN_MEMO = 4_096;\n/** The longest transaction BOC text kept: a wallet transaction takes about 1-2 KB. */\nexport const MEMO_TX_LENGTH = 16_384;\n/** The most assembled messages a driver remembers; an evicted one is guarded as foreign. */\nexport const ASSEMBLED_MEMO = 4_096;\n\n/** Keeps `value` in a bounded memo, dropping the oldest entry beyond `size`. */\nexport function keep<K, V>(memo: Map<K, V>, key: K, value: V, size: number): void {\n memo.set(key, value);\n if (memo.size > size) memo.delete(memo.keys().next().value as K);\n}\n\nexport function createTonContext(args: {\n readonly api: TonApi;\n readonly chain: ChainInfo;\n readonly network: NetworkInfo;\n readonly config: TonNetworkConfig;\n readonly log: Logger;\n readonly clock: Clock;\n}): TonContext {\n const codec = createTonAddressCodec({\n testnet: args.config.testnet,\n fromPublicKey: (publicKey: Uint8Array, wallet?: WalletOptions) =>\n walletAddress(resolveIdentity(wallet, args.config.globalId), publicKey),\n });\n return {\n ...args,\n codec,\n jettonWallets: new Map(),\n verified: new Map(),\n chainTxs: new Map(),\n assembled: new Map(),\n };\n}\n\nconst assetError = (reason: string) => new ValidationError('ASSET_RESOLUTION', reason);\n\nconst notYet = (reason: string) =>\n new ProviderError('PROVIDER_UNAVAILABLE', reason, { retryable: true });\n\n/**\n * Metadata the indexer does not have, for a token read anywhere (`jettonMetadata`):\n * non-retryable, so the core reports a transfer of it unresolved instead of failing the\n * read, and not `ASSET_RESOLUTION`, so the core never caches it.\n */\nconst unresolvable = (reason: string) =>\n new ProviderError('PROVIDER_UNAVAILABLE', reason, { retryable: false });\n\n/**\n * The core caches a token's metadata,\n * and its \"no such token\", for the container's life, so one lagging or buggy endpoint must\n * never decide it. Balances stay plain reads.\n */\nconst METADATA: TonCallTags = { ...READ, quorum: 'proof' };\n\n/**\n * A token's own failure (a missing account, a TVM exit code, content that does\n * not parse) is `ASSET_RESOLUTION`; `PROVIDER_MISCONFIGURED` and already retryable errors\n * propagate unchanged; any other definitive node answer is made retryable.\n */\nfunction asRetryable(error: unknown): unknown {\n if (\n isCryptoAioError(error) &&\n error.category === 'provider' &&\n !error.retryable &&\n error.code !== 'PROVIDER_MISCONFIGURED'\n ) {\n return withContext(error, {}, { retryable: true });\n }\n return error;\n}\n\nasync function tokenCall<T>(work: () => Promise<T>): Promise<T> {\n try {\n return await work();\n } catch (error) {\n throw asRetryable(error);\n }\n}\n\nconst cellStack = (entry: RunResult['stack'][number] | undefined): string | undefined =>\n entry?.type === 'cell' ? entry.boc : undefined;\n\n/** A lookup id (a 32-byte hash in hex, either case) in lower case; undefined otherwise. */\nconst hashId = (id: string): string | undefined =>\n typeof id === 'string' && /^[0-9a-fA-F]{64}$/.test(id) ? id.toLowerCase() : undefined;\n\n/** The wallet address a `get_wallet_address` answer names; null when it names none. */\nfunction namedWallet(result: RunResult): string | null {\n const boc = result.exitCode === 0 ? cellStack(result.stack[0]) : undefined;\n return boc ? addressFromBoc(boc) : null;\n}\n\n/**\n * What endpoints must agree on for `get_wallet_address`: the exit code and the\n * address it names, never the slice's serialization. It never throws: an answer that does\n * not parse is itself a fact, which the parse then refuses (retryable).\n */\nfunction walletAddressKey(body: unknown): unknown {\n try {\n const result = runResultOf(body);\n return { exitCode: result.exitCode, wallet: namedWallet(result) };\n } catch {\n return 'malformed';\n }\n}\n\n/**\n * The jetton wallet `master` assigns to `owner` (`get_wallet_address`), at masterchain\n * block `block` when given. Cached only when the proof quorum attested it: the builder\n * sends jettons to it and the verdict checks it, so one endpoint's answer must never stick.\n * Under a quorum the endpoints agree on the address itself (`walletAddressKey`).\n */\nexport async function jettonWalletAddress(\n ctx: TonContext,\n master: string,\n owner: string,\n tags: TonCallTags,\n block?: number,\n): Promise<string> {\n const key = `${master}|${owner}`;\n const cached = ctx.jettonWallets.get(key);\n if (cached) return cached;\n const keyed =\n tags.quorum !== undefined && tags.quorumKey === undefined\n ? { ...tags, quorumKey: walletAddressKey }\n : tags;\n const result = await tokenCall(() =>\n ctx.api.runGetMethod(\n master,\n 'get_wallet_address',\n [['tvm.Slice', addressArgument(owner)]],\n keyed,\n block,\n ),\n );\n const address = namedWallet(result);\n if (!address) throw assetError('the jetton master gives no wallet address');\n if (tags.quorum !== undefined) ctx.jettonWallets.set(key, address);\n return address;\n}\n\n/**\n * `owner`'s jetton balance; 0 while its jetton wallet is not deployed. The state and the\n * balance are read at one block, so a load-balanced endpoint never mixes two views.\n */\nexport async function jettonBalance(\n ctx: TonContext,\n master: string,\n owner: string,\n tags: TonCallTags,\n): Promise<bigint> {\n const wallet = await jettonWalletAddress(ctx, master, owner, tags);\n const state = await tokenCall(() => ctx.api.account(wallet, tags));\n if (state.status === 'uninitialized') return 0n;\n const data = await tokenCall(() =>\n ctx.api.runGetMethod(wallet, 'get_wallet_data', [], tags, state.blockSeqno),\n );\n const first = data.stack[0];\n if (data.exitCode === 0 && first?.type === 'num' && first.value >= 0n) {\n return first.value;\n }\n throw assetError('the jetton wallet gives no balance');\n}\n\n/**\n * What the get-methods at masterchain block `block` say about a jetton wallet:\n * - `verified`: it names an owner and a master, and that master names it for that owner;\n * - `foreign`: it names an owner and a master that parse, and that master names another\n * wallet for that owner: positive evidence that it is not the master's;\n * - `unknown`: no evidence either way. `get_wallet_data` exited with `exitCode` (toncenter\n * answers -13 for an account it holds no state for at that block), or named no owner\n * or master that parses, or the master named no wallet.\n * Both get-methods run at `block`, one at which the wallet had already run a transaction\n * (a fact at its own height): an endpoint that lags behind it refuses\n * (retryable), where a read at its own head would take a wallet it has not seen yet for a\n * fake. Cached once verified under the quorum.\n */\nexport type JettonWalletFacts =\n | { readonly kind: 'verified'; readonly wallet: VerifiedJettonWallet }\n | { readonly kind: 'foreign' }\n | { readonly kind: 'unknown'; readonly exitCode?: number };\n\n/** toncenter's exit code for an account it holds no state for at the block asked. */\nexport const NO_STATE_EXIT = -13;\n\nexport async function jettonWalletFacts(\n ctx: TonContext,\n address: string,\n tags: TonCallTags,\n block: number,\n): Promise<JettonWalletFacts> {\n const known = ctx.verified.get(address);\n if (known) return { kind: 'verified', wallet: known };\n const data = await tokenCall(() =>\n ctx.api.runGetMethod(address, 'get_wallet_data', [], tags, block),\n );\n if (data.exitCode !== 0) return { kind: 'unknown', exitCode: data.exitCode };\n const ownerBoc = cellStack(data.stack[1]);\n const masterBoc = cellStack(data.stack[2]);\n const owner = ownerBoc ? addressFromBoc(ownerBoc) : null;\n const master = masterBoc ? addressFromBoc(masterBoc) : null;\n if (!owner || !master) return { kind: 'unknown' };\n let named: string;\n try {\n named = await jettonWalletAddress(ctx, master, owner, tags, block);\n } catch (error) {\n if (isCryptoAioError(error, 'ASSET_RESOLUTION')) return { kind: 'unknown' };\n throw error;\n }\n if (named !== address) return { kind: 'foreign' };\n const verified = { address, owner, master };\n if (tags.quorum !== undefined) ctx.verified.set(address, verified);\n return { kind: 'verified', wallet: verified };\n}\n\n/**\n * The lenient reading for history: a wallet the master names, else `undefined` (any\n * other contract; the transaction is then `partial`), so a fake contract never stalls a\n * page. One exception: \"no state at this block\" (exit -13) for the jetton\n * wallet whose own transaction this is (`ranHere`) contradicts the chain, which shows it\n * running there, so it is unavailable data (retryable), never a silent drop of a deposit.\n */\nexport async function verifyJettonWallet(\n ctx: TonContext,\n address: string,\n tags: TonCallTags,\n block: number,\n ranHere = false,\n memo?: PageMemo,\n): Promise<VerifiedJettonWallet | undefined> {\n const facts = await remembered(memo?.jettonWallets, address, () =>\n jettonWalletFacts(ctx, address, tags, block),\n );\n if (facts.kind === 'verified') return facts.wallet;\n if (ranHere && facts.kind === 'unknown' && facts.exitCode === NO_STATE_EXIT) {\n throw notYet('the jetton wallet state is not available at its block');\n }\n return undefined;\n}\n\n// ---- jetton metadata (TEP-64) -------------------------------------------------------------\n\n/**\n * The most cells one on-chain content value is read to (at most 127 bytes each,\n * about 8 KB), snake or chunked alike; past them it is unreadable. A symbol or name takes a\n * few cells: the bound keeps an author's long texts readable while bounding the work on\n * content anyone can deploy.\n */\nconst MAX_VALUE_CELLS = 64;\n/** The longest symbol and name kept: the indexer's limits (`api.ts`). */\nconst MAX_SYMBOL_LENGTH = 256;\nconst MAX_NAME_LENGTH = 256;\n\ntype Slice = ReturnType<Cell['beginParse']>;\n\n/**\n * TEP-64 snake data, read in one pass (`@ton/core`'s `loadStringTail` recurses\n * per cell and concatenates at each level, quadratic in the chain); undefined for a cell that\n * is not whole bytes with at most one ref, or a chain past `MAX_VALUE_CELLS`.\n */\nfunction snakeBytes(first: Slice): Buffer | undefined {\n let slice = first;\n const chunks: Buffer[] = [];\n for (let cells = 1; ; cells += 1) {\n const bits = slice.remainingBits;\n if (cells > MAX_VALUE_CELLS || bits % 8 !== 0 || slice.remainingRefs > 1) {\n return undefined;\n }\n if (bits > 0) chunks.push(slice.loadBuffer(bits / 8));\n if (slice.remainingRefs === 0) return Buffer.concat(chunks);\n slice = slice.loadRef().beginParse();\n }\n}\n\n/**\n * TEP-64 chunked data (`chunks#01 data:ChunkedData`, `chunked_data#_ data:(HashmapE 32\n * ^(SnakeData ~0))`): its chunks in index order, from 0 without a gap, each one cell of\n * whole bytes and no refs; at most `MAX_VALUE_CELLS` of them. Undefined otherwise.\n */\nfunction chunkedBytes(slice: Slice): Buffer | undefined {\n const dict = slice.loadDict(Dictionary.Keys.Uint(32), Dictionary.Values.Cell());\n if (dict.size > MAX_VALUE_CELLS) return undefined;\n const chunks: Buffer[] = [];\n for (let index = 0; index < dict.size; index += 1) {\n const chunk = dict.get(index)?.beginParse();\n if (!chunk || chunk.remainingRefs !== 0 || chunk.remainingBits % 8 !== 0) {\n return undefined;\n }\n chunks.push(chunk.loadBuffer(chunk.remainingBits / 8));\n }\n return Buffer.concat(chunks);\n}\n\n/**\n * A TEP-64 `ContentData` value as text: snake data (prefix 0x00, which some masters omit) or\n * chunked data (prefix 0x01), both bounded by `MAX_VALUE_CELLS`. Undefined when it does not\n * read.\n */\nfunction contentText(value: Cell): string | undefined {\n try {\n const slice = value.beginParse();\n const prefix = slice.remainingBits >= 8 ? slice.preloadUint(8) : undefined;\n if (prefix === 0 || prefix === 1) slice.skip(8);\n const bytes = prefix === 1 ? chunkedBytes(slice) : snakeBytes(slice);\n return bytes?.toString('utf8');\n } catch {\n return undefined;\n }\n}\n\n/** The on-chain content fields read (null: present but unreadable). */\ninterface OnchainFields {\n readonly decimals?: string | null;\n readonly symbol?: string | null;\n readonly name?: string | null;\n}\n\ninterface JettonContent {\n readonly fields: OnchainFields;\n /**\n * Whether an off-chain JSON holds the fields the chain does not (TEP-64: off-chain\n * content, or on-chain content with a `uri`); only the indexer has read it.\n */\n readonly linked: boolean;\n}\n\nconst contentKey = (name: string): Buffer => createHash('sha256').update(name).digest();\n\n/**\n * TEP-64: a parsed content cell's layout and fields. A layout or dictionary that does not\n * read is the token's own content (`ASSET_RESOLUTION`).\n */\nfunction contentOf(cell: Cell): JettonContent {\n try {\n const slice = cell.beginParse();\n const prefix = slice.loadUint(8);\n if (prefix === 1) return { fields: {}, linked: true };\n if (prefix !== 0) throw new Error('layout');\n const dict = slice.loadDict(Dictionary.Keys.Buffer(32), Dictionary.Values.Cell());\n const fields: {\n decimals?: string | null;\n symbol?: string | null;\n name?: string | null;\n } = {};\n for (const key of ['decimals', 'symbol', 'name'] as const) {\n const value = dict.get(contentKey(key));\n if (value) fields[key] = contentText(value) ?? null;\n }\n return { fields, linked: dict.has(contentKey('uri')) };\n } catch {\n throw assetError('the jetton content is unreadable');\n }\n}\n\n/** A content BOC as a cell; undefined when it does not parse as one root. */\nfunction contentCell(boc: string): Cell | undefined {\n try {\n const cells = Cell.fromBoc(Buffer.from(boc, 'base64'));\n return cells.length === 1 ? cells[0] : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Content cells parsed once per metadata read: a state-sized content takes about 2 s to\n * decode (`MAX_STATE_BOC_LENGTH`), and the quorum's endpoints usually serve the same text.\n */\nfunction contentCells(): (boc: string) => Cell | undefined {\n const parsed = new Map<string, Cell | undefined>();\n return (boc) => {\n if (!parsed.has(boc)) parsed.set(boc, contentCell(boc));\n return parsed.get(boc);\n };\n}\n\n/**\n * The facts endpoints must agree on for jetton metadata: the exit code and the content\n * cell's hash, never the rest of the answer (a total supply that moves between two reads)\n * nor the cell's serialization. It never throws: an answer that does not parse\n * is itself a fact, which the parse then refuses (retryable).\n */\nfunction jettonDataKey(cellOf: (boc: string) => Cell | undefined) {\n return (body: unknown): unknown => {\n try {\n const { exitCode, content } = jettonDataOf(body);\n if (!content) return { exitCode };\n if (content.kind === 'oversized') return { exitCode, content: 'oversized' };\n const cell = cellOf(content.boc);\n return { exitCode, content: cell ? cell.hash().toString('hex') : 'unparseable' };\n } catch {\n return 'malformed';\n }\n };\n}\n\n/**\n * A jetton's metadata, under the proof quorum. The master's content decides what it can:\n * - no master, or content beyond an account state's limits (every quorum endpoint agreed\n * on it), or a layout or value that does not read: `ASSET_RESOLUTION`;\n * - a content BOC that does not parse: the endpoint's fault, retryable;\n * - content wholly on chain: its own symbol, and its decimals or TEP-64's default of 9;\n * - otherwise the off-chain JSON fills in what the chain does not state, as the indexer\n * fetched it, and only those fields are judged: one the indexer holds but is not one\n * (agreed by the quorum) is the token's own `ASSET_RESOLUTION`. Metadata the indexer\n * does not have (no usable entry: never indexed, not valid, an unfetchable JSON; or a\n * JSON that states no decimals) is never a default: an index that lags or drops its\n * filter would otherwise cache 9 decimals for the container's life, and a 6-decimal\n * token would be mis-scaled 1,000× (fund safety over liveness).\n *\n * That absence is `unresolvable`, a non-retryable `PROVIDER_UNAVAILABLE`. Anyone can send\n * a junk jetton to a deposit address, and a retryable answer would fail every history\n * page and `getTransaction` that holds it, forever. Non-retryable, the core reports the\n * transfer with its raw base-unit amount and the asset unresolved and reads the rest of\n * the page. Its code is not `ASSET_RESOLUTION`, the one failure the core caches for the\n * container's life, so it is never cached: once the indexer has the metadata, the next\n * read resolves the token. A transfer of such a token fails the same way, before anything\n * is signed.\n * Known gap: that refusal is not retryable, even for a jetton the indexer has simply not\n * indexed yet; it records nothing, so the same call succeeds later. A retryable refusal\n * needs the core to report a transfer unresolved on a retryable failure too, or the\n * history stall comes back. A jetton whose metadata states no decimals stays unresolved:\n * the only way to use it is to register its decimals in a plugin's `assets`.\n */\nasync function jettonMetadata(ctx: TonContext, master: string): Promise<AssetMetadata> {\n const cellOf = contentCells();\n const data = await tokenCall(() =>\n ctx.api.jettonData(master, { ...METADATA, quorumKey: jettonDataKey(cellOf) }),\n );\n if (data.exitCode !== 0 || !data.content) {\n throw assetError('no jetton master at this address');\n }\n if (data.content.kind === 'oversized')\n throw assetError('the jetton content is unreadable');\n const cell = cellOf(data.content.boc);\n if (!cell) throw notYet('malformed jetton content answer');\n const { fields, linked } = contentOf(cell);\n if (fields.decimals === null) throw assetError('the jetton decimals are unreadable');\n if (fields.symbol === null) throw assetError('the jetton symbol is unreadable');\n let decimals: string | null | undefined = fields.decimals;\n let symbol: string | null | undefined = fields.symbol;\n let name = fields.name ?? undefined;\n if (!linked) {\n decimals ??= '9';\n } else if (decimals === undefined || symbol === undefined) {\n const info = await tokenCall(() => ctx.api.tokenInfo(master, METADATA));\n if (!info) throw unresolvable('the jetton metadata is not indexed');\n if (decimals === undefined) decimals = info.decimals;\n if (symbol === undefined) symbol = info.symbol;\n name ??= info.name;\n if (decimals === null) throw assetError('the jetton decimals are unreadable');\n if (symbol === null) throw assetError('the jetton symbol is unreadable');\n if (decimals === undefined)\n throw unresolvable('the jetton metadata states no decimals');\n }\n if (!/^\\d{1,3}$/.test(decimals) || Number(decimals) > 255) {\n throw assetError('the jetton decimals are unreadable');\n }\n if (!symbol) throw assetError('the jetton has no symbol');\n if (symbol.length > MAX_SYMBOL_LENGTH)\n throw assetError('the jetton symbol is unreadable');\n return {\n symbol,\n decimals: Number(decimals),\n ...(name && name.length <= MAX_NAME_LENGTH ? { name } : {}),\n };\n}\n\n/** The canonical master address of a jetton asset ref; `ASSET_RESOLUTION` otherwise. */\nexport function jettonMaster(ctx: TonContext, asset: AssetRef): string {\n if (asset === 'native' || asset.standard !== 'jetton') {\n throw assetError(`TON tokens use the 'jetton' standard`);\n }\n try {\n return ctx.codec.normalize(asset.contract).canonical;\n } catch {\n throw assetError('not a TON jetton master address');\n }\n}\n\nexport function toDriverBlock(header: BlockHeader): DriverBlock {\n return {\n height: BigInt(header.id.seqno),\n hash: header.id.rootHash,\n parentHash: header.prev[0]?.rootHash ?? '',\n timestamp: header.genUtime,\n };\n}\n\n// ---- transactions and Attempts -------------------------------------------------------------\n\n/**\n * The transaction a lookup id names (anyone's): by message hash, then by its own hash. An\n * external message can run more than once while it does not consume its seqno; the run\n * that consumed it is the one that took effect, so it is preferred.\n */\nasync function findTransaction(\n ctx: TonContext,\n id: string,\n tags: TonCallTags,\n): Promise<V3Transaction | null> {\n const hash = hashId(id);\n if (!hash) return null;\n const byMessage = await ctx.api.transactionsByMessage(hash, tags);\n const runs = byMessage.filter((tx) => tx.inMsg?.source === null);\n const found = runs.find(consumesSeqno) ?? runs[0] ?? byMessage[0];\n return found ?? ctx.api.transaction(hash, tags);\n}\n\n/**\n * Our own Attempt's wallet transaction, bound by account and a locally computed hash\n * (`isOwnAttempt`, never a first-result fallback). A run that did not consume its\n * seqno (a failed action phase, or a compute phase that failed before `commit()`) leaves the\n * same message valid, so it may run again; the run that consumed the seqno is preferred,\n * since only it decides.\n */\nexport async function findOwnAttempt(\n ctx: TonContext,\n ref: AttemptRef,\n from: string,\n tags: TonCallTags,\n): Promise<V3Transaction | undefined> {\n const hash = hashId(ref.id);\n if (!hash) return undefined;\n const own = (await ctx.api.transactionsByMessage(hash, tags)).filter((tx) =>\n isOwnAttempt(tx, from, hash),\n );\n return own.find(consumesSeqno) ?? own[0];\n}\n\n/**\n * Each jetton leg's wallets must be the master's own for the sender and the intended\n * recipient (the same master), as masterchain block `block` (the trace's last) records\n * them: a fake jetton wallet can \"accept\" a transfer that moves nothing. The verdict\n * unchanged when they are.\n *\n * Only positive evidence decides `failed`, never a missing\n * answer. The sender's jetton wallet is the one the proof quorum attested at build and the\n * trace shows both wallets running, so a leg that cannot be verified (no answer, exit -13\n * \"no state at this block\", nothing that parses), or a sender wallet that is not ours,\n * contradicts the chain: a retryable `PROVIDER_INCONSISTENT` (logged `JETTON_UNVERIFIED`),\n * never a terminal failure that a new key would pay again. `failed` only when the recipient\n * wallet answered, and it is not the master's for the intended recipient (another wallet\n * named, another owner, another master): the jettons went elsewhere.\n */\nexport async function confirmLegs(\n ctx: TonContext,\n verdict: Verdict,\n from: string,\n tags: TonCallTags,\n block: number,\n): Promise<Verdict> {\n if (verdict.kind !== 'success') return verdict;\n for (const leg of verdict.legs) {\n const sender = await jettonWalletFacts(ctx, leg.senderWallet, tags, block);\n const recipient = await jettonWalletFacts(ctx, leg.recipientWallet, tags, block);\n if (\n sender.kind !== 'verified' ||\n sender.wallet.owner !== from ||\n recipient.kind === 'unknown'\n ) {\n ctx.log.warn('a jetton wallet of the transfer could not be verified', {\n code: 'JETTON_UNVERIFIED',\n });\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n 'the jetton wallets of the transfer could not be verified at its block',\n { retryable: true },\n );\n }\n if (\n recipient.kind === 'foreign' ||\n recipient.wallet.owner !== leg.recipient ||\n recipient.wallet.master !== sender.wallet.master\n ) {\n // The jettons left the wallet, to a wallet the master does not name.\n return Object.freeze({\n kind: 'failed',\n reason: REASONS.jettonUnverified,\n failure: 'unevidenced',\n });\n }\n }\n return verdict;\n}\n\n/** The newest masterchain block of a trace: every leg's wallet has run by then. */\nexport function traceBlock(root: V3Transaction, trace: V3Trace | null): number {\n return Math.max(root.mcSeqno, ...(trace?.transactions ?? []).map((tx) => tx.mcSeqno));\n}\n\n// ---- the chain's own transactions ---------------------------------------------------------\n\n/** A raw address's account id, as a transaction cell names it. */\nexport const accountId = (raw: string): bigint =>\n BigInt(`0x${raw.slice(raw.indexOf(':') + 1)}`);\n\nexport const notTheChains = () =>\n new ProviderError(\n 'PROVIDER_INCONSISTENT',\n \"the liteserver answered a transaction that is not the chain's\",\n { retryable: true },\n );\n\n/**\n * A transaction the liteserver served, authenticated: its cell (capped by the API before\n * this decodes it) hashes to the id expected, and it is the account's own at the lt\n * expected. Anything else is not the chain's.\n */\nexport function authenticated(\n row: RawTransaction,\n expected: TransactionId,\n account: bigint,\n): Transaction {\n if (row.lt !== expected.lt || row.hash !== expected.hash) throw notTheChains();\n let cell: Cell;\n let tx: Transaction;\n try {\n const cells = Cell.fromBoc(Buffer.from(row.boc, 'base64'));\n if (cells.length !== 1) throw notTheChains();\n cell = cells[0] as Cell;\n tx = loadTransaction(cell.beginParse());\n } catch {\n throw notTheChains();\n }\n if (\n cell.hash().toString('hex') !== expected.hash ||\n tx.lt !== expected.lt ||\n tx.address !== account\n ) {\n throw notTheChains();\n }\n return tx;\n}\n\n/**\n * Whether the chain's `tx` ran its inbound message to the end: its compute and action\n * phases both succeeded, so its state and its outgoing messages stand (a failed phase\n * drops both, transaction.cpp).\n */\nexport function chainRan(tx: Transaction): boolean {\n const d = tx.description;\n return (\n d.type === 'generic' &&\n d.computePhase.type === 'vm' &&\n d.computePhase.success &&\n d.actionPhase?.success === true\n );\n}\n\n/**\n * Whether the chain's `tx` is our message run to the end: its inbound external message's\n * TEP-467 hash, computed here from the authenticated body, is `id`, and it consumed its\n * seqno.\n */\nexport function ourRun(tx: Transaction, wallet: string, id: string): boolean {\n const inbound = tx.inMessage;\n return (\n chainRan(tx) &&\n inbound?.info.type === 'external-in' &&\n externalHashOf(wallet, inbound.body) === id\n );\n}\n\n/**\n * The transaction `id` names, as the liteserver serves it under `tags` (v2, by its lt and\n * hash), authenticated. One read under the proof quorum is kept with the chain walk's\n * (`chainTxs`), and a kept one is as good as one fetched again; one read under any other\n * tags is used once.\n */\nasync function chainTransaction(\n ctx: TonContext,\n id: ChainTxId,\n tags: TonCallTags,\n): Promise<Transaction> {\n const key = `${id.lt}:${id.hash}`;\n const account = accountId(id.account);\n const kept = ctx.chainTxs.get(key);\n if (kept !== undefined) {\n if (kept.address !== account) throw notTheChains();\n return kept;\n }\n const [row] = await ctx.api.rawTransactions(id.account, id, 1, tags);\n if (row === undefined)\n throw notYet('the liteserver does not hold the transaction asked');\n const tx = authenticated(row, id, account);\n if (tags.quorum !== undefined && row.boc.length <= MEMO_TX_LENGTH) {\n keep(ctx.chainTxs, key, tx, CHAIN_MEMO);\n }\n return tx;\n}\n\n/**\n * An `out_msgs` value (block.tlb `HashmapE 15 ^(Message Any)`): the message's own cell,\n * read as `loadTransaction` reads it, so every transaction it loaded reads here too.\n */\nconst MESSAGE_CELL: DictionaryValue<Cell> = {\n serialize: Dictionary.Values.Cell().serialize,\n parse: (slice) => slice.loadRef(),\n};\n\n/**\n * The cells of the messages the chain's `tx` received and sent, as its own cell holds\n * them: a message's hash is its cell's, the same in the transaction that sent it and the\n * one that received it.\n */\nfunction messageCells(tx: Transaction): {\n readonly inbound: Cell | undefined;\n readonly outbound: readonly Cell[];\n} {\n const slice = (tx.raw.refs[0] as Cell).beginParse();\n const inbound = slice.loadBit() ? slice.loadRef() : undefined;\n const outbound = slice.loadDict(Dictionary.Keys.Uint(15), MESSAGE_CELL).values();\n return { inbound, outbound };\n}\n\nconst hashOf = (cell: Cell | undefined): string | undefined =>\n cell?.hash().toString('hex');\n\n/** The jettons an `internal_transfer` in `message` carries from `from`; else undefined. */\nfunction jettonsFrom(message: Cell, from: string): bigint | undefined {\n const { info, body } = loadMessage(message.beginParse());\n const transfer = info.type === 'internal' ? decodeJettonInternalTransfer(body) : null;\n return transfer?.from === from ? transfer.amount : undefined;\n}\n\n/** Whether the chain's last delivery `tx` did what the verdict says (`end`). */\nfunction endedAs(tx: Transaction, end: BounceEvidence['end'], from: string): boolean {\n if (end === 'bounced') {\n // The bounce phase sent the value back; `nofunds` and `negfunds` left it there.\n const d = tx.description;\n return d.type === 'generic' && d.bouncePhase?.type === 'ok';\n }\n if (end === 'unran') return !chainRan(tx);\n // It ran, and every `internal_transfer` it sent for us moved nothing.\n const amounts = messageCells(tx).outbound.map((m) => jettonsFrom(m, from));\n return (\n chainRan(tx) &&\n amounts.some((amount) => amount === 0n) &&\n !amounts.some((amount) => amount !== undefined && amount > 0n)\n );\n}\n\n/**\n * A bounce verdict (`transfer bounced`, `jetton transfer bounced`), authenticated from the\n * chain itself: a lone lying indexer could report one for a transfer that landed, and a\n * `failed` invites a second payment. The indexer only names the transactions\n * (`BounceEvidence`); the liteserver serves each under `tags` (the proof quorum on the\n * proof path), hashed here (`chainTransaction`). The verdict stands only when the chain\n * shows all of it: our wallet transaction is our Attempt run to the end; each delivery\n * received a message the one before it sent, by the message's cell hash, so no other\n * delivery (another transfer's bounce at the same recipient) stands in for ours, and the\n * message past our jetton wallet carries our jettons onward; and the last one sent the\n * value back, ran nothing, or moved no jettons. A delivery the liteserver does not hold\n * yet decides nothing (a retryable `PROVIDER_UNAVAILABLE`), nor do endpoints that disagree\n * on one (the quorum's `PROVIDER_INCONSISTENT`); a chain that shows otherwise is a\n * retryable `PROVIDER_INCONSISTENT` (logged `BOUNCE_UNPROVEN`), never `success` either: a\n * real bounce may only lack its evidence yet, and the indexer's word decides neither way.\n * Any other verdict passes unchanged.\n */\nexport async function confirmBounce(\n ctx: TonContext,\n verdict: Verdict,\n from: string,\n id: string,\n tags: TonCallTags,\n): Promise<Verdict> {\n if (verdict.kind !== 'failed') return verdict;\n const evidence = verdict.bounce;\n if (\n evidence === undefined &&\n verdict.reason !== REASONS.bounced &&\n verdict.reason !== REASONS.jettonBounced\n ) {\n return verdict;\n }\n const unproven = () => {\n ctx.log.warn('the chain does not show the bounce the indexer reports', {\n code: 'BOUNCE_UNPROVEN',\n });\n return new ProviderError(\n 'PROVIDER_INCONSISTENT',\n 'the chain does not show the bounce the indexer reports',\n { retryable: true },\n );\n };\n // Only a Gram bounce rests on a bounce phase, the value sent back; a jetton one rests on\n // a jetton wallet that ran nothing or moved nothing.\n if (\n evidence === undefined ||\n evidence.path.length === 0 ||\n (evidence.end === 'bounced') !== (verdict.reason === REASONS.bounced)\n ) {\n throw unproven();\n }\n const ours = await chainTransaction(ctx, { ...evidence.root, account: from }, tags);\n if (!ourRun(ours, from, id)) throw unproven();\n let sent = messageCells(ours).outbound;\n for (const [index, step] of evidence.path.entries()) {\n const message = sent.find((cell) => hashOf(cell) === step.message);\n if (!message || (index > 0 && !((jettonsFrom(message, from) ?? 0n) > 0n))) {\n throw unproven();\n }\n const tx = await chainTransaction(ctx, step, tags);\n const cells = messageCells(tx);\n const last = index === evidence.path.length - 1;\n if (\n hashOf(cells.inbound) !== step.message ||\n (last ? !endedAs(tx, evidence.end, from) : !chainRan(tx))\n ) {\n throw unproven();\n }\n sent = cells.outbound;\n }\n return verdict;\n}\n\n/**\n * What one history page reads once and uses for every transaction on it:\n * each masterchain block's header, and each jetton wallet's facts, read at the block of the\n * first (newest) transaction that needs them. The same answer reused, so it trusts nothing\n * more; a page reads from then on only what it has not read.\n */\nexport interface PageMemo {\n readonly headers: Map<number, Promise<BlockHeader>>;\n readonly jettonWallets: Map<string, Promise<JettonWalletFacts>>;\n}\n\nexport const pageMemo = (): PageMemo => ({\n headers: new Map(),\n jettonWallets: new Map(),\n});\n\n/** `read()` once per key in `memo` (none: read every time). */\nfunction remembered<K, V>(\n memo: Map<K, Promise<V>> | undefined,\n key: K,\n read: () => Promise<V>,\n): Promise<V> {\n if (!memo) return read();\n let pending = memo.get(key);\n if (!pending) {\n pending = read();\n memo.set(key, pending);\n }\n return pending;\n}\n\n/**\n * A transaction decoded with its jetton wallet verified at the transaction's own block\n * and its block's hash; `memo` shares both reads across one history page.\n */\nexport async function decodeWithJettons(\n ctx: TonContext,\n tx: V3Transaction,\n tags: TonCallTags,\n memo?: PageMemo,\n) {\n const candidate = jettonWalletToVerify(tx);\n // The arrival's own jetton wallet ran here; a notification's sender ran earlier.\n const jetton = candidate\n ? await verifyJettonWallet(\n ctx,\n candidate,\n tags,\n tx.mcSeqno,\n candidate === tx.account,\n memo,\n )\n : undefined;\n const header = await remembered(memo?.headers, tx.mcSeqno, () =>\n ctx.api.masterchainHeader(tx.mcSeqno, tags),\n );\n return decodeTransaction(tx, {\n blockHash: header.id.rootHash,\n ...(jetton ? { jetton } : {}),\n });\n}\n\n/** The highest masterchain seqno (a uint32). */\nconst MAX_BLOCK_SEQNO = 0xffff_ffffn;\n\nexport function createTonReader(ctx: TonContext): ChainReader {\n const { api } = ctx;\n return {\n getBalance: async (address, asset) => {\n const owner = ctx.codec.normalize(address).canonical;\n if (asset === 'native') return (await api.account(owner, READ)).balance;\n return jettonBalance(ctx, jettonMaster(ctx, asset), owner, READ);\n },\n getBlockHeight: async () => BigInt(await api.masterchainHead(MONITOR)),\n // Every masterchain block is final once it exists.\n getFinalizedHeight: async () => BigInt(await api.masterchainHead(MONITOR)),\n getBlock: async (ref) => {\n let seqno: number | null;\n let hash: string | undefined;\n if (typeof ref === 'bigint') {\n if (ref < 0n || ref > MAX_BLOCK_SEQNO) return null;\n seqno = Number(ref);\n } else {\n hash = hashId(ref);\n if (!hash) return null;\n seqno = await api.masterchainSeqnoOf(hash, READ);\n }\n if (seqno === null || seqno > (await api.masterchainHead(READ))) return null;\n const header = await api.masterchainHeader(seqno, READ);\n if (hash !== undefined && header.id.rootHash !== hash) {\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n 'the indexer and the liteserver name different blocks',\n { retryable: true },\n );\n }\n return toDriverBlock(header);\n },\n getTransaction: async (id) => {\n const tx = await findTransaction(ctx, id, READ);\n return tx ? decodeWithJettons(ctx, tx, READ) : null;\n },\n observe: async (ref, ordering, from): Promise<DriverTxObservation> => {\n const managed = ordering !== undefined && from !== undefined;\n const wallet = managed ? ctx.codec.normalize(from).canonical : undefined;\n // A managed Attempt is only ever our own wallet transaction (`isOwnAttempt`, before\n // any verdict), never a fallback.\n const tx =\n wallet !== undefined\n ? await findOwnAttempt(ctx, ref, wallet, MONITOR)\n : await findTransaction(ctx, ref.id, MONITOR);\n if (!tx) return { seen: 'none' };\n const header = await api.masterchainHeader(tx.mcSeqno, MONITOR);\n const seen = {\n seen: 'block' as const,\n txHash: tx.hash,\n blockHeight: BigInt(tx.mcSeqno),\n blockHash: header.id.rootHash,\n };\n // Anyone's transaction: its execution status as the chain reports it.\n if (wallet === undefined) return { ...seen, success: executed(tx) };\n // Our own Attempt, found under its id: the verdict path. A bounce, as a jetton leg,\n // stands only once the chain shows it.\n const trace = await api.trace(tx.hash, MONITOR);\n const verdict = await confirmBounce(\n ctx,\n await confirmLegs(\n ctx,\n attemptVerdict(tx, trace),\n wallet,\n MONITOR,\n traceBlock(tx, trace),\n ),\n wallet,\n hashId(ref.id) as string,\n MONITOR,\n );\n if (verdict.kind === 'pending') return seen;\n return verdict.kind === 'success'\n ? { ...seen, success: true }\n : {\n ...seen,\n success: false,\n reason: verdict.reason,\n ...(verdict.failure ? { failure: verdict.failure } : {}),\n };\n },\n getTokenMetadata: async (ref: TokenRef) =>\n jettonMetadata(ctx, jettonMaster(ctx, ref)),\n normalizeTokenRef: (ref) => ({\n standard: 'jetton',\n contract: jettonMaster(ctx, ref),\n }),\n };\n}\n\n// ---- seqnos --------------------------------------------------------------------------------\n\n/** A live seqno read and the account state it was read at. */\ninterface LiveSeqno {\n readonly seqno: bigint;\n readonly state: AccountState;\n /** Whether the wallet is deployed at that block (it then has a public key there). */\n readonly deployed: boolean;\n}\n\n/**\n * A get-method's answer is the one run where it was asked: at `block` (the full id\n * when the caller has it, else the masterchain seqno), and on `state` when given, the\n * account's last transaction there. An endpoint that drops the block answers at its own\n * latest state, which decides nothing (a retryable `PROVIDER_INCONSISTENT`).\n */\nfunction assertRunAt(\n result: BoundRunResult,\n block: BlockId | number,\n state?: Pick<AccountState, 'lastLt' | 'lastHash'>,\n): void {\n const atBlock =\n typeof block === 'number'\n ? result.block.workchain === -1 &&\n result.block.shard === MASTERCHAIN_SHARD &&\n result.block.seqno === block\n : sameBlock(result.block, block);\n if (\n !atBlock ||\n (state !== undefined &&\n (result.lastTransaction.lt !== state.lastLt ||\n result.lastTransaction.hash !== state.lastHash))\n ) {\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n 'a get-method was answered at another state than the one asked',\n { retryable: true },\n );\n }\n}\n\nconst MAX_WALLET_SEQNO = 0xffff_ffffn;\n\n/** The wallet's seqno at the latest state: 0 while undeployed (its first message deploys it). */\nexport async function walletSeqno(\n ctx: TonContext,\n address: string,\n tags: TonCallTags,\n): Promise<bigint> {\n return (await liveSeqno(ctx, address, tags)).seqno;\n}\n\n/**\n * The seqno at the block the account state was read at, so both come from one view. A\n * frozen account is refused from its state alone, before any get-method: its deploy\n * `StateInit` would not revive it, and a message signed for it can never run.\n */\nasync function liveSeqno(\n ctx: TonContext,\n address: string,\n tags: TonCallTags,\n): Promise<LiveSeqno> {\n const state = await ctx.api.account(address, tags);\n if (state.status === 'uninitialized') {\n return { seqno: 0n, state, deployed: false };\n }\n if (state.status === 'frozen') {\n throw new ChainError('TX_REFUSED', 'the wallet account is frozen');\n }\n const result = await ctx.api.runGetMethodAt(\n address,\n 'seqno',\n [],\n tags,\n state.blockSeqno,\n );\n assertRunAt(result, state.block, state);\n const first = result.stack[0];\n if (\n result.exitCode !== 0 ||\n first?.type !== 'num' ||\n first.value < 0n ||\n first.value > MAX_WALLET_SEQNO\n ) {\n throw new ValidationError(\n 'INVALID_INTENT',\n 'the account is not a v4r2 or v5r1 wallet',\n );\n }\n return { seqno: first.value, state, deployed: true };\n}\n\n/**\n * The wallet's public key at masterchain block `block` (`get_public_key`), read once and\n * only when needed; undefined when the account has none there. The answer is bound to the\n * block asked and, when given, to the account state read there.\n */\nexport function publicKeyAt(\n ctx: TonContext,\n address: string,\n tags: TonCallTags,\n block: BlockId | number,\n state?: Pick<AccountState, 'lastLt' | 'lastHash'>,\n): () => Promise<Uint8Array | undefined> {\n let key: Promise<Uint8Array | undefined> | undefined;\n const seqno = typeof block === 'number' ? block : block.seqno;\n const read = async (): Promise<Uint8Array | undefined> => {\n const result = await ctx.api.runGetMethodAt(\n address,\n 'get_public_key',\n [],\n tags,\n seqno,\n );\n assertRunAt(result, block, state);\n const first = result.stack[0];\n if (result.exitCode !== 0 || first?.type !== 'num') return undefined;\n if (first.value < 0n || first.value >= 1n << 256n) return undefined;\n return Buffer.from(first.value.toString(16).padStart(64, '0'), 'hex');\n };\n return () => (key ??= read());\n}\n\n/**\n * The wallet request `tx` proves `from` consumed its seqno,\n * else null. Every request must be the wallet's own, signed by its key (`requestIsOwn`): a\n * lone lying indexer can make up an external one, and anyone can post a relayed W5 body for\n * a small fee (a v5r1 wallet ignores a forged one). And it must have consumed the seqno: an\n * external request only when `consumesSeqno` holds (its action phase succeeded, or W5\n * committed and then threw 137), a relayed one only when the wallet ran it to the end\n * (`ran`: with no `commit()` there, a failed action phase rolls the seqno back). A foreign\n * request signed with the same key whose action phase failed consumed nothing. `publicKey`\n * gives the wallet's key for `tx`; it is read only for a request that passed the rest.\n */\nexport async function provenRequest(\n ctx: TonContext,\n tx: V3Transaction,\n from: string,\n publicKey: (tx: V3Transaction) => Promise<Uint8Array | undefined>,\n): Promise<WalletRequest | null> {\n const inMsg = tx.inMsg;\n if (!inMsg || tx.account !== from) return null;\n const body = messageBody(inMsg);\n const request = body ? decodeWalletRequest(body) : null;\n if (!body || !request) return null;\n if (inMsg.source === null) {\n if (request.auth !== 'external' || !consumesSeqno(tx)) return null;\n } else if (request.auth !== 'internal' || !ran(tx)) {\n return null;\n }\n const key = await publicKey(tx);\n return key && requestIsOwn(from, body, key, ctx.config.globalId) ? request : null;\n}\n\n/** The history page the seqno floor reads, and how many pages before it gives up. */\nconst FLOOR_PAGE = 64;\nconst FLOOR_PAGES = 4;\n\n/**\n * The seqno after the newest wallet request the indexer has. Once the previous transfer\n * is `included`, the core hands out the next seqno; a lagging liteserver read could still\n * show the consumed one, and a message signed for it could only end `replaced`. Only a\n * proven request counts, and only one newer than the live read: the live read\n * already covers the rest. The history is paged on the indexer's own pages (a page\n * whose newest transactions are not final yet still leads to the older ones) until it\n * reaches the live read's block; more than `FLOOR_PAGES` pages since then decides nothing\n * (retryable) rather than guess, and so does a request dated after its own lifetime.\n */\nasync function indexedSeqnoFloor(\n ctx: TonContext,\n address: string,\n live: LiveSeqno,\n tags: TonCallTags,\n): Promise<bigint> {\n const liveKey = live.deployed\n ? publicKeyAt(ctx, address, tags, live.state.block, live.state)\n : async () => undefined;\n // An undeployed wallet at the live read has no key there: read it at the evidence's own\n // block, which a lagging endpoint refuses (retryable), so nothing is guessed meanwhile.\n const key = async (tx: V3Transaction) =>\n (await liveKey()) ?? publicKeyAt(ctx, address, tags, tx.mcSeqno)();\n let endLt: bigint | undefined;\n for (let page = 0; page < FLOOR_PAGES; page += 1) {\n const { transactions, next } = await ctx.api.accountTransactionsPage(\n address,\n { limit: FLOOR_PAGE, ...(endLt !== undefined ? { endLt } : {}) },\n tags,\n );\n for (const tx of transactions) {\n if (tx.mcSeqno <= live.state.blockSeqno) return 0n; // newest first: the rest is older still\n const request = await provenRequest(ctx, tx, address, key);\n if (!request) continue;\n // A request that ran after its own lifetime is a record the chain\n // cannot produce (the wallet refuses it), so it decides nothing, as in the proofs.\n if (request.validUntil <= tx.now) {\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n 'the seqno consumer ran after its request expired',\n { retryable: true },\n );\n }\n return BigInt(request.seqno) + 1n;\n }\n if (next === undefined) return 0n;\n endLt = next;\n }\n throw notYet('the wallet history since the live seqno read is too long to check');\n}\n\nexport function createTonSequence(ctx: TonContext): SequenceSource {\n return {\n pending: async (address) => {\n const wallet = ctx.codec.normalize(address).canonical;\n const live = await liveSeqno(ctx, wallet, MONITOR);\n const floor = await indexedSeqnoFloor(ctx, wallet, live, MONITOR);\n return live.seqno > floor ? live.seqno : floor;\n },\n latest: async (address) =>\n walletSeqno(ctx, ctx.codec.normalize(address).canonical, MONITOR),\n };\n}\n\nexport function createTonExt(ctx: TonContext): TonExt {\n return {\n ton: {\n getSeqno: async (address) =>\n walletSeqno(ctx, ctx.codec.normalize(address).canonical, READ),\n // A caller sends jettons to it, so the proof quorum attests it, and the attested\n // answer is kept.\n jettonWallet: async (owner, master) =>\n jettonWalletAddress(\n ctx,\n jettonMaster(ctx, { standard: 'jetton', contract: master }),\n ctx.codec.normalize(owner).canonical,\n PROOF,\n ),\n },\n };\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import type { TxFailure } from '../../core/model/transaction';
1
2
  import type { V3Trace, V3Transaction } from './api';
2
3
  /** One jetton transfer: the jetton wallets whose owners must be `from` and `recipient`. */
3
4
  export interface JettonLeg {
@@ -5,12 +6,37 @@ export interface JettonLeg {
5
6
  readonly recipientWallet: string;
6
7
  readonly recipient: string;
7
8
  }
9
+ /** A transaction as the chain names it: its account (raw), logical time and hash (hex). */
10
+ export interface ChainTxId {
11
+ readonly account: string;
12
+ readonly lt: bigint;
13
+ readonly hash: string;
14
+ }
15
+ /** A delivery on a bounce's path: its transaction and the hash of the message it received. */
16
+ export interface Delivery extends ChainTxId {
17
+ readonly message: string;
18
+ }
19
+ /**
20
+ * Where the chain records a bounce, as the indexer names it: our wallet transaction
21
+ * (`root`), each delivery from its message on to the one that failed (`path`), and what
22
+ * that last one did (`end`): sent the value back (its bounce phase), ran nothing, or ran
23
+ * and moved no jettons. Names only: `confirmBounce` reads each from the chain.
24
+ */
25
+ export interface BounceEvidence {
26
+ readonly root: ChainTxId;
27
+ readonly path: readonly Delivery[];
28
+ readonly end: 'bounced' | 'unran' | 'unmoved';
29
+ }
8
30
  export type Verdict = {
9
31
  readonly kind: 'success';
10
32
  readonly legs: readonly JettonLeg[];
11
33
  } | {
12
34
  readonly kind: 'failed';
13
35
  readonly reason: string;
36
+ /** Absent: the transfer did not happen (`reverted`). */
37
+ readonly failure?: TxFailure;
38
+ /** Every `bounced` and `jettonBounced` verdict carries its chain evidence. */
39
+ readonly bounce?: BounceEvidence;
14
40
  }
15
41
  /**
16
42
  * Not decidable yet: the trace is still being executed or indexed, or the request ran
@@ -21,6 +21,10 @@ exports.attemptVerdict = attemptVerdict;
21
21
  * wallets are the master's own for the sender and the intended recipient. That last
22
22
  * check needs chain reads, so the verdict returns the `legs` for the caller to confirm
23
23
  * (`confirmLegs` in `reader.ts`); the receiving wallet's own 707 check then holds.
24
+ * A bounce read here is still only the indexer's word, and a lone lying indexer could
25
+ * report one for a transfer that landed: so a bounce verdict returns where the chain
26
+ * records it (`bounce`), for the caller to authenticate from the chain itself
27
+ * (`confirmBounce` in `reader.ts`) before it decides anything.
24
28
  * Only a request that consumed its seqno is final: any other run (a failed action phase,
25
29
  * or a compute phase that failed before `commit()`) left the same message valid until it
26
30
  * expires, so anyone may replay it and move the value; such a run decides nothing
@@ -47,7 +51,7 @@ exports.REASONS = Object.freeze({
47
51
  jettonUnverified: 'the jetton wallets are not the master’s',
48
52
  });
49
53
  const PENDING = Object.freeze({ kind: 'pending' });
50
- const failed = (reason) => Object.freeze({ kind: 'failed', reason });
54
+ const failed = (reason, bounce) => Object.freeze({ kind: 'failed', reason, ...(bounce ? { bounce } : {}) });
51
55
  const inconsistent = (reason) => new error_1.ProviderError('PROVIDER_INCONSISTENT', reason, { retryable: true });
52
56
  /**
53
57
  * wallet_v5.fc: an external request whose send mode lacks +2, refused after `commit()`
@@ -209,10 +213,18 @@ function onward(hop, from) {
209
213
  return null;
210
214
  throw inconsistent('the jetton wallet ran the transfer but sent none from the sender');
211
215
  }
216
+ /** `tx`, which received `message`, as a delivery on a bounce's path. */
217
+ const delivery = (tx, message) => ({
218
+ account: tx.account,
219
+ lt: tx.lt,
220
+ hash: tx.hash,
221
+ message: message.hash,
222
+ });
212
223
  /** The outcome of the output `sent` of our wallet `from`, checked against the chain. */
213
224
  function outcomeOf(trace, from, sent) {
214
225
  const { out, bounceable, jettonRecipient } = sent;
215
226
  const hop = receiver(trace, out, from);
227
+ const first = delivery(hop, out);
216
228
  const hopRan = (0, decode_1.ran)(hop);
217
229
  // A bounce phase exists only for a bounceable message, and always when its compute
218
230
  // phase failed (collator.cpp, transaction.cpp `bounce_enabled`). A bounce on a message
@@ -226,20 +238,28 @@ function outcomeOf(trace, from, sent) {
226
238
  }
227
239
  if (jettonRecipient === undefined) {
228
240
  // The value stays unless the bounce phase sent it back.
229
- return hop.bounce === 'ok' ? { failed: exports.REASONS.bounced } : { delivered: true };
241
+ return hop.bounce === 'ok'
242
+ ? { failed: exports.REASONS.bounced, path: [first], end: 'bounced' }
243
+ : { delivered: true };
230
244
  }
231
245
  // The owner's jetton wallet ran `transfer` and sent `internal_transfer` onwards. A
232
246
  // failed phase dropped its state: the jettons never left.
233
247
  if (!hopRan)
234
- return { failed: exports.REASONS.jettonBounced };
248
+ return { failed: exports.REASONS.jettonBounced, path: [first], end: 'unran' };
235
249
  const arrivalMessage = onward(hop, from);
236
- if (!arrivalMessage)
237
- return { failed: exports.REASONS.jettonBounced };
250
+ if (!arrivalMessage) {
251
+ return { failed: exports.REASONS.jettonBounced, path: [first], end: 'unmoved' };
252
+ }
238
253
  // TEP-74 707: the receiving wallet takes it only from the sender's jetton wallet.
239
254
  const arrival = receiver(trace, arrivalMessage, hop.account);
240
255
  // A failed phase drops the credit: the jettons came back, or never arrived.
241
- if (!(0, decode_1.ran)(arrival))
242
- return { failed: exports.REASONS.jettonBounced };
256
+ if (!(0, decode_1.ran)(arrival)) {
257
+ return {
258
+ failed: exports.REASONS.jettonBounced,
259
+ path: [first, delivery(arrival, arrivalMessage)],
260
+ end: 'unran',
261
+ };
262
+ }
243
263
  return {
244
264
  leg: {
245
265
  senderWallet: hop.account,
@@ -268,8 +288,14 @@ function attemptVerdict(root, trace) {
268
288
  // contradiction.
269
289
  const outcomes = sent.map((each) => outcomeOf(trace, root.account, each));
270
290
  for (const outcome of outcomes) {
271
- if ('failed' in outcome)
272
- return failed(outcome.failed);
291
+ if ('failed' in outcome) {
292
+ const { account, lt, hash } = root;
293
+ return failed(outcome.failed, Object.freeze({
294
+ root: { account, lt, hash },
295
+ path: outcome.path,
296
+ end: outcome.end,
297
+ }));
298
+ }
273
299
  }
274
300
  const legs = outcomes.flatMap((outcome) => ('leg' in outcome ? [outcome.leg] : []));
275
301
  return Object.freeze({ kind: 'success', legs });