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.
- package/CHANGELOG.md +151 -1
- package/README.md +32 -12
- package/dist/adapters/evm/builder.js +64 -4
- package/dist/adapters/evm/builder.js.map +1 -1
- package/dist/adapters/evm/decode.js +6 -1
- package/dist/adapters/evm/decode.js.map +1 -1
- package/dist/adapters/evm/ethers-client.js +4 -0
- package/dist/adapters/evm/ethers-client.js.map +1 -1
- package/dist/adapters/evm/fees.d.ts +24 -0
- package/dist/adapters/evm/fees.js +47 -4
- package/dist/adapters/evm/fees.js.map +1 -1
- package/dist/adapters/evm/index.d.ts +1 -1
- package/dist/adapters/evm/index.js +2 -1
- package/dist/adapters/evm/index.js.map +1 -1
- package/dist/adapters/evm/network.d.ts +5 -0
- package/dist/adapters/evm/network.js +21 -2
- package/dist/adapters/evm/network.js.map +1 -1
- package/dist/adapters/evm/plugin.d.ts +5 -6
- package/dist/adapters/evm/plugin.js +50 -2
- package/dist/adapters/evm/plugin.js.map +1 -1
- package/dist/adapters/evm/proofs.js +17 -5
- package/dist/adapters/evm/proofs.js.map +1 -1
- package/dist/adapters/evm/reader.d.ts +18 -0
- package/dist/adapters/evm/reader.js +34 -0
- package/dist/adapters/evm/reader.js.map +1 -1
- package/dist/adapters/evm/tokens.d.ts +3 -0
- package/dist/adapters/evm/tokens.js.map +1 -1
- package/dist/adapters/evm/types.d.ts +10 -0
- package/dist/adapters/evm/types.js.map +1 -1
- package/dist/adapters/evm/web3-client.d.ts +6 -3
- package/dist/adapters/evm/web3-client.js +19 -2
- package/dist/adapters/evm/web3-client.js.map +1 -1
- package/dist/adapters/solana/builder.js +29 -18
- package/dist/adapters/solana/builder.js.map +1 -1
- package/dist/adapters/solana/fees.d.ts +12 -3
- package/dist/adapters/solana/fees.js +13 -4
- package/dist/adapters/solana/fees.js.map +1 -1
- package/dist/adapters/solana/message.d.ts +15 -0
- package/dist/adapters/solana/message.js +120 -0
- package/dist/adapters/solana/message.js.map +1 -0
- package/dist/adapters/solana/plugin.js +4 -1
- package/dist/adapters/solana/plugin.js.map +1 -1
- package/dist/adapters/solana/types.d.ts +8 -5
- package/dist/adapters/solana/types.js.map +1 -1
- package/dist/adapters/solana/web3.js +10 -32
- package/dist/adapters/solana/web3.js.map +1 -1
- package/dist/adapters/ton/proofs.js +18 -76
- package/dist/adapters/ton/proofs.js.map +1 -1
- package/dist/adapters/ton/reader.d.ts +45 -4
- package/dist/adapters/ton/reader.js +200 -5
- package/dist/adapters/ton/reader.js.map +1 -1
- package/dist/adapters/ton/trace.d.ts +26 -0
- package/dist/adapters/ton/trace.js +35 -9
- package/dist/adapters/ton/trace.js.map +1 -1
- package/dist/adapters/tron/abi.d.ts +2 -0
- package/dist/adapters/tron/abi.js +2 -0
- package/dist/adapters/tron/abi.js.map +1 -1
- package/dist/adapters/tron/builder.js +20 -4
- package/dist/adapters/tron/builder.js.map +1 -1
- package/dist/adapters/tron/decode.d.ts +2 -0
- package/dist/adapters/tron/decode.js +1 -1
- package/dist/adapters/tron/decode.js.map +1 -1
- package/dist/adapters/tron/proofs.js +1 -0
- package/dist/adapters/tron/proofs.js.map +1 -1
- package/dist/adapters/tron/reader.d.ts +10 -0
- package/dist/adapters/tron/reader.js +17 -0
- package/dist/adapters/tron/reader.js.map +1 -1
- package/dist/adapters/tron/tokens.d.ts +2 -0
- package/dist/adapters/tron/tokens.js.map +1 -1
- package/dist/adapters/utxo/builder.js +1 -1
- package/dist/adapters/utxo/builder.js.map +1 -1
- package/dist/adapters/utxo/chains.js +2 -1
- package/dist/adapters/utxo/chains.js.map +1 -1
- package/dist/adapters/utxo/context.d.ts +6 -0
- package/dist/adapters/utxo/context.js +8 -1
- package/dist/adapters/utxo/context.js.map +1 -1
- package/dist/adapters/utxo/decode.d.ts +8 -0
- package/dist/adapters/utxo/decode.js +36 -0
- package/dist/adapters/utxo/decode.js.map +1 -1
- package/dist/adapters/utxo/driver.js +5 -0
- package/dist/adapters/utxo/driver.js.map +1 -1
- package/dist/adapters/utxo/esplora.d.ts +23 -2
- package/dist/adapters/utxo/esplora.js +49 -2
- package/dist/adapters/utxo/esplora.js.map +1 -1
- package/dist/adapters/utxo/proofs.d.ts +15 -6
- package/dist/adapters/utxo/proofs.js +185 -47
- package/dist/adapters/utxo/proofs.js.map +1 -1
- package/dist/adapters/utxo/rawblock.d.ts +46 -0
- package/dist/adapters/utxo/rawblock.js +159 -0
- package/dist/adapters/utxo/rawblock.js.map +1 -0
- package/dist/adapters/utxo/rawtx.d.ts +14 -0
- package/dist/adapters/utxo/rawtx.js +44 -14
- package/dist/adapters/utxo/rawtx.js.map +1 -1
- package/dist/core/blockchain/handle.d.ts +6 -27
- package/dist/core/blockchain/handle.js +112 -112
- package/dist/core/blockchain/handle.js.map +1 -1
- package/dist/core/config/types.d.ts +15 -0
- package/dist/core/config/types.js.map +1 -1
- package/dist/core/container/container.d.ts +1 -8
- package/dist/core/container/container.js +42 -8
- package/dist/core/container/container.js.map +1 -1
- package/dist/core/driver/types.d.ts +34 -1
- package/dist/core/driver/types.js.map +1 -1
- package/dist/core/errors/codes.d.ts +10 -0
- package/dist/core/errors/codes.js +4 -0
- package/dist/core/errors/codes.js.map +1 -1
- package/dist/core/lifecycle/engine-rules.d.ts +3 -4
- package/dist/core/lifecycle/engine-rules.js +16 -6
- package/dist/core/lifecycle/engine-rules.js.map +1 -1
- package/dist/core/lifecycle/engine.d.ts +2 -0
- package/dist/core/lifecycle/engine.js +19 -1
- package/dist/core/lifecycle/engine.js.map +1 -1
- package/dist/core/lifecycle/evaluate.js +9 -4
- package/dist/core/lifecycle/evaluate.js.map +1 -1
- package/dist/core/lifecycle/monitor.js +16 -6
- package/dist/core/lifecycle/monitor.js.map +1 -1
- package/dist/core/lifecycle/reconcile.d.ts +1 -1
- package/dist/core/lifecycle/reconcile.js +1 -1
- package/dist/core/lifecycle/reconcile.js.map +1 -1
- package/dist/core/lifecycle/workers.d.ts +9 -3
- package/dist/core/lifecycle/workers.js +32 -14
- package/dist/core/lifecycle/workers.js.map +1 -1
- package/dist/core/model/ids.d.ts +1 -0
- package/dist/core/model/ids.js +1 -0
- package/dist/core/model/ids.js.map +1 -1
- package/dist/core/model/ordering.d.ts +8 -0
- package/dist/core/model/ordering.js.map +1 -1
- package/dist/core/model/transaction.d.ts +7 -0
- package/dist/core/model/transaction.js.map +1 -1
- package/dist/core/observe/scanner.js +3 -0
- package/dist/core/observe/scanner.js.map +1 -1
- package/dist/core/signing/wallet.js +8 -0
- package/dist/core/signing/wallet.js.map +1 -1
- package/dist/core/store/format.d.ts +20 -0
- package/dist/core/store/format.js +86 -0
- package/dist/core/store/format.js.map +1 -0
- package/dist/core/store/memory.js +2 -2
- package/dist/core/store/memory.js.map +1 -1
- package/dist/core/store/types.d.ts +15 -3
- package/dist/core/store/types.js +2 -0
- package/dist/core/store/types.js.map +1 -1
- package/dist/core/transport/http-transport.js +21 -13
- package/dist/core/transport/http-transport.js.map +1 -1
- package/dist/core/transport/types.d.ts +16 -1
- package/dist/core/transport/types.js.map +1 -1
- package/dist/core/util/json.d.ts +7 -1
- package/dist/core/util/json.js +13 -4
- package/dist/core/util/json.js.map +1 -1
- package/dist/core/util/names.d.ts +6 -0
- package/dist/core/util/names.js +10 -0
- package/dist/core/util/names.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/testing/contracts/operations.js +20 -1
- package/dist/testing/contracts/operations.js.map +1 -1
- package/dist/testing/env.d.ts +5 -0
- package/dist/testing/env.js +1 -1
- package/dist/testing/env.js.map +1 -1
- package/dist/testing/faulty-store.d.ts +2 -0
- package/dist/testing/faulty-store.js +5 -0
- package/dist/testing/faulty-store.js.map +1 -1
- package/package.json +17 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trace.js","sourceRoot":"","sources":["../../../src/adapters/ton/trace.ts"],"names":[],"mappings":";;;AAyGA,sC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AE,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC;IAC1E,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,IAAI,QAAQ,IAAI,OAAO;YAAE,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACzD,CAAC;IACD,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,KAAK,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACpF,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;AAClD,CAAC","sourcesContent":["/**\n * The verdict on one of our own Attempts: did the value move? A TON wallet transaction\n * \"succeeds\" even when it moved nothing (send mode +2 skips a message it cannot pay), and\n * a transfer can still bounce, or a jetton move fail, one or two hops later. So an\n * Attempt succeeded only when:\n * - the wallet transaction consumed the request's seqno and ran it to the end;\n * - every message of the signed request is among its outgoing messages (a missing one is a\n * skip only when the wallet's action phase itself counts that many skipped actions);\n * - no native message came back bounced (a `nofunds` or `negfunds` bounce, a failed action\n * phase without send mode +16 and a non-bounceable message all leave the value with the\n * recipient), each delivery's bounce phase agreeing with the flag we signed;\n * - every jetton request reached a jetton wallet as an `internal_transfer` of a positive\n * amount from our wallet, sent by our jetton wallet and run to the end by the receiving\n * one (the exact amount is not required: fee-on-transfer tokens exist), and both jetton\n * wallets are the master's own for the sender and the intended recipient. That last\n * check needs chain reads, so the verdict returns the `legs` for the caller to confirm\n * (`confirmLegs` in `reader.ts`); the receiving wallet's own 707 check then holds.\n * Only a request that consumed its seqno is final: any other run (a failed action phase,\n * or a compute phase that failed before `commit()`) left the same message valid until it\n * expires, so anyone may replay it and move the value; such a run decides nothing\n * (`pending`), and only the seqno or the proven expiry can.\n * Used on the verdict paths only (`observe`, `includedFinal`). Every body read here is\n * bound to the hash the quorum keyed (`messageBody`). A batch is one Attempt: one bounced\n * output fails it, although the other outputs moved. Only the chain's own record of a\n * failure decides `failed`; an answer that contradicts the chain or the signed request (a\n * message missing that the wallet did not skip, a jetton wallet that ran the transfer yet\n * sent nothing from the sender, phases that contradict each other or the chain's own\n * counters) throws a retryable `PROVIDER_INCONSISTENT`, which decides nothing. Every\n * output is checked before any of them decides.\n */\nimport { ProviderError } from '../../core/errors/error';\nimport type { V3Message, V3Trace, V3Transaction } from './api';\nimport { ran, threwAfterCommit } from './decode';\nimport {\n OP,\n decodeComment,\n decodeJettonInternalTransfer,\n decodeJettonTransfer,\n decodeWalletRequest,\n messageBody,\n messageFacts,\n} from './messages';\nimport { externalHashOf } from './wallets';\n\n/** One jetton transfer: the jetton wallets whose owners must be `from` and `recipient`. */\nexport interface JettonLeg {\n readonly senderWallet: string;\n readonly recipientWallet: string;\n readonly recipient: string;\n}\n\nexport type Verdict =\n | { readonly kind: 'success'; readonly legs: readonly JettonLeg[] }\n | { readonly kind: 'failed'; readonly reason: string }\n /**\n * Not decidable yet: the trace is still being executed or indexed, or the request ran\n * without consuming its seqno and may still run again until it expires.\n */\n | { readonly kind: 'pending' };\n\n/** Fixed reasons: a stored reason never holds an address, an amount or node text. */\nexport const REASONS = Object.freeze({\n walletFailed: 'the wallet transaction failed',\n skipped: 'the wallet skipped a message',\n bounced: 'transfer bounced',\n jettonBounced: 'jetton transfer bounced',\n jettonUnverified: 'the jetton wallets are not the master’s',\n});\n\nconst PENDING: Verdict = Object.freeze({ kind: 'pending' });\nconst failed = (reason: string): Verdict => Object.freeze({ kind: 'failed', reason });\n\nconst inconsistent = (reason: string) =>\n new ProviderError('PROVIDER_INCONSISTENT', reason, { retryable: true });\n\n/**\n * wallet_v5.fc: an external request whose send mode lacks +2, refused after `commit()`\n * stored the next seqno with an empty action list. The chain counts that compute phase a\n * success (transaction.cpp: `success = accepted && committed`) and runs the empty list, so\n * the transaction ran; the scripted node records it that way too. An indexer that wrote it\n * as a failed compute phase is still read as W5's refusal.\n */\nconst W5_REFUSED_AFTER_COMMIT = 137;\n\n/** Whether `tx` ran a W5 signed external request (only W5 throws 137 after committing). */\nfunction w5External(tx: V3Transaction): boolean {\n if (!tx.inMsg || tx.inMsg.source !== null) return false;\n const body = messageBody(tx.inMsg);\n return (\n body !== null &&\n body.bits.length >= 32 &&\n body.beginParse().preloadUint(32) === OP.w5SignedExternal\n );\n}\n\n/**\n * Whether the wallet transaction of an external request `tx` consumed the request's seqno,\n * so that the same message can never run again: it ran (the new seqno stands with the\n * actions, W5's 137 included), or, as a defensive reading of W5 alone, its compute phase is\n * recorded failed with 137. Any other run left the old seqno (transaction.cpp: a\n * failed action phase drops the compute phase's state, and a compute phase that failed\n * before `commit()` never had one): a foreign request signed with the same key, or our\n * own, whose action phase failed does not consume the seqno. Throws the retryable\n * contradiction of `ran`.\n */\nexport function consumesSeqno(tx: V3Transaction): boolean {\n if (ran(tx)) return true;\n return (\n !tx.compute.success &&\n !tx.compute.skipped &&\n tx.compute.exitCode === W5_REFUSED_AFTER_COMMIT &&\n w5External(tx)\n );\n}\n\n/**\n * Whether `tx` is our Attempt: the external message to `from` whose TEP-467 hash,\n * computed here from the bound body, is the Attempt id. The indexer's `hash_norm` only\n * finds candidates; it never decides.\n */\nexport function isOwnAttempt(tx: V3Transaction, from: string, refId: string): boolean {\n if (!tx.inMsg || tx.inMsg.source !== null || tx.account !== from) return false;\n const body = messageBody(tx.inMsg);\n return body !== null && externalHashOf(tx.account, body) === refId;\n}\n\n/**\n * The transaction in `trace` that received `message`, which `sender` sent. An internal\n * message is delivered once, to its destination, with its value and its bounce flag:\n * anything else contradicts the chain.\n */\nfunction receiver(trace: V3Trace, message: V3Message, sender: string): V3Transaction {\n const found = trace.transactions.filter((t) => t.inMsg?.hash === message.hash);\n const [tx] = found;\n if (!tx) throw inconsistent('a complete trace lacks a delivered message');\n if (\n found.length > 1 ||\n message.source !== sender ||\n tx.account !== message.destination ||\n tx.inMsg?.source !== sender ||\n tx.inMsg.value !== message.value ||\n (message.bounce !== null &&\n tx.inMsg.bounce !== null &&\n tx.inMsg.bounce !== message.bounce)\n ) {\n throw inconsistent('the trace delivered a message other than the one sent');\n }\n return tx;\n}\n\ninterface Sent {\n readonly out: V3Message;\n /** The bounce flag we signed for it: it decides whether a bounce phase may exist. */\n readonly bounceable: boolean;\n /** For a jetton request: its intended recipient (the owner). */\n readonly jettonRecipient?: string;\n}\n\n/** A native transfer as our builder signs it: a positive value, no body or a comment. */\nfunction plainTransfer(facts: NonNullable<ReturnType<typeof messageFacts>>): boolean {\n const { value, body } = facts;\n const empty = body.bits.length === 0 && body.refs.length === 0;\n return value > 0n && (empty || decodeComment(body) !== undefined);\n}\n\n/**\n * The requested messages, matched one to one with the wallet transaction's outgoing\n * messages; or why they did not all go out: the wallet skipped them (send mode +2), or its\n * code threw after committing the seqno. `ran` holds, so the outgoing messages are\n * distinct and as many as the action phase created; the skips must be exactly the missing\n * messages.\n */\nfunction sentMessages(root: V3Transaction): readonly Sent[] | 'skipped' | 'threw' {\n const body = messageBody(root.inMsg as V3Message);\n if (!body) throw inconsistent('the indexer has no body for the external message');\n const request = decodeWalletRequest(body);\n if (!request || request.auth !== 'external') {\n throw inconsistent('the indexed external message is not a wallet transfer');\n }\n const action = root.action as NonNullable<V3Transaction['action']>;\n // Committed, then threw (W5 137): the list committed with the seqno was empty.\n if (threwAfterCommit(root)) {\n if (action.msgsCreated !== 0 || action.skippedActions !== 0) {\n throw inconsistent('the wallet threw after committing, yet ran an action');\n }\n return 'threw';\n }\n const unused = [...root.outMsgs];\n const matched: Sent[] = [];\n let missing = 0;\n for (const requested of request.messages) {\n const facts = messageFacts(requested);\n if (!facts)\n throw inconsistent('the signed request holds a message that is not internal');\n // Our builder signs only plain transfers of a positive value and TEP-74 transfers; any\n // other message moves what the verdict cannot see, so it is never judged a success.\n const jetton = decodeJettonTransfer(facts.body);\n if (!jetton && !plainTransfer(facts)) {\n throw inconsistent('the signed request holds a message the verdict cannot judge');\n }\n const index = unused.findIndex(\n (out) =>\n out.destination === facts.to &&\n out.value === facts.value &&\n out.bodyHash === facts.bodyHash,\n );\n if (index < 0) {\n missing += 1;\n continue;\n }\n const out = unused.splice(index, 1)[0] as V3Message;\n // A message leaves the wallet with the flag we signed.\n const bounceable = requested.info.type === 'internal' && requested.info.bounce;\n if (out.bounce !== null && out.bounce !== bounceable) {\n throw inconsistent('a message went out with another bounce flag than signed');\n }\n matched.push({\n out,\n bounceable,\n ...(jetton ? { jettonRecipient: jetton.destination } : {}),\n });\n }\n if (unused.length > 0) {\n throw inconsistent(\n 'the wallet transaction sent a message the request did not ask for',\n );\n }\n // Send mode +2: the wallet records exactly the messages it skipped. The action phase\n // counts skipped sends since global version 8 (config param 8), which both networks\n // run; on an older chain this refuses (retryable), and never decides.\n if (missing !== action.skippedActions) {\n throw inconsistent('the wallet counts other skips than the messages it did not send');\n }\n return missing > 0 ? 'skipped' : matched;\n}\n\n/**\n * The `internal_transfer` our jetton wallet `hop` sent onwards for our wallet `from`: the\n * message of a positive amount, `null` when it moved nothing.\n */\nfunction onward(hop: V3Transaction, from: string): V3Message | null {\n let nothingMoved = false;\n for (const m of hop.outMsgs) {\n const body = messageBody(m);\n const internal = body ? decodeJettonInternalTransfer(body) : null;\n if (!internal || internal.from !== from) continue;\n // From the sender, a positive amount, never the exact one (fee-on-transfer tokens).\n if (internal.amount > 0n) return m;\n nothingMoved = true; // a zero amount: nothing moved, so `failed` is accurate\n }\n if (nothingMoved) return null;\n throw inconsistent('the jetton wallet ran the transfer but sent none from the sender');\n}\n\n/** What one output did: failed (with why), a jetton leg to confirm, or delivered. */\ntype Outcome =\n | { readonly failed: string }\n | { readonly leg: JettonLeg }\n | { readonly delivered: true };\n\n/** The outcome of the output `sent` of our wallet `from`, checked against the chain. */\nfunction outcomeOf(trace: V3Trace, from: string, sent: Sent): Outcome {\n const { out, bounceable, jettonRecipient } = sent;\n const hop = receiver(trace, out, from);\n const hopRan = ran(hop);\n // A bounce phase exists only for a bounceable message, and always when its compute\n // phase failed (collator.cpp, transaction.cpp `bounce_enabled`). A bounce on a message\n // we signed non-bounceable would fail a delivery that credited the value; a failed\n // bounceable delivery without one lacks data. The flag we signed decides, even when the\n // indexer leaves the delivery's own flag out.\n if (\n (hop.inMsg?.bounce !== null && hop.inMsg?.bounce !== bounceable) ||\n (hop.bounce !== undefined && !bounceable) ||\n (bounceable && !hop.compute.success && hop.bounce === undefined)\n ) {\n throw inconsistent('the delivery contradicts the bounce flag we signed');\n }\n if (jettonRecipient === undefined) {\n // The value stays unless the bounce phase sent it back.\n return hop.bounce === 'ok' ? { failed: REASONS.bounced } : { delivered: true };\n }\n // The owner's jetton wallet ran `transfer` and sent `internal_transfer` onwards. A\n // failed phase dropped its state: the jettons never left.\n if (!hopRan) return { failed: REASONS.jettonBounced };\n const arrivalMessage = onward(hop, from);\n if (!arrivalMessage) return { failed: REASONS.jettonBounced };\n // TEP-74 707: the receiving wallet takes it only from the sender's jetton wallet.\n const arrival = receiver(trace, arrivalMessage, hop.account);\n // A failed phase drops the credit: the jettons came back, or never arrived.\n if (!ran(arrival)) return { failed: REASONS.jettonBounced };\n return {\n leg: {\n senderWallet: hop.account,\n recipientWallet: arrival.account,\n recipient: jettonRecipient,\n },\n };\n}\n\n/** The verdict on the Attempt whose wallet transaction is `root`, within `trace`. */\nexport function attemptVerdict(root: V3Transaction, trace: V3Trace | null): Verdict {\n if (!root.inMsg || root.inMsg.source !== null) {\n throw inconsistent('the attempt is not an external message');\n }\n if (!consumesSeqno(root)) return PENDING;\n if (!root.compute.success) return failed(REASONS.walletFailed);\n const sent = sentMessages(root);\n if (sent === 'threw') return failed(REASONS.walletFailed);\n if (sent === 'skipped') return failed(REASONS.skipped);\n if (!trace || !trace.complete) return PENDING;\n // Every output is checked before any decides, so an early failure never hides a later\n // contradiction.\n const outcomes = sent.map((each) => outcomeOf(trace, root.account, each));\n for (const outcome of outcomes) {\n if ('failed' in outcome) return failed(outcome.failed);\n }\n const legs = outcomes.flatMap((outcome) => ('leg' in outcome ? [outcome.leg] : []));\n return Object.freeze({ kind: 'success', legs });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"trace.js","sourceRoot":"","sources":["../../../src/adapters/ton/trace.ts"],"names":[],"mappings":";;;AA8IA,sCAQC;AAOD,oCAIC;AA0MD,wCA4BC;AAvYD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,mDAAwD;AAGxD,qCAAiD;AACjD,yCAQoB;AACpB,uCAA2C;AAiD3C,qFAAqF;AACxE,QAAA,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC;IACnC,YAAY,EAAE,+BAA+B;IAC7C,OAAO,EAAE,8BAA8B;IACvC,OAAO,EAAE,kBAAkB;IAC3B,aAAa,EAAE,yBAAyB;IACxC,gBAAgB,EAAE,yCAAyC;CAC5D,CAAC,CAAC;AAEH,MAAM,OAAO,GAAY,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC;AAC5D,MAAM,MAAM,GAAG,CAAC,MAAc,EAAE,MAAuB,EAAW,EAAE,CAClE,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AAE3E,MAAM,YAAY,GAAG,CAAC,MAAc,EAAE,EAAE,CACtC,IAAI,qBAAa,CAAC,uBAAuB,EAAE,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;AAE1E;;;;;;GAMG;AACH,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC,2FAA2F;AAC3F,SAAS,UAAU,CAAC,EAAiB;IACnC,IAAI,CAAC,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,KA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,CAAC;YACnC,OAAO,MAAM,CACX,OAAO,CAAC,MAAM,EACd,MAAM,CAAC,MAAM,CAAC;gBACZ,IAAI,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE;gBAC3B,IAAI,EAAE,OAAO,CAAC,IAAI;gBAClB,GAAG,EAAE,OAAO,CAAC,GAAG;aACjB,CAAC,CACH,CAAC;QACJ,CAAC;IACH,CAAC;IACD,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,KAAK,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACpF,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;AAClD,CAAC","sourcesContent":["/**\n * The verdict on one of our own Attempts: did the value move? A TON wallet transaction\n * \"succeeds\" even when it moved nothing (send mode +2 skips a message it cannot pay), and\n * a transfer can still bounce, or a jetton move fail, one or two hops later. So an\n * Attempt succeeded only when:\n * - the wallet transaction consumed the request's seqno and ran it to the end;\n * - every message of the signed request is among its outgoing messages (a missing one is a\n * skip only when the wallet's action phase itself counts that many skipped actions);\n * - no native message came back bounced (a `nofunds` or `negfunds` bounce, a failed action\n * phase without send mode +16 and a non-bounceable message all leave the value with the\n * recipient), each delivery's bounce phase agreeing with the flag we signed;\n * - every jetton request reached a jetton wallet as an `internal_transfer` of a positive\n * amount from our wallet, sent by our jetton wallet and run to the end by the receiving\n * one (the exact amount is not required: fee-on-transfer tokens exist), and both jetton\n * wallets are the master's own for the sender and the intended recipient. That last\n * check needs chain reads, so the verdict returns the `legs` for the caller to confirm\n * (`confirmLegs` in `reader.ts`); the receiving wallet's own 707 check then holds.\n * A bounce read here is still only the indexer's word, and a lone lying indexer could\n * report one for a transfer that landed: so a bounce verdict returns where the chain\n * records it (`bounce`), for the caller to authenticate from the chain itself\n * (`confirmBounce` in `reader.ts`) before it decides anything.\n * Only a request that consumed its seqno is final: any other run (a failed action phase,\n * or a compute phase that failed before `commit()`) left the same message valid until it\n * expires, so anyone may replay it and move the value; such a run decides nothing\n * (`pending`), and only the seqno or the proven expiry can.\n * Used on the verdict paths only (`observe`, `includedFinal`). Every body read here is\n * bound to the hash the quorum keyed (`messageBody`). A batch is one Attempt: one bounced\n * output fails it, although the other outputs moved. Only the chain's own record of a\n * failure decides `failed`; an answer that contradicts the chain or the signed request (a\n * message missing that the wallet did not skip, a jetton wallet that ran the transfer yet\n * sent nothing from the sender, phases that contradict each other or the chain's own\n * counters) throws a retryable `PROVIDER_INCONSISTENT`, which decides nothing. Every\n * output is checked before any of them decides.\n */\nimport { ProviderError } from '../../core/errors/error';\nimport type { TxFailure } from '../../core/model/transaction';\nimport type { V3Message, V3Trace, V3Transaction } from './api';\nimport { ran, threwAfterCommit } from './decode';\nimport {\n OP,\n decodeComment,\n decodeJettonInternalTransfer,\n decodeJettonTransfer,\n decodeWalletRequest,\n messageBody,\n messageFacts,\n} from './messages';\nimport { externalHashOf } from './wallets';\n\n/** One jetton transfer: the jetton wallets whose owners must be `from` and `recipient`. */\nexport interface JettonLeg {\n readonly senderWallet: string;\n readonly recipientWallet: string;\n readonly recipient: string;\n}\n\n/** A transaction as the chain names it: its account (raw), logical time and hash (hex). */\nexport interface ChainTxId {\n readonly account: string;\n readonly lt: bigint;\n readonly hash: string;\n}\n\n/** A delivery on a bounce's path: its transaction and the hash of the message it received. */\nexport interface Delivery extends ChainTxId {\n readonly message: string;\n}\n\n/**\n * Where the chain records a bounce, as the indexer names it: our wallet transaction\n * (`root`), each delivery from its message on to the one that failed (`path`), and what\n * that last one did (`end`): sent the value back (its bounce phase), ran nothing, or ran\n * and moved no jettons. Names only: `confirmBounce` reads each from the chain.\n */\nexport interface BounceEvidence {\n readonly root: ChainTxId;\n readonly path: readonly Delivery[];\n readonly end: 'bounced' | 'unran' | 'unmoved';\n}\n\nexport type Verdict =\n | { readonly kind: 'success'; readonly legs: readonly JettonLeg[] }\n | {\n readonly kind: 'failed';\n readonly reason: string;\n /** Absent: the transfer did not happen (`reverted`). */\n readonly failure?: TxFailure;\n /** Every `bounced` and `jettonBounced` verdict carries its chain evidence. */\n readonly bounce?: BounceEvidence;\n }\n /**\n * Not decidable yet: the trace is still being executed or indexed, or the request ran\n * without consuming its seqno and may still run again until it expires.\n */\n | { readonly kind: 'pending' };\n\n/** Fixed reasons: a stored reason never holds an address, an amount or node text. */\nexport const REASONS = Object.freeze({\n walletFailed: 'the wallet transaction failed',\n skipped: 'the wallet skipped a message',\n bounced: 'transfer bounced',\n jettonBounced: 'jetton transfer bounced',\n jettonUnverified: 'the jetton wallets are not the master’s',\n});\n\nconst PENDING: Verdict = Object.freeze({ kind: 'pending' });\nconst failed = (reason: string, bounce?: BounceEvidence): Verdict =>\n Object.freeze({ kind: 'failed', reason, ...(bounce ? { bounce } : {}) });\n\nconst inconsistent = (reason: string) =>\n new ProviderError('PROVIDER_INCONSISTENT', reason, { retryable: true });\n\n/**\n * wallet_v5.fc: an external request whose send mode lacks +2, refused after `commit()`\n * stored the next seqno with an empty action list. The chain counts that compute phase a\n * success (transaction.cpp: `success = accepted && committed`) and runs the empty list, so\n * the transaction ran; the scripted node records it that way too. An indexer that wrote it\n * as a failed compute phase is still read as W5's refusal.\n */\nconst W5_REFUSED_AFTER_COMMIT = 137;\n\n/** Whether `tx` ran a W5 signed external request (only W5 throws 137 after committing). */\nfunction w5External(tx: V3Transaction): boolean {\n if (!tx.inMsg || tx.inMsg.source !== null) return false;\n const body = messageBody(tx.inMsg);\n return (\n body !== null &&\n body.bits.length >= 32 &&\n body.beginParse().preloadUint(32) === OP.w5SignedExternal\n );\n}\n\n/**\n * Whether the wallet transaction of an external request `tx` consumed the request's seqno,\n * so that the same message can never run again: it ran (the new seqno stands with the\n * actions, W5's 137 included), or, as a defensive reading of W5 alone, its compute phase is\n * recorded failed with 137. Any other run left the old seqno (transaction.cpp: a\n * failed action phase drops the compute phase's state, and a compute phase that failed\n * before `commit()` never had one): a foreign request signed with the same key, or our\n * own, whose action phase failed does not consume the seqno. Throws the retryable\n * contradiction of `ran`.\n */\nexport function consumesSeqno(tx: V3Transaction): boolean {\n if (ran(tx)) return true;\n return (\n !tx.compute.success &&\n !tx.compute.skipped &&\n tx.compute.exitCode === W5_REFUSED_AFTER_COMMIT &&\n w5External(tx)\n );\n}\n\n/**\n * Whether `tx` is our Attempt: the external message to `from` whose TEP-467 hash,\n * computed here from the bound body, is the Attempt id. The indexer's `hash_norm` only\n * finds candidates; it never decides.\n */\nexport function isOwnAttempt(tx: V3Transaction, from: string, refId: string): boolean {\n if (!tx.inMsg || tx.inMsg.source !== null || tx.account !== from) return false;\n const body = messageBody(tx.inMsg);\n return body !== null && externalHashOf(tx.account, body) === refId;\n}\n\n/**\n * The transaction in `trace` that received `message`, which `sender` sent. An internal\n * message is delivered once, to its destination, with its value and its bounce flag:\n * anything else contradicts the chain.\n */\nfunction receiver(trace: V3Trace, message: V3Message, sender: string): V3Transaction {\n const found = trace.transactions.filter((t) => t.inMsg?.hash === message.hash);\n const [tx] = found;\n if (!tx) throw inconsistent('a complete trace lacks a delivered message');\n if (\n found.length > 1 ||\n message.source !== sender ||\n tx.account !== message.destination ||\n tx.inMsg?.source !== sender ||\n tx.inMsg.value !== message.value ||\n (message.bounce !== null &&\n tx.inMsg.bounce !== null &&\n tx.inMsg.bounce !== message.bounce)\n ) {\n throw inconsistent('the trace delivered a message other than the one sent');\n }\n return tx;\n}\n\ninterface Sent {\n readonly out: V3Message;\n /** The bounce flag we signed for it: it decides whether a bounce phase may exist. */\n readonly bounceable: boolean;\n /** For a jetton request: its intended recipient (the owner). */\n readonly jettonRecipient?: string;\n}\n\n/** A native transfer as our builder signs it: a positive value, no body or a comment. */\nfunction plainTransfer(facts: NonNullable<ReturnType<typeof messageFacts>>): boolean {\n const { value, body } = facts;\n const empty = body.bits.length === 0 && body.refs.length === 0;\n return value > 0n && (empty || decodeComment(body) !== undefined);\n}\n\n/**\n * The requested messages, matched one to one with the wallet transaction's outgoing\n * messages; or why they did not all go out: the wallet skipped them (send mode +2), or its\n * code threw after committing the seqno. `ran` holds, so the outgoing messages are\n * distinct and as many as the action phase created; the skips must be exactly the missing\n * messages.\n */\nfunction sentMessages(root: V3Transaction): readonly Sent[] | 'skipped' | 'threw' {\n const body = messageBody(root.inMsg as V3Message);\n if (!body) throw inconsistent('the indexer has no body for the external message');\n const request = decodeWalletRequest(body);\n if (!request || request.auth !== 'external') {\n throw inconsistent('the indexed external message is not a wallet transfer');\n }\n const action = root.action as NonNullable<V3Transaction['action']>;\n // Committed, then threw (W5 137): the list committed with the seqno was empty.\n if (threwAfterCommit(root)) {\n if (action.msgsCreated !== 0 || action.skippedActions !== 0) {\n throw inconsistent('the wallet threw after committing, yet ran an action');\n }\n return 'threw';\n }\n const unused = [...root.outMsgs];\n const matched: Sent[] = [];\n let missing = 0;\n for (const requested of request.messages) {\n const facts = messageFacts(requested);\n if (!facts)\n throw inconsistent('the signed request holds a message that is not internal');\n // Our builder signs only plain transfers of a positive value and TEP-74 transfers; any\n // other message moves what the verdict cannot see, so it is never judged a success.\n const jetton = decodeJettonTransfer(facts.body);\n if (!jetton && !plainTransfer(facts)) {\n throw inconsistent('the signed request holds a message the verdict cannot judge');\n }\n const index = unused.findIndex(\n (out) =>\n out.destination === facts.to &&\n out.value === facts.value &&\n out.bodyHash === facts.bodyHash,\n );\n if (index < 0) {\n missing += 1;\n continue;\n }\n const out = unused.splice(index, 1)[0] as V3Message;\n // A message leaves the wallet with the flag we signed.\n const bounceable = requested.info.type === 'internal' && requested.info.bounce;\n if (out.bounce !== null && out.bounce !== bounceable) {\n throw inconsistent('a message went out with another bounce flag than signed');\n }\n matched.push({\n out,\n bounceable,\n ...(jetton ? { jettonRecipient: jetton.destination } : {}),\n });\n }\n if (unused.length > 0) {\n throw inconsistent(\n 'the wallet transaction sent a message the request did not ask for',\n );\n }\n // Send mode +2: the wallet records exactly the messages it skipped. The action phase\n // counts skipped sends since global version 8 (config param 8), which both networks\n // run; on an older chain this refuses (retryable), and never decides.\n if (missing !== action.skippedActions) {\n throw inconsistent('the wallet counts other skips than the messages it did not send');\n }\n return missing > 0 ? 'skipped' : matched;\n}\n\n/**\n * The `internal_transfer` our jetton wallet `hop` sent onwards for our wallet `from`: the\n * message of a positive amount, `null` when it moved nothing.\n */\nfunction onward(hop: V3Transaction, from: string): V3Message | null {\n let nothingMoved = false;\n for (const m of hop.outMsgs) {\n const body = messageBody(m);\n const internal = body ? decodeJettonInternalTransfer(body) : null;\n if (!internal || internal.from !== from) continue;\n // From the sender, a positive amount, never the exact one (fee-on-transfer tokens).\n if (internal.amount > 0n) return m;\n nothingMoved = true; // a zero amount: nothing moved, so `failed` is accurate\n }\n if (nothingMoved) return null;\n throw inconsistent('the jetton wallet ran the transfer but sent none from the sender');\n}\n\n/**\n * What one output did: failed (with why, and the deliveries the chain records it in), a\n * jetton leg to confirm, or delivered.\n */\ntype Outcome =\n | {\n readonly failed: string;\n readonly path: readonly Delivery[];\n readonly end: BounceEvidence['end'];\n }\n | { readonly leg: JettonLeg }\n | { readonly delivered: true };\n\n/** `tx`, which received `message`, as a delivery on a bounce's path. */\nconst delivery = (tx: V3Transaction, message: V3Message): Delivery => ({\n account: tx.account,\n lt: tx.lt,\n hash: tx.hash,\n message: message.hash,\n});\n\n/** The outcome of the output `sent` of our wallet `from`, checked against the chain. */\nfunction outcomeOf(trace: V3Trace, from: string, sent: Sent): Outcome {\n const { out, bounceable, jettonRecipient } = sent;\n const hop = receiver(trace, out, from);\n const first = delivery(hop, out);\n const hopRan = ran(hop);\n // A bounce phase exists only for a bounceable message, and always when its compute\n // phase failed (collator.cpp, transaction.cpp `bounce_enabled`). A bounce on a message\n // we signed non-bounceable would fail a delivery that credited the value; a failed\n // bounceable delivery without one lacks data. The flag we signed decides, even when the\n // indexer leaves the delivery's own flag out.\n if (\n (hop.inMsg?.bounce !== null && hop.inMsg?.bounce !== bounceable) ||\n (hop.bounce !== undefined && !bounceable) ||\n (bounceable && !hop.compute.success && hop.bounce === undefined)\n ) {\n throw inconsistent('the delivery contradicts the bounce flag we signed');\n }\n if (jettonRecipient === undefined) {\n // The value stays unless the bounce phase sent it back.\n return hop.bounce === 'ok'\n ? { failed: REASONS.bounced, path: [first], end: 'bounced' }\n : { delivered: true };\n }\n // The owner's jetton wallet ran `transfer` and sent `internal_transfer` onwards. A\n // failed phase dropped its state: the jettons never left.\n if (!hopRan) return { failed: REASONS.jettonBounced, path: [first], end: 'unran' };\n const arrivalMessage = onward(hop, from);\n if (!arrivalMessage) {\n return { failed: REASONS.jettonBounced, path: [first], end: 'unmoved' };\n }\n // TEP-74 707: the receiving wallet takes it only from the sender's jetton wallet.\n const arrival = receiver(trace, arrivalMessage, hop.account);\n // A failed phase drops the credit: the jettons came back, or never arrived.\n if (!ran(arrival)) {\n return {\n failed: REASONS.jettonBounced,\n path: [first, delivery(arrival, arrivalMessage)],\n end: 'unran',\n };\n }\n return {\n leg: {\n senderWallet: hop.account,\n recipientWallet: arrival.account,\n recipient: jettonRecipient,\n },\n };\n}\n\n/** The verdict on the Attempt whose wallet transaction is `root`, within `trace`. */\nexport function attemptVerdict(root: V3Transaction, trace: V3Trace | null): Verdict {\n if (!root.inMsg || root.inMsg.source !== null) {\n throw inconsistent('the attempt is not an external message');\n }\n if (!consumesSeqno(root)) return PENDING;\n if (!root.compute.success) return failed(REASONS.walletFailed);\n const sent = sentMessages(root);\n if (sent === 'threw') return failed(REASONS.walletFailed);\n if (sent === 'skipped') return failed(REASONS.skipped);\n if (!trace || !trace.complete) return PENDING;\n // Every output is checked before any decides, so an early failure never hides a later\n // contradiction.\n const outcomes = sent.map((each) => outcomeOf(trace, root.account, each));\n for (const outcome of outcomes) {\n if ('failed' in outcome) {\n const { account, lt, hash } = root;\n return failed(\n outcome.failed,\n Object.freeze({\n root: { account, lt, hash },\n path: outcome.path,\n end: outcome.end,\n }),\n );\n }\n }\n const legs = outcomes.flatMap((outcome) => ('leg' in outcome ? [outcome.leg] : []));\n return Object.freeze({ kind: 'success', legs });\n}\n"]}
|
|
@@ -3,6 +3,8 @@ export declare const SELECTORS: Readonly<{
|
|
|
3
3
|
balanceOf: "70a08231";
|
|
4
4
|
decimals: "313ce567";
|
|
5
5
|
symbol: "95d89b41";
|
|
6
|
+
/** Tether's `deprecated()`: `true` once `TetherToken` forwards to an upgraded contract. */
|
|
7
|
+
deprecated: "0e136b19";
|
|
6
8
|
}>;
|
|
7
9
|
/** `keccak256("Transfer(address,address,uint256)")`, without `0x`. */
|
|
8
10
|
export declare const TRANSFER_TOPIC = "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
|
|
@@ -20,6 +20,8 @@ exports.SELECTORS = Object.freeze({
|
|
|
20
20
|
balanceOf: '70a08231',
|
|
21
21
|
decimals: '313ce567',
|
|
22
22
|
symbol: '95d89b41',
|
|
23
|
+
/** Tether's `deprecated()`: `true` once `TetherToken` forwards to an upgraded contract. */
|
|
24
|
+
deprecated: '0e136b19',
|
|
23
25
|
});
|
|
24
26
|
/** `keccak256("Transfer(address,address,uint256)")`, without `0x`. */
|
|
25
27
|
exports.TRANSFER_TOPIC = 'ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abi.js","sourceRoot":"","sources":["../../../src/adapters/tron/abi.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"abi.js","sourceRoot":"","sources":["../../../src/adapters/tron/abi.ts"],"names":[],"mappings":";;;AAiCA,wCAKC;AAED,0CAEC;AAMD,gDAWC;AAGD,sCAGC;AAUD,oCAiBC;AAMD,8CAiBC;AAnHD;;;;GAIG;AACH,mDAA0D;AAC1D,iDAA6D;AAC7D,uCAAyC;AAE5B,QAAA,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC;IACrC,QAAQ,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AAI,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;QACjF,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,CAAC,KAAK,GAAG,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;AAC1E,CAAC","sourcesContent":["/**\n * The TRC-20 calls and events the driver uses, SDK-free: TRC-20 is ERC-20's ABI on the\n * TVM, with 20-byte addresses in ABI words (the `41` prefix dropped). Selectors are pinned\n * by a keccak-256 test.\n */\nimport { ValidationError } from '../../core/errors/error';\nimport { bytesToUtf8, fromHex } from '../../core/util/bytes';\nimport { toHexAddress } from './address';\n\nexport const SELECTORS = Object.freeze({\n transfer: 'a9059cbb',\n balanceOf: '70a08231',\n decimals: '313ce567',\n symbol: '95d89b41',\n /** Tether's `deprecated()`: `true` once `TetherToken` forwards to an upgraded contract. */\n deprecated: '0e136b19',\n});\n\n/** `keccak256(\"Transfer(address,address,uint256)\")`, without `0x`. */\nexport const TRANSFER_TOPIC =\n 'ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';\n\nconst UINT256_MAX = (1n << 256n) - 1n;\n\nfunction word(value: bigint): string {\n return value.toString(16).padStart(64, '0');\n}\n\nfunction addressWord(address: string): string {\n return toHexAddress(address).slice(2).padStart(64, '0');\n}\n\n/** An amount outside `uint256` is refused with a fixed text, never wrapped. */\nexport function encodeTransfer(to: string, amount: bigint): string {\n if (amount < 0n || amount > UINT256_MAX) {\n throw new ValidationError('INVALID_AMOUNT', 'amount does not fit in a uint256');\n }\n return `${SELECTORS.transfer}${addressWord(to)}${word(amount)}`;\n}\n\nexport function encodeBalanceOf(owner: string): string {\n return `${SELECTORS.balanceOf}${addressWord(owner)}`;\n}\n\n/**\n * The (to, amount) of `transfer(address,uint256)` call data built the canonical way (12\n * zero bytes before the address); `null` for anything else.\n */\nexport function decodeTransferCall(\n data: string,\n): { readonly to: string; readonly amount: bigint } | null {\n // A fixed length (selector + two words), checked before any other work, so a long\n // untrusted input costs one length check.\n if (data.length !== 136) return null;\n const hex = data.toLowerCase();\n if (!/^a9059cbb[0-9a-f]{128}$/.test(hex)) return null;\n const toWord = hex.slice(8, 72);\n if (!toWord.startsWith('0'.repeat(24))) return null;\n return { to: `41${toWord.slice(24)}`, amount: BigInt(`0x${hex.slice(72)}`) };\n}\n\n/** Throws on data that is not exactly one ABI `uint256` word. */\nexport function decodeUint256(data: string): bigint {\n if (!/^[0-9a-fA-F]{64}$/.test(data)) throw new TypeError('not one uint256 word');\n return BigInt(`0x${data}`);\n}\n\n/** One character class, no repeated group: linear on any input. */\nconst HEX_DIGITS = /^[0-9a-fA-F]+$/;\n\n/**\n * Throws on data that is not an ABI `string` (offset 32, length, padded UTF-8). The shape is\n * checked by length and one character class: a repeated-group regex overflows V8's stack\n * on a few million characters.\n */\nexport function decodeString(data: string): string {\n if (\n typeof data !== 'string' ||\n data.length < 128 ||\n data.length % 64 !== 0 ||\n !HEX_DIGITS.test(data)\n ) {\n throw new TypeError('not an ABI string');\n }\n if (BigInt(`0x${data.slice(0, 64)}`) !== 32n) throw new TypeError('bad string offset');\n const length = BigInt(`0x${data.slice(64, 128)}`);\n const available = BigInt((data.length - 128) / 2);\n if (length > available || available - length >= 32n) {\n throw new TypeError('bad string length');\n }\n const bytes = fromHex(data.slice(128, 128 + Number(length) * 2));\n return bytesToUtf8(bytes);\n}\n\n/**\n * A TRC-20 `Transfer` log's parties (`41…` hex) and amount; `null` for any other log. Tron\n * logs carry hex without `0x`, and `address` is the 20-byte emitter.\n */\nexport function decodeTransferLog(log: {\n readonly topics: readonly string[];\n readonly data: string;\n}): { readonly from: string; readonly to: string; readonly amount: bigint } | null {\n if (log.topics.length !== 3) return null;\n const [topic, from, to] = log.topics.map((t) => t.toLowerCase());\n if (topic !== TRANSFER_TOPIC) return null;\n const party = (value: string | undefined): string | null =>\n value !== undefined && /^0{24}[0-9a-f]{40}$/.test(value)\n ? `41${value.slice(24)}`\n : null;\n const sender = party(from);\n const recipient = party(to);\n if (sender === null || recipient === null || !/^[0-9a-fA-F]{64}$/.test(log.data)) {\n return null;\n }\n return { from: sender, to: recipient, amount: BigInt(`0x${log.data}`) };\n}\n"]}
|
|
@@ -272,14 +272,30 @@ function createTronBuilder(ctx) {
|
|
|
272
272
|
return (await api.block('full', undefined, (0, http_1.withSignal)(http_1.READ, signal)));
|
|
273
273
|
}
|
|
274
274
|
/**
|
|
275
|
-
* The simulated energy of a TRC-20 transfer, after the balance
|
|
276
|
-
*
|
|
277
|
-
* allows (a blacklist, say) is
|
|
275
|
+
* The simulated energy of a TRC-20 transfer, after the deprecation and balance checks: a
|
|
276
|
+
* deprecated token is `ASSET_RESOLUTION`; a shortfall is `INSUFFICIENT_FUNDS`, never a
|
|
277
|
+
* revert; a token that refuses a transfer its balance allows (a blacklist, say) is
|
|
278
|
+
* `INVALID_INTENT`.
|
|
279
|
+
*
|
|
280
|
+
* Tether's `TetherToken` (USDT) forwards a deprecated contract's `transfer` to its
|
|
281
|
+
* upgraded contract, which moves the value and emits the `Transfer` event, so the
|
|
282
|
+
* transfer simulates and executes, and the verdict, which reads the old contract's event,
|
|
283
|
+
* finds no evidence of it. So `deprecated()` is read beside the balance, once per
|
|
284
|
+
* estimate (the core estimates before every build), one endpoint's answer as for the
|
|
285
|
+
* other token reads here, not the proof quorum's: a `true` can only refuse before
|
|
286
|
+
* signing, the safe direction (as one endpoint's failed simulation already does), and a
|
|
287
|
+
* wrong `false` leaves the transfer where it was without the guard.
|
|
278
288
|
*/
|
|
279
289
|
async function tokenEnergy(p, signal) {
|
|
280
290
|
const tags = (0, http_1.withSignal)(http_1.READ, signal);
|
|
281
291
|
const token = p.token;
|
|
282
|
-
const available = await
|
|
292
|
+
const [deprecated, available] = await Promise.all([
|
|
293
|
+
(0, reader_1.trc20Deprecated)(ctx, token, tags),
|
|
294
|
+
(0, reader_1.trc20Balance)(ctx, token, p.owner, tags),
|
|
295
|
+
]);
|
|
296
|
+
if (deprecated) {
|
|
297
|
+
throw new error_1.ValidationError('ASSET_RESOLUTION', 'the token contract is deprecated in favour of an upgraded contract; the asset must be re-registered at the upgraded contract');
|
|
298
|
+
}
|
|
283
299
|
if (available < p.amount) {
|
|
284
300
|
throw new error_1.ChainError('INSUFFICIENT_FUNDS', 'insufficient token balance for this transfer', { details: { required: p.amount.toString(), available: available.toString() } });
|
|
285
301
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builder.js","sourceRoot":"","sources":["../../../src/adapters/tron/builder.ts"],"names":[],"mappings":";;AA2TA,kCAEC;AA0BD,8CAiVC;AAxqBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,iDAA8C;AAO9C,mDAOiC;AACjC,kDAA+D;AAK/D,yDAA6D;AAC7D,iDAO+B;AAC/B,+BAA2D;AAC3D,uCAA+D;AAC/D,qCAA2D;AAC3D,iCAA0D;AAC1D,iCAAsF;AACtF,uCAKmB;AACnB,qCAAyE;AASzE,6DAA6D;AAC7D,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;AACjD,wFAAwF;AACxF,MAAM,cAAc,GAAG,oBAAoB,CAAC;AAC5C,mEAAmE;AACnE,MAAM,UAAU,GAAG,gBAAgB,CAAC;AAmBpC,SAAS,OAAO,CAAC,OAAe;IAC9B,OAAO,IAAI,uBAAe,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC;AACxD,CAAC;AAED;;;GAGG;AACH,MAAM,SAAS,GAAiB,EAAE,GAAG,WAAI,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;AAE7D,uFAAuF;AACvF,SAAS,OAAO,CAAC,IAAwB;IACvC,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAC9D,MAAM,OAAO,GAAG,GAAG,EAAE,CA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AC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBACnE,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACtD,CAAC,CAAC;YACH,yFAAyF;YACzF,iEAAiE;YACjE,OAAO,IAAA,6BAAoB,EAAC,MAAM,EAAE,IAAA,kBAAS,EAAC,GAAG,CAAC,CAAC,CAAC;QACtD,CAAC;KACF,CAAC;IAEF,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC;AAClC,CAAC","sourcesContent":["/**\n * The Tron `TxBuilder` and `Broadcaster`. One output (TRX or TRC-20), an optional memo in\n * `raw_data.data`, `expiry` ordering (`expiresAtMs`), one `secp256k1-ecdsa` digest request\n * over the txID, and the txID as the Attempt ref, known before signing.\n *\n * Reference block and expiration: the reference is the head block (TaPoS), and the\n * transaction expires `expirationMs` after the earlier of the head's time and the local\n * clock, as tronweb does from the head. A head older than half the window is refused\n * (retryable) instead of producing a transaction that is born nearly expired, and so is a\n * head dated more than half the window ahead of the local clock (a clock behind the chain\n * would build transactions born expired); a head dated less far in the future cannot push\n * the expiration beyond the window from now. The ordering records the signed expiration and\n * the reference block's TaPoS bound (`lastValidHeight`: its height, read from its id, plus\n * `TAPOS_WINDOW`), so the negative inclusion proof scans from the attested reference block\n * up to the expiration, whatever the head or the clock claimed: a floor derived from the\n * clock could sit above the block that holds the transaction. The expiration stays inside\n * java-tron's own window (at least the next slot, at most 24 h past its head).\n *\n * Uniqueness: Tron has no nonce, so two identical transfers built on the same head in\n * the same millisecond would share one txID and one on-chain effect. The core refuses an\n * Attempt whose ref another Operation holds; as defense in depth, each build takes a\n * `timestamp` strictly above the previous one from this driver, plus crypto-random offsets\n * on `timestamp` (up to +999 ms) and `expiration` (up to −999 ms); java-tron never\n * validates `raw_data.timestamp`.\n *\n * Nothing is signed before the built bytes are decoded back and shown to carry exactly the\n * intent: owner, recipient, amount, token contract, canonical `transfer(to, amount)` call\n * data with no value, memo, expiration and fee limit. `assemble` checks the same against the\n * stored summary, ordering and fee limit, so the signature goes out only with the transfer\n * that was authorized.\n *\n * Broadcasts are classified here (`classifyOwnBroadcast`), never under a quorum: a transport\n * failure, an unreadable reply or a node answer that may follow pooling is thrown ambiguous\n * (possibly sent). A node's rejection is a claim: it stands only when its reason\n * holds for the bytes that were sent, read back from them; otherwise it is a refusal. A\n * `TX_EXPIRED` refusal is the node's view at its own head, a hint and not proof: Tron has no\n * nonce, so a second Attempt could land beside the first. The broadcaster never re-sends or\n * rebuilds on it; only an attested expiry (the proofs) lets the core build again.\n */\nimport { sha256 } from '@noble/hashes/sha256';\nimport type {\n Broadcaster,\n BuildContext,\n TxBuilder,\n WalletKey,\n} from '../../core/driver/types';\nimport {\n ChainError,\n ConfigError,\n ProviderError,\n SigningError,\n UnsupportedCapabilityError,\n ValidationError,\n} from '../../core/errors/error';\nimport { assetId, parseAssetId } from '../../core/model/asset';\nimport type { FeeEstimateDraft } from '../../core/model/fee';\nimport type { DriverIntent, IntentSummary } from '../../core/model/intent';\nimport type { OrderingData } from '../../core/model/ordering';\nimport type { UnsignedTx } from '../../core/model/transaction';\nimport { secp256k1Ecdsa } from '../../core/registry/schemes';\nimport {\n bytesToUtf8,\n concatBytes,\n fromHex,\n randomBytes,\n toHex,\n utf8ToBytes,\n} from '../../core/util/bytes';\nimport { decodeTransferCall, encodeTransfer } from './abi';\nimport { addressFromPublicKey, toHexAddress } from './address';\nimport { classifyOwnBroadcast, txBytesOf } from './errors';\nimport { feeLimitCeiling, feeSun, tronFee } from './fees';\nimport { BROADCAST, READ, malformed, withSignal, type TronBlockHeader } from './http';\nimport {\n MAX_EXPIRATION_MS,\n MAX_MEMO_BYTES,\n MIN_EXPIRATION_MS,\n TAPOS_WINDOW,\n} from './network';\nimport { trc20Balance, trc20Contract, type TronContext } from './reader';\nimport type {\n TronCallTags,\n TronContract,\n TronExpiryOrdering,\n TronFeeDetails,\n TronRawData,\n} from './types';\n\n/** The largest `int64` the codec writes from a JS number. */\nconst MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);\n/** A positive base-unit amount in a stored summary: at most a `uint256` (78 digits). */\nconst SUMMARY_AMOUNT = /^[1-9][0-9]{0,77}$/;\n/** Linear on any input: one character class, no repeated group. */\nconst HEX_DIGITS = /^[0-9a-fA-F]+$/;\n\n/** What the signed bytes must carry; addresses are lower-case `41…` hex. */\ninterface Transfer {\n readonly owner: string;\n readonly recipient: string;\n readonly amount: bigint;\n /** The TRC-20 contract, absent for TRX. */\n readonly token?: string;\n /** The memo bytes, lower-case hex; absent without a memo. */\n readonly memo?: string;\n}\n\ninterface Prepared extends Transfer {\n /** The recipient as the intent gives it (the summary's form). */\n readonly to: string;\n readonly contract: TronContract;\n}\n\nfunction invalid(message: string): ValidationError {\n return new ValidationError('INVALID_INTENT', message);\n}\n\n/**\n * Whether an address holds a contract, read under the proof quorum: a node's word\n * alone must not refuse a valid transfer, and endpoints that disagree decide nothing.\n */\nconst CONFIRMED: TronCallTags = { ...READ, quorum: 'proof' };\n\n/** The memo's UTF-8 bytes as hex, or undefined; refused when over `MAX_MEMO_BYTES`. */\nfunction memoHex(memo: string | undefined): string | undefined {\n if (memo === undefined || memo.length === 0) return undefined;\n const tooLong = () => invalid(`a Tron memo is at most ${MAX_MEMO_BYTES} UTF-8 bytes`);\n // Each UTF-16 unit is at least one UTF-8 byte, so a longer string is refused unencoded.\n if (memo.length > MAX_MEMO_BYTES) throw tooLong();\n const bytes = utf8ToBytes(memo);\n if (bytes.length > MAX_MEMO_BYTES) throw tooLong();\n // A lone surrogate would be written as U+FFFD: the chain would carry another memo.\n if (bytesToUtf8(bytes) !== memo) throw invalid('a Tron memo must be well-formed text');\n return toHex(bytes);\n}\n\n/**\n * The validated transfer, before any I/O: one output, a positive amount, TRX or TRC-20,\n * valid addresses, a memo within bounds, amounts the encoders can write exactly (a TRX\n * transfer above 2^53 − 1 sun must be split), and TRX never to the sender (java-tron:\n * \"Cannot transfer TRX to yourself.\", for the bytes alone). A TRC-20 transfer to the\n * sender is valid on chain and is allowed.\n */\nfunction prepare(intent: DriverIntent): Prepared {\n const output = intent.outputs[0];\n if (!output || intent.outputs.length !== 1) {\n throw invalid('a Tron transfer has exactly one output');\n }\n if (output.amount <= 0n) {\n throw new ValidationError('INVALID_AMOUNT', 'the amount must be positive');\n }\n const token = intent.asset === 'native' ? undefined : trc20Contract(intent.asset);\n const owner = toHexAddress(intent.from);\n const recipient = toHexAddress(output.to);\n const memo = memoHex(intent.memo);\n let contract: TronContract;\n if (token === undefined) {\n if (output.amount > MAX_SAFE) {\n throw new ValidationError(\n 'INVALID_AMOUNT',\n 'a TRX amount must be at most the largest safe integer of sun',\n );\n }\n if (recipient === owner) throw invalid('a TRX transfer cannot go to its sender');\n contract = { type: 'TransferContract', owner, to: recipient, amount: output.amount };\n } else {\n // encodeTransfer refuses an amount outside uint256 (INVALID_AMOUNT).\n const data = encodeTransfer(recipient, output.amount);\n contract = { type: 'TriggerSmartContract', owner, contract: token, data };\n }\n return {\n to: output.to,\n amount: output.amount,\n owner,\n recipient,\n contract,\n ...(token !== undefined ? { token } : {}),\n ...(memo !== undefined ? { memo } : {}),\n };\n}\n\n/**\n * Whether decoded raw data carries exactly `t`. A TRC-20 call must be the canonical\n * `transfer(to, amount)` (selector, zero-padded recipient, one amount word, nothing more)\n * with no TRX or TRC-10 value: the verdict reads only that shape.\n */\nfunction carries(raw: TronRawData, t: Transfer): boolean {\n const c = raw.contract;\n if (c.owner !== t.owner || raw.data !== t.memo) return false;\n if (t.token === undefined) {\n return c.type === 'TransferContract' && c.to === t.recipient && c.amount === t.amount;\n }\n if (c.type !== 'TriggerSmartContract' || c.contract !== t.token) return false;\n if (\n c.callValue !== undefined ||\n c.callTokenValue !== undefined ||\n c.tokenId !== undefined\n ) {\n return false;\n }\n const call = decodeTransferCall(c.data);\n return call !== null && call.to === t.recipient && call.amount === t.amount;\n}\n\n/** The transfer a stored summary describes, signed by `owner`; null when it describes none. */\nfunction summaryTransfer(\n ctx: TronContext,\n summary: IntentSummary,\n owner: string,\n): Transfer | null {\n try {\n const { chain, network, ref } = parseAssetId(summary.asset);\n const output = summary.outputs[0];\n if (\n chain !== ctx.chain.id ||\n network !== ctx.network.id ||\n !output ||\n summary.outputs.length !== 1 ||\n !SUMMARY_AMOUNT.test(output.amount)\n ) {\n return null;\n }\n const token = ref === 'native' ? undefined : trc20Contract(ref);\n const memo = memoHex(summary.memo);\n return {\n owner,\n recipient: toHexAddress(output.to),\n amount: BigInt(output.amount),\n ...(token !== undefined ? { token } : {}),\n ...(memo !== undefined ? { memo } : {}),\n };\n } catch {\n return null;\n }\n}\n\n/**\n * The fee fields a build writes, from this transfer's own `tron` estimate: the bandwidth\n * the estimate covers and, for TRC-20 only, a positive fee limit within the handle's\n * `maxFeeLimit`, wherever the estimate came from. The limit is handed to the codec\n * as a number and its `safe()` refuses one it cannot hold exactly: it is never\n * rounded into the bytes.\n */\nfunction feeFields(\n fee: FeeEstimateDraft,\n p: Prepared,\n maxFeeLimit: bigint,\n): { readonly bandwidth: bigint; readonly feeLimit?: number } {\n const details = fee.details as Partial<TronFeeDetails>;\n const mismatch = () =>\n invalid('the fee estimate is not a Tron estimate for this transfer');\n if (\n fee.kind !== 'tron' ||\n typeof details.bandwidth !== 'bigint' ||\n details.bandwidth <= 0n\n ) {\n throw mismatch();\n }\n if (p.token === undefined) {\n if (details.feeLimit !== undefined) throw mismatch();\n return { bandwidth: details.bandwidth };\n }\n if (typeof details.feeLimit !== 'bigint' || details.feeLimit <= 0n) throw mismatch();\n if (details.feeLimit > maxFeeLimit) {\n throw invalid(\n 'the fee limit is above maxFeeLimit, the Tron handle option that bounds it (in sun)',\n );\n }\n return { bandwidth: details.bandwidth, feeLimit: Number(details.feeLimit) };\n}\n\n/** The sender's own key: a signature from any other key would not authorize the owner. */\nfunction signingKey(keys: readonly WalletKey[], owner: string): WalletKey {\n for (const key of keys) {\n if (key.scheme !== 'secp256k1-ecdsa') continue;\n try {\n if (toHexAddress(addressFromPublicKey(key.publicKey)) === owner) return key;\n } catch {\n // Not a secp256k1 point: not this sender's key.\n }\n }\n throw new SigningError(\n 'SIGNER_UNAVAILABLE',\n 'no secp256k1 key for the sending address',\n );\n}\n\nfunction varint(value: number): Uint8Array {\n const out: number[] = [];\n let v = value;\n do {\n let byte = v & 0x7f;\n v = Math.floor(v / 128);\n if (v > 0) byte |= 0x80;\n out.push(byte);\n } while (v > 0);\n return Uint8Array.from(out);\n}\n\n/** `Transaction { raw raw_data = 1; repeated bytes signature = 2; }` with one signature. */\nfunction signedTransaction(raw: Uint8Array, signature: Uint8Array): Uint8Array {\n return concatBytes(\n Uint8Array.of(0x0a),\n varint(raw.length),\n raw,\n Uint8Array.of(0x12),\n varint(signature.length),\n signature,\n );\n}\n\n/**\n * java-tron's bandwidth for a transaction whose `raw_data` is `rawBytes` long\n * (`BandwidthProcessor.consume`): the signed size without `ret` (field 1 with its length and\n * the raw bytes, field 2 with its length and one 65-byte signature) plus 64 result bytes.\n */\nexport function bandwidthOf(rawBytes: number): bigint {\n return BigInt(1 + varint(rawBytes).length + rawBytes + 2 + 65 + 64);\n}\n\n/** A crypto-random integer in [0, 1000). */\nfunction jitter(): number {\n const bytes = randomBytes(2);\n return (((bytes[0] as number) << 8) | (bytes[1] as number)) % 1000;\n}\n\nconst expiresAt = (ordering: OrderingData): number | undefined =>\n ordering.kind === 'expiry' ? ordering.expiresAtMs : undefined;\n\n/**\n * Whether an ordering names the signed reference block: a reference height\n * (`lastValidHeight − TAPOS_WINDOW`) whose bytes 6..8 are the signed `ref_block_bytes`, and\n * the signed `ref_block_hash` itself. The proofs trust the height only with the hash.\n */\nfunction boundToReference(ordering: OrderingData, raw: TronRawData): boolean {\n if (ordering.kind !== 'expiry') return false;\n const { lastValidHeight: last, refBlockHash } = ordering as Partial<TronExpiryOrdering>;\n if (typeof last !== 'bigint' || last < TAPOS_WINDOW) return false;\n return (\n ((last - TAPOS_WINDOW) & 0xffffn) === BigInt(`0x${raw.refBlockBytes}`) &&\n refBlockHash === raw.refBlockHash\n );\n}\n\nexport function createTronBuilder(ctx: TronContext): {\n readonly builder: TxBuilder;\n readonly broadcaster: Broadcaster;\n} {\n const { api, codec, config } = ctx;\n let lastTimestamp = 0;\n\n const refFields = (head: TronBlockHeader) => ({\n refBlockBytes: head.id.slice(12, 16),\n refBlockHash: head.id.slice(16, 32),\n });\n\n async function head(signal?: AbortSignal): Promise<TronBlockHeader> {\n // `block` throws a malformed answer rather than return no head.\n return (await api.block(\n 'full',\n undefined,\n withSignal(READ, signal),\n )) as TronBlockHeader;\n }\n\n /**\n * The simulated energy of a TRC-20 transfer, after the balance check: a shortfall is\n * `INSUFFICIENT_FUNDS`, never a revert; a token that refuses a transfer its balance\n * allows (a blacklist, say) is `INVALID_INTENT`.\n */\n async function tokenEnergy(p: Prepared, signal?: AbortSignal): Promise<bigint> {\n const tags = withSignal(READ, signal);\n const token = p.token as string;\n const available = await trc20Balance(ctx, token, p.owner, tags);\n if (available < p.amount) {\n throw new ChainError(\n 'INSUFFICIENT_FUNDS',\n 'insufficient token balance for this transfer',\n { details: { required: p.amount.toString(), available: available.toString() } },\n );\n }\n const data = (p.contract as Extract<TronContract, { type: 'TriggerSmartContract' }>)\n .data;\n const call = await api.constantCall(p.owner, token, data, tags);\n if (call.kind === 'no-contract') {\n // Its balanceOf just answered: two reads disagree, which decides nothing.\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n 'the node both holds and lacks this token contract',\n { retryable: true },\n );\n }\n if (call.kind === 'failed') throw invalid('the token contract refuses this transfer');\n return call.energy;\n }\n\n const builder: TxBuilder = {\n async estimateFee(intent, build: BuildContext) {\n const p = prepare(intent);\n const tags = withSignal(READ, build.signal);\n const [params, resources, block, recipient, energy] = await Promise.all([\n api.chainParameters(tags),\n api.resources(p.owner, tags),\n head(build.signal),\n p.token === undefined ? api.account(p.recipient, tags) : undefined,\n p.token === undefined ? undefined : tokenEnergy(p, build.signal),\n ]);\n // Where the chain forbids TRX to a contract, such a transfer is refused before\n // signing (it would only be refused, stall and expire). Elsewhere it is valid on\n // chain: the flag is 0 on mainnet, Nile and Shasta.\n // Known gap: the flag is one endpoint's word, read without a quorum, so a false 1\n // refuses a valid transfer before signing and a false 0 lets the chain refuse it;\n // liveness only, never a wrong payment.\n if (\n p.token === undefined &&\n params.forbidTransferToContract &&\n (await api.contractExists(p.recipient, withSignal(CONFIRMED, build.signal)))\n ) {\n throw invalid(\n 'this network refuses TRX sent to a contract (getForbidTransferToContract)',\n );\n }\n // An upper bound of the built size: no expiration jitter, a later timestamp, and the\n // largest fee limit a build can carry (the ceiling `tronFee` applies).\n const now = ctx.clock.now();\n const ceiling = feeLimitCeiling(params, config.maxFeeLimit).value;\n const provisional = codec.encodeRaw({\n ...refFields(block),\n expiration: Math.min(block.timestamp, now) + config.expirationMs,\n timestamp: Math.max(now + 1_000, lastTimestamp + 1),\n ...(p.token !== undefined ? { feeLimit: Number(ceiling) } : {}),\n ...(p.memo !== undefined ? { data: p.memo } : {}),\n contract: p.contract,\n });\n return tronFee({\n fee: intent.fee,\n params,\n resources,\n bandwidth: bandwidthOf(provisional.length / 2),\n activation: recipient !== undefined && !recipient.exists,\n memo: p.memo !== undefined,\n ...(energy !== undefined ? { energy } : {}),\n marginPercent: config.energyMarginPercent,\n maxFeeLimit: config.maxFeeLimit,\n });\n },\n\n async checkFunds(intent, fee, build) {\n const p = prepare(intent);\n const tags = withSignal(READ, build.signal);\n const [account, tokens] = await Promise.all([\n api.account(p.owner, tags),\n p.token === undefined ? undefined : trc20Balance(ctx, p.token, p.owner, tags),\n ]);\n if (tokens !== undefined && tokens < p.amount) {\n return { ok: false, asset: intent.asset, required: p.amount, available: tokens };\n }\n const required = feeSun(fee) + (p.token === undefined ? p.amount : 0n);\n // An account that was never activated has no free bandwidth and cannot send.\n return account.exists && account.balance >= required\n ? { ok: true }\n : { ok: false, asset: 'native', required, available: account.balance };\n },\n\n async build(intent, fee, build): Promise<UnsignedTx> {\n const p = prepare(intent);\n const key = signingKey(build.keys, p.owner);\n const fees = feeFields(fee, p, config.maxFeeLimit);\n const block = await head(build.signal);\n const now = ctx.clock.now();\n if (now - block.timestamp > config.expirationMs / 2) {\n throw new ProviderError(\n 'PROVIDER_UNAVAILABLE',\n 'the head block is too old to reference; try again',\n );\n }\n // A head dated more than half the window ahead means a local clock behind\n // the chain, whose every build would be born expired (and cost a signature per\n // rebuild), or a lying endpoint. Either way nothing is built on it.\n if (block.timestamp - now > config.expirationMs / 2) {\n throw new ProviderError(\n 'PROVIDER_UNAVAILABLE',\n 'the head block is dated ahead of the local clock; check the clock or try again',\n );\n }\n // The reference block's height, from its id (java-tron's block id is the\n // height's 8 bytes followed by 24 bytes of the header hash, `generateBlockId`): the\n // same bytes TaPoS reads. A head whose id and number disagree is not a block.\n const reference = BigInt(`0x${block.id.slice(0, 16)}`);\n if (reference !== block.number) throw malformed('head block id');\n const anchor = Math.min(block.timestamp, now);\n const expiration = anchor + config.expirationMs - jitter();\n // The window stays within MAX_EXPIRATION_MS, and java-tron wants at least the next\n // slot. The network config bounds the window; this holds it.\n if (expiration - anchor > MAX_EXPIRATION_MS) {\n throw new ConfigError(\n 'CONFIG_INVALID',\n 'the expiration window exceeds the maximum',\n );\n }\n if (expiration - anchor < MIN_EXPIRATION_MS - 1_000) {\n throw new ConfigError(\n 'CONFIG_INVALID',\n 'the expiration window is below the minimum',\n );\n }\n const timestamp = Math.max(now + jitter(), lastTimestamp + 1);\n lastTimestamp = timestamp;\n const raw: TronRawData = {\n ...refFields(block),\n expiration,\n timestamp,\n ...(fees.feeLimit !== undefined ? { feeLimit: fees.feeLimit } : {}),\n ...(p.memo !== undefined ? { data: p.memo } : {}),\n contract: p.contract,\n };\n const payload = codec.encodeRaw(raw);\n // Before anything is signed: the bytes decode strictly to exactly this transfer.\n let built: TronRawData | undefined;\n try {\n built = codec.decodeRaw(payload);\n } catch {\n built = undefined;\n }\n if (\n !built ||\n !carries(built, p) ||\n built.expiration !== expiration ||\n built.feeLimit !== raw.feeLimit\n ) {\n throw invalid('the built transaction does not carry this transfer');\n }\n if (bandwidthOf(payload.length / 2) > fees.bandwidth) {\n throw invalid(\"the fee estimate does not cover this transaction's bandwidth\");\n }\n const txId = toHex(sha256(fromHex(payload)));\n // The negative proof scans from the reference block to the signed expiration; the\n // height is the head's claim, so the signed hash bytes go with it, and the proof\n // trusts the height only where the attested block carries them.\n const ordering: TronExpiryOrdering = {\n kind: 'expiry',\n expiresAtMs: expiration,\n lastValidHeight: reference + TAPOS_WINDOW,\n refBlockHash: raw.refBlockHash,\n };\n return {\n payload: { encoding: 'hex', data: payload },\n expectedRef: { id: txId, idKind: 'tx-hash', canonical: true },\n signingRequests: [\n {\n id: 'r0',\n scheme: 'secp256k1-ecdsa',\n payload: fromHex(txId),\n payloadKind: 'digest',\n publicKey: key.publicKey,\n ...(key.keyRef ? { keyRef: key.keyRef } : {}),\n },\n ],\n ordering,\n fee,\n summary: {\n asset: assetId(ctx.chain.id, ctx.network.id, intent.asset),\n outputs: [{ to: p.to, amount: p.amount.toString() }],\n ...(intent.memo !== undefined ? { memo: intent.memo } : {}),\n },\n };\n },\n\n async assemble(unsigned, signatures) {\n const fail = (message: string) => new SigningError('SIGNING_FAILED', message);\n const request = unsigned.signingRequests[0];\n const signature = signatures.find((s) => s.requestId === 'r0');\n if (\n !request ||\n request.id !== 'r0' ||\n unsigned.signingRequests.length !== 1 ||\n !signature ||\n signature.bytes.length !== 64 ||\n (signature.recovery !== 0 && signature.recovery !== 1)\n ) {\n throw fail('missing or malformed signature for request r0');\n }\n const mismatch = () => fail('the unsigned payload does not match its txID');\n if (unsigned.payload.encoding !== 'hex') throw mismatch();\n let raw: Uint8Array;\n try {\n raw = fromHex(unsigned.payload.data);\n } catch {\n throw mismatch();\n }\n const txId = toHex(sha256(raw));\n if (txId !== toHex(request.payload) || txId !== unsigned.expectedRef?.id) {\n throw mismatch();\n }\n // The stored bytes decode strictly, and their owner is the signing key's\n // account, so a signature never authorizes another account's transaction.\n let decoded: TronRawData;\n try {\n decoded = codec.decodeRaw(unsigned.payload.data);\n } catch {\n throw fail('the unsigned payload is not a Tron transfer');\n }\n let signer: string;\n try {\n signer = toHexAddress(addressFromPublicKey(request.publicKey));\n } catch {\n throw fail('the signing request has no valid public key');\n }\n if (decoded.contract.owner !== signer) {\n throw fail(\"the payload's owner is not the signing key's account\");\n }\n // Only a signature the node will take for the owner's goes out, low s and\n // recovery bit included, as the core's scheme checks it; a signer fault is a signing\n // failure here, never a refusal on chain.\n if (\n !secp256k1Ecdsa.verify({\n publicKey: request.publicKey,\n payload: fromHex(txId),\n signature: signature.bytes,\n recovery: signature.recovery,\n })\n ) {\n throw fail('the signature does not verify against the signing key');\n }\n // The bytes carry the authorized summary; the proofs read the expiration and the\n // reference height from the ordering; only the named fee field is read (the core may\n // add others).\n const expected = summaryTransfer(ctx, unsigned.summary, signer);\n const feeLimit = (unsigned.fee.details as Partial<TronFeeDetails>).feeLimit;\n if (\n !expected ||\n !carries(decoded, expected) ||\n expiresAt(unsigned.ordering) !== decoded.expiration ||\n !boundToReference(unsigned.ordering, decoded) ||\n unsigned.fee.kind !== 'tron' ||\n (expected.token === undefined\n ? decoded.feeLimit !== undefined\n : typeof feeLimit !== 'bigint' ||\n decoded.feeLimit === undefined ||\n BigInt(decoded.feeLimit) !== feeLimit)\n ) {\n throw fail(\n 'the unsigned payload does not match its summary, expiry or fee limit',\n );\n }\n const sig = concatBytes(signature.bytes, Uint8Array.of(27 + signature.recovery));\n return {\n raw: { encoding: 'hex', data: toHex(signedTransaction(raw, sig)) },\n ref: { id: txId, idKind: 'tx-hash', canonical: true },\n };\n },\n };\n\n const broadcaster: Broadcaster = {\n async broadcast(signed, options = {}) {\n const { raw } = signed;\n if (\n raw.encoding !== 'hex' ||\n typeof raw.data !== 'string' ||\n raw.data.length % 2 !== 0 ||\n !HEX_DIGITS.test(raw.data)\n ) {\n throw new UnsupportedCapabilityError(\n 'UNSUPPORTED_CAPABILITY',\n 'Tron broadcasts take the signed transaction as hex',\n );\n }\n // The broadcast tags carry no quorum: one node's answer is classified, never compared.\n const hex = raw.data.toLowerCase();\n const answer = await api.broadcastHex(hex, {\n ...BROADCAST,\n ...(options.fanout !== undefined ? { fanout: options.fanout } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n // Inside the broadcaster, so a possibly-sent throw reaches the engine's recordAmbiguous.\n // A rejection stands only when its reason holds for these bytes.\n return classifyOwnBroadcast(answer, txBytesOf(hex));\n },\n };\n\n return { builder, broadcaster };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"builder.js","sourceRoot":"","sources":["../../../src/adapters/tron/builder.ts"],"names":[],"mappings":";;AA2TA,kCAEC;AA0BD,8CAoWC;AA3rBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,iDAA8C;AAO9C,mDAOiC;AACjC,kDAA+D;AAK/D,yDAA6D;AAC7D,iDAO+B;AAC/B,+BAA2D;AAC3D,uCAA+D;AAC/D,qCAA2D;AAC3D,iCAA0D;AAC1D,iCAAsF;AACtF,uCAKmB;AACnB,qCAA0F;AAS1F,6DAA6D;AAC7D,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;AACjD,wFAAwF;AACxF,MAAM,cAAc,GAAG,oBAAoB,CAAC;AAC5C,mEAAmE;AACnE,MAAM,UAAU,GAAG,gBAAgB,CAAC;AAmBpC,SAAS,OAAO,CAAC,OAAe;IAC9B,OAAO,IAAI,uBAAe,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC;AACxD,CAAC;AAED;;;GAGG;AACH,MAAM,SAAS,GAAiB,EAAE,GAAG,WAAI,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;AAE7D,uFAAuF;AACvF,SAAS,OAAO,CAAC,IAAwB;IACvC,IAAI,IAAI,KAAK,S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AC,GAAG,CAAC,IAAI,CAAC,EAC1B,CAAC;gBACD,MAAM,IAAI,kCAA0B,CAClC,wBAAwB,EACxB,oDAAoD,CACrD,CAAC;YACJ,CAAC;YACD,uFAAuF;YACvF,MAAM,GAAG,GAAG,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;YACnC,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,YAAY,CAAC,GAAG,EAAE;gBACzC,GAAG,gBAAS;gBACZ,GAAG,CAAC,OAAO,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBACnE,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACtD,CAAC,CAAC;YACH,yFAAyF;YACzF,iEAAiE;YACjE,OAAO,IAAA,6BAAoB,EAAC,MAAM,EAAE,IAAA,kBAAS,EAAC,GAAG,CAAC,CAAC,CAAC;QACtD,CAAC;KACF,CAAC;IAEF,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC;AAClC,CAAC","sourcesContent":["/**\n * The Tron `TxBuilder` and `Broadcaster`. One output (TRX or TRC-20), an optional memo in\n * `raw_data.data`, `expiry` ordering (`expiresAtMs`), one `secp256k1-ecdsa` digest request\n * over the txID, and the txID as the Attempt ref, known before signing.\n *\n * Reference block and expiration: the reference is the head block (TaPoS), and the\n * transaction expires `expirationMs` after the earlier of the head's time and the local\n * clock, as tronweb does from the head. A head older than half the window is refused\n * (retryable) instead of producing a transaction that is born nearly expired, and so is a\n * head dated more than half the window ahead of the local clock (a clock behind the chain\n * would build transactions born expired); a head dated less far in the future cannot push\n * the expiration beyond the window from now. The ordering records the signed expiration and\n * the reference block's TaPoS bound (`lastValidHeight`: its height, read from its id, plus\n * `TAPOS_WINDOW`), so the negative inclusion proof scans from the attested reference block\n * up to the expiration, whatever the head or the clock claimed: a floor derived from the\n * clock could sit above the block that holds the transaction. The expiration stays inside\n * java-tron's own window (at least the next slot, at most 24 h past its head).\n *\n * Uniqueness: Tron has no nonce, so two identical transfers built on the same head in\n * the same millisecond would share one txID and one on-chain effect. The core refuses an\n * Attempt whose ref another Operation holds; as defense in depth, each build takes a\n * `timestamp` strictly above the previous one from this driver, plus crypto-random offsets\n * on `timestamp` (up to +999 ms) and `expiration` (up to −999 ms); java-tron never\n * validates `raw_data.timestamp`.\n *\n * Nothing is signed before the built bytes are decoded back and shown to carry exactly the\n * intent: owner, recipient, amount, token contract, canonical `transfer(to, amount)` call\n * data with no value, memo, expiration and fee limit. `assemble` checks the same against the\n * stored summary, ordering and fee limit, so the signature goes out only with the transfer\n * that was authorized.\n *\n * Broadcasts are classified here (`classifyOwnBroadcast`), never under a quorum: a transport\n * failure, an unreadable reply or a node answer that may follow pooling is thrown ambiguous\n * (possibly sent). A node's rejection is a claim: it stands only when its reason\n * holds for the bytes that were sent, read back from them; otherwise it is a refusal. A\n * `TX_EXPIRED` refusal is the node's view at its own head, a hint and not proof: Tron has no\n * nonce, so a second Attempt could land beside the first. The broadcaster never re-sends or\n * rebuilds on it; only an attested expiry (the proofs) lets the core build again.\n */\nimport { sha256 } from '@noble/hashes/sha256';\nimport type {\n Broadcaster,\n BuildContext,\n TxBuilder,\n WalletKey,\n} from '../../core/driver/types';\nimport {\n ChainError,\n ConfigError,\n ProviderError,\n SigningError,\n UnsupportedCapabilityError,\n ValidationError,\n} from '../../core/errors/error';\nimport { assetId, parseAssetId } from '../../core/model/asset';\nimport type { FeeEstimateDraft } from '../../core/model/fee';\nimport type { DriverIntent, IntentSummary } from '../../core/model/intent';\nimport type { OrderingData } from '../../core/model/ordering';\nimport type { UnsignedTx } from '../../core/model/transaction';\nimport { secp256k1Ecdsa } from '../../core/registry/schemes';\nimport {\n bytesToUtf8,\n concatBytes,\n fromHex,\n randomBytes,\n toHex,\n utf8ToBytes,\n} from '../../core/util/bytes';\nimport { decodeTransferCall, encodeTransfer } from './abi';\nimport { addressFromPublicKey, toHexAddress } from './address';\nimport { classifyOwnBroadcast, txBytesOf } from './errors';\nimport { feeLimitCeiling, feeSun, tronFee } from './fees';\nimport { BROADCAST, READ, malformed, withSignal, type TronBlockHeader } from './http';\nimport {\n MAX_EXPIRATION_MS,\n MAX_MEMO_BYTES,\n MIN_EXPIRATION_MS,\n TAPOS_WINDOW,\n} from './network';\nimport { trc20Balance, trc20Contract, trc20Deprecated, type TronContext } from './reader';\nimport type {\n TronCallTags,\n TronContract,\n TronExpiryOrdering,\n TronFeeDetails,\n TronRawData,\n} from './types';\n\n/** The largest `int64` the codec writes from a JS number. */\nconst MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);\n/** A positive base-unit amount in a stored summary: at most a `uint256` (78 digits). */\nconst SUMMARY_AMOUNT = /^[1-9][0-9]{0,77}$/;\n/** Linear on any input: one character class, no repeated group. */\nconst HEX_DIGITS = /^[0-9a-fA-F]+$/;\n\n/** What the signed bytes must carry; addresses are lower-case `41…` hex. */\ninterface Transfer {\n readonly owner: string;\n readonly recipient: string;\n readonly amount: bigint;\n /** The TRC-20 contract, absent for TRX. */\n readonly token?: string;\n /** The memo bytes, lower-case hex; absent without a memo. */\n readonly memo?: string;\n}\n\ninterface Prepared extends Transfer {\n /** The recipient as the intent gives it (the summary's form). */\n readonly to: string;\n readonly contract: TronContract;\n}\n\nfunction invalid(message: string): ValidationError {\n return new ValidationError('INVALID_INTENT', message);\n}\n\n/**\n * Whether an address holds a contract, read under the proof quorum: a node's word\n * alone must not refuse a valid transfer, and endpoints that disagree decide nothing.\n */\nconst CONFIRMED: TronCallTags = { ...READ, quorum: 'proof' };\n\n/** The memo's UTF-8 bytes as hex, or undefined; refused when over `MAX_MEMO_BYTES`. */\nfunction memoHex(memo: string | undefined): string | undefined {\n if (memo === undefined || memo.length === 0) return undefined;\n const tooLong = () => invalid(`a Tron memo is at most ${MAX_MEMO_BYTES} UTF-8 bytes`);\n // Each UTF-16 unit is at least one UTF-8 byte, so a longer string is refused unencoded.\n if (memo.length > MAX_MEMO_BYTES) throw tooLong();\n const bytes = utf8ToBytes(memo);\n if (bytes.length > MAX_MEMO_BYTES) throw tooLong();\n // A lone surrogate would be written as U+FFFD: the chain would carry another memo.\n if (bytesToUtf8(bytes) !== memo) throw invalid('a Tron memo must be well-formed text');\n return toHex(bytes);\n}\n\n/**\n * The validated transfer, before any I/O: one output, a positive amount, TRX or TRC-20,\n * valid addresses, a memo within bounds, amounts the encoders can write exactly (a TRX\n * transfer above 2^53 − 1 sun must be split), and TRX never to the sender (java-tron:\n * \"Cannot transfer TRX to yourself.\", for the bytes alone). A TRC-20 transfer to the\n * sender is valid on chain and is allowed.\n */\nfunction prepare(intent: DriverIntent): Prepared {\n const output = intent.outputs[0];\n if (!output || intent.outputs.length !== 1) {\n throw invalid('a Tron transfer has exactly one output');\n }\n if (output.amount <= 0n) {\n throw new ValidationError('INVALID_AMOUNT', 'the amount must be positive');\n }\n const token = intent.asset === 'native' ? undefined : trc20Contract(intent.asset);\n const owner = toHexAddress(intent.from);\n const recipient = toHexAddress(output.to);\n const memo = memoHex(intent.memo);\n let contract: TronContract;\n if (token === undefined) {\n if (output.amount > MAX_SAFE) {\n throw new ValidationError(\n 'INVALID_AMOUNT',\n 'a TRX amount must be at most the largest safe integer of sun',\n );\n }\n if (recipient === owner) throw invalid('a TRX transfer cannot go to its sender');\n contract = { type: 'TransferContract', owner, to: recipient, amount: output.amount };\n } else {\n // encodeTransfer refuses an amount outside uint256 (INVALID_AMOUNT).\n const data = encodeTransfer(recipient, output.amount);\n contract = { type: 'TriggerSmartContract', owner, contract: token, data };\n }\n return {\n to: output.to,\n amount: output.amount,\n owner,\n recipient,\n contract,\n ...(token !== undefined ? { token } : {}),\n ...(memo !== undefined ? { memo } : {}),\n };\n}\n\n/**\n * Whether decoded raw data carries exactly `t`. A TRC-20 call must be the canonical\n * `transfer(to, amount)` (selector, zero-padded recipient, one amount word, nothing more)\n * with no TRX or TRC-10 value: the verdict reads only that shape.\n */\nfunction carries(raw: TronRawData, t: Transfer): boolean {\n const c = raw.contract;\n if (c.owner !== t.owner || raw.data !== t.memo) return false;\n if (t.token === undefined) {\n return c.type === 'TransferContract' && c.to === t.recipient && c.amount === t.amount;\n }\n if (c.type !== 'TriggerSmartContract' || c.contract !== t.token) return false;\n if (\n c.callValue !== undefined ||\n c.callTokenValue !== undefined ||\n c.tokenId !== undefined\n ) {\n return false;\n }\n const call = decodeTransferCall(c.data);\n return call !== null && call.to === t.recipient && call.amount === t.amount;\n}\n\n/** The transfer a stored summary describes, signed by `owner`; null when it describes none. */\nfunction summaryTransfer(\n ctx: TronContext,\n summary: IntentSummary,\n owner: string,\n): Transfer | null {\n try {\n const { chain, network, ref } = parseAssetId(summary.asset);\n const output = summary.outputs[0];\n if (\n chain !== ctx.chain.id ||\n network !== ctx.network.id ||\n !output ||\n summary.outputs.length !== 1 ||\n !SUMMARY_AMOUNT.test(output.amount)\n ) {\n return null;\n }\n const token = ref === 'native' ? undefined : trc20Contract(ref);\n const memo = memoHex(summary.memo);\n return {\n owner,\n recipient: toHexAddress(output.to),\n amount: BigInt(output.amount),\n ...(token !== undefined ? { token } : {}),\n ...(memo !== undefined ? { memo } : {}),\n };\n } catch {\n return null;\n }\n}\n\n/**\n * The fee fields a build writes, from this transfer's own `tron` estimate: the bandwidth\n * the estimate covers and, for TRC-20 only, a positive fee limit within the handle's\n * `maxFeeLimit`, wherever the estimate came from. The limit is handed to the codec\n * as a number and its `safe()` refuses one it cannot hold exactly: it is never\n * rounded into the bytes.\n */\nfunction feeFields(\n fee: FeeEstimateDraft,\n p: Prepared,\n maxFeeLimit: bigint,\n): { readonly bandwidth: bigint; readonly feeLimit?: number } {\n const details = fee.details as Partial<TronFeeDetails>;\n const mismatch = () =>\n invalid('the fee estimate is not a Tron estimate for this transfer');\n if (\n fee.kind !== 'tron' ||\n typeof details.bandwidth !== 'bigint' ||\n details.bandwidth <= 0n\n ) {\n throw mismatch();\n }\n if (p.token === undefined) {\n if (details.feeLimit !== undefined) throw mismatch();\n return { bandwidth: details.bandwidth };\n }\n if (typeof details.feeLimit !== 'bigint' || details.feeLimit <= 0n) throw mismatch();\n if (details.feeLimit > maxFeeLimit) {\n throw invalid(\n 'the fee limit is above maxFeeLimit, the Tron handle option that bounds it (in sun)',\n );\n }\n return { bandwidth: details.bandwidth, feeLimit: Number(details.feeLimit) };\n}\n\n/** The sender's own key: a signature from any other key would not authorize the owner. */\nfunction signingKey(keys: readonly WalletKey[], owner: string): WalletKey {\n for (const key of keys) {\n if (key.scheme !== 'secp256k1-ecdsa') continue;\n try {\n if (toHexAddress(addressFromPublicKey(key.publicKey)) === owner) return key;\n } catch {\n // Not a secp256k1 point: not this sender's key.\n }\n }\n throw new SigningError(\n 'SIGNER_UNAVAILABLE',\n 'no secp256k1 key for the sending address',\n );\n}\n\nfunction varint(value: number): Uint8Array {\n const out: number[] = [];\n let v = value;\n do {\n let byte = v & 0x7f;\n v = Math.floor(v / 128);\n if (v > 0) byte |= 0x80;\n out.push(byte);\n } while (v > 0);\n return Uint8Array.from(out);\n}\n\n/** `Transaction { raw raw_data = 1; repeated bytes signature = 2; }` with one signature. */\nfunction signedTransaction(raw: Uint8Array, signature: Uint8Array): Uint8Array {\n return concatBytes(\n Uint8Array.of(0x0a),\n varint(raw.length),\n raw,\n Uint8Array.of(0x12),\n varint(signature.length),\n signature,\n );\n}\n\n/**\n * java-tron's bandwidth for a transaction whose `raw_data` is `rawBytes` long\n * (`BandwidthProcessor.consume`): the signed size without `ret` (field 1 with its length and\n * the raw bytes, field 2 with its length and one 65-byte signature) plus 64 result bytes.\n */\nexport function bandwidthOf(rawBytes: number): bigint {\n return BigInt(1 + varint(rawBytes).length + rawBytes + 2 + 65 + 64);\n}\n\n/** A crypto-random integer in [0, 1000). */\nfunction jitter(): number {\n const bytes = randomBytes(2);\n return (((bytes[0] as number) << 8) | (bytes[1] as number)) % 1000;\n}\n\nconst expiresAt = (ordering: OrderingData): number | undefined =>\n ordering.kind === 'expiry' ? ordering.expiresAtMs : undefined;\n\n/**\n * Whether an ordering names the signed reference block: a reference height\n * (`lastValidHeight − TAPOS_WINDOW`) whose bytes 6..8 are the signed `ref_block_bytes`, and\n * the signed `ref_block_hash` itself. The proofs trust the height only with the hash.\n */\nfunction boundToReference(ordering: OrderingData, raw: TronRawData): boolean {\n if (ordering.kind !== 'expiry') return false;\n const { lastValidHeight: last, refBlockHash } = ordering as Partial<TronExpiryOrdering>;\n if (typeof last !== 'bigint' || last < TAPOS_WINDOW) return false;\n return (\n ((last - TAPOS_WINDOW) & 0xffffn) === BigInt(`0x${raw.refBlockBytes}`) &&\n refBlockHash === raw.refBlockHash\n );\n}\n\nexport function createTronBuilder(ctx: TronContext): {\n readonly builder: TxBuilder;\n readonly broadcaster: Broadcaster;\n} {\n const { api, codec, config } = ctx;\n let lastTimestamp = 0;\n\n const refFields = (head: TronBlockHeader) => ({\n refBlockBytes: head.id.slice(12, 16),\n refBlockHash: head.id.slice(16, 32),\n });\n\n async function head(signal?: AbortSignal): Promise<TronBlockHeader> {\n // `block` throws a malformed answer rather than return no head.\n return (await api.block(\n 'full',\n undefined,\n withSignal(READ, signal),\n )) as TronBlockHeader;\n }\n\n /**\n * The simulated energy of a TRC-20 transfer, after the deprecation and balance checks: a\n * deprecated token is `ASSET_RESOLUTION`; a shortfall is `INSUFFICIENT_FUNDS`, never a\n * revert; a token that refuses a transfer its balance allows (a blacklist, say) is\n * `INVALID_INTENT`.\n *\n * Tether's `TetherToken` (USDT) forwards a deprecated contract's `transfer` to its\n * upgraded contract, which moves the value and emits the `Transfer` event, so the\n * transfer simulates and executes, and the verdict, which reads the old contract's event,\n * finds no evidence of it. So `deprecated()` is read beside the balance, once per\n * estimate (the core estimates before every build), one endpoint's answer as for the\n * other token reads here, not the proof quorum's: a `true` can only refuse before\n * signing, the safe direction (as one endpoint's failed simulation already does), and a\n * wrong `false` leaves the transfer where it was without the guard.\n */\n async function tokenEnergy(p: Prepared, signal?: AbortSignal): Promise<bigint> {\n const tags = withSignal(READ, signal);\n const token = p.token as string;\n const [deprecated, available] = await Promise.all([\n trc20Deprecated(ctx, token, tags),\n trc20Balance(ctx, token, p.owner, tags),\n ]);\n if (deprecated) {\n throw new ValidationError(\n 'ASSET_RESOLUTION',\n 'the token contract is deprecated in favour of an upgraded contract; the asset must be re-registered at the upgraded contract',\n );\n }\n if (available < p.amount) {\n throw new ChainError(\n 'INSUFFICIENT_FUNDS',\n 'insufficient token balance for this transfer',\n { details: { required: p.amount.toString(), available: available.toString() } },\n );\n }\n const data = (p.contract as Extract<TronContract, { type: 'TriggerSmartContract' }>)\n .data;\n const call = await api.constantCall(p.owner, token, data, tags);\n if (call.kind === 'no-contract') {\n // Its balanceOf just answered: two reads disagree, which decides nothing.\n throw new ProviderError(\n 'PROVIDER_INCONSISTENT',\n 'the node both holds and lacks this token contract',\n { retryable: true },\n );\n }\n if (call.kind === 'failed') throw invalid('the token contract refuses this transfer');\n return call.energy;\n }\n\n const builder: TxBuilder = {\n async estimateFee(intent, build: BuildContext) {\n const p = prepare(intent);\n const tags = withSignal(READ, build.signal);\n const [params, resources, block, recipient, energy] = await Promise.all([\n api.chainParameters(tags),\n api.resources(p.owner, tags),\n head(build.signal),\n p.token === undefined ? api.account(p.recipient, tags) : undefined,\n p.token === undefined ? undefined : tokenEnergy(p, build.signal),\n ]);\n // Where the chain forbids TRX to a contract, such a transfer is refused before\n // signing (it would only be refused, stall and expire). Elsewhere it is valid on\n // chain: the flag is 0 on mainnet, Nile and Shasta.\n // Known gap: the flag is one endpoint's word, read without a quorum, so a false 1\n // refuses a valid transfer before signing and a false 0 lets the chain refuse it;\n // liveness only, never a wrong payment.\n if (\n p.token === undefined &&\n params.forbidTransferToContract &&\n (await api.contractExists(p.recipient, withSignal(CONFIRMED, build.signal)))\n ) {\n throw invalid(\n 'this network refuses TRX sent to a contract (getForbidTransferToContract)',\n );\n }\n // An upper bound of the built size: no expiration jitter, a later timestamp, and the\n // largest fee limit a build can carry (the ceiling `tronFee` applies).\n const now = ctx.clock.now();\n const ceiling = feeLimitCeiling(params, config.maxFeeLimit).value;\n const provisional = codec.encodeRaw({\n ...refFields(block),\n expiration: Math.min(block.timestamp, now) + config.expirationMs,\n timestamp: Math.max(now + 1_000, lastTimestamp + 1),\n ...(p.token !== undefined ? { feeLimit: Number(ceiling) } : {}),\n ...(p.memo !== undefined ? { data: p.memo } : {}),\n contract: p.contract,\n });\n return tronFee({\n fee: intent.fee,\n params,\n resources,\n bandwidth: bandwidthOf(provisional.length / 2),\n activation: recipient !== undefined && !recipient.exists,\n memo: p.memo !== undefined,\n ...(energy !== undefined ? { energy } : {}),\n marginPercent: config.energyMarginPercent,\n maxFeeLimit: config.maxFeeLimit,\n });\n },\n\n async checkFunds(intent, fee, build) {\n const p = prepare(intent);\n const tags = withSignal(READ, build.signal);\n const [account, tokens] = await Promise.all([\n api.account(p.owner, tags),\n p.token === undefined ? undefined : trc20Balance(ctx, p.token, p.owner, tags),\n ]);\n if (tokens !== undefined && tokens < p.amount) {\n return { ok: false, asset: intent.asset, required: p.amount, available: tokens };\n }\n const required = feeSun(fee) + (p.token === undefined ? p.amount : 0n);\n // An account that was never activated has no free bandwidth and cannot send.\n return account.exists && account.balance >= required\n ? { ok: true }\n : { ok: false, asset: 'native', required, available: account.balance };\n },\n\n async build(intent, fee, build): Promise<UnsignedTx> {\n const p = prepare(intent);\n const key = signingKey(build.keys, p.owner);\n const fees = feeFields(fee, p, config.maxFeeLimit);\n const block = await head(build.signal);\n const now = ctx.clock.now();\n if (now - block.timestamp > config.expirationMs / 2) {\n throw new ProviderError(\n 'PROVIDER_UNAVAILABLE',\n 'the head block is too old to reference; try again',\n );\n }\n // A head dated more than half the window ahead means a local clock behind\n // the chain, whose every build would be born expired (and cost a signature per\n // rebuild), or a lying endpoint. Either way nothing is built on it.\n if (block.timestamp - now > config.expirationMs / 2) {\n throw new ProviderError(\n 'PROVIDER_UNAVAILABLE',\n 'the head block is dated ahead of the local clock; check the clock or try again',\n );\n }\n // The reference block's height, from its id (java-tron's block id is the\n // height's 8 bytes followed by 24 bytes of the header hash, `generateBlockId`): the\n // same bytes TaPoS reads. A head whose id and number disagree is not a block.\n const reference = BigInt(`0x${block.id.slice(0, 16)}`);\n if (reference !== block.number) throw malformed('head block id');\n const anchor = Math.min(block.timestamp, now);\n const expiration = anchor + config.expirationMs - jitter();\n // The window stays within MAX_EXPIRATION_MS, and java-tron wants at least the next\n // slot. The network config bounds the window; this holds it.\n if (expiration - anchor > MAX_EXPIRATION_MS) {\n throw new ConfigError(\n 'CONFIG_INVALID',\n 'the expiration window exceeds the maximum',\n );\n }\n if (expiration - anchor < MIN_EXPIRATION_MS - 1_000) {\n throw new ConfigError(\n 'CONFIG_INVALID',\n 'the expiration window is below the minimum',\n );\n }\n const timestamp = Math.max(now + jitter(), lastTimestamp + 1);\n lastTimestamp = timestamp;\n const raw: TronRawData = {\n ...refFields(block),\n expiration,\n timestamp,\n ...(fees.feeLimit !== undefined ? { feeLimit: fees.feeLimit } : {}),\n ...(p.memo !== undefined ? { data: p.memo } : {}),\n contract: p.contract,\n };\n const payload = codec.encodeRaw(raw);\n // Before anything is signed: the bytes decode strictly to exactly this transfer.\n let built: TronRawData | undefined;\n try {\n built = codec.decodeRaw(payload);\n } catch {\n built = undefined;\n }\n if (\n !built ||\n !carries(built, p) ||\n built.expiration !== expiration ||\n built.feeLimit !== raw.feeLimit\n ) {\n throw invalid('the built transaction does not carry this transfer');\n }\n if (bandwidthOf(payload.length / 2) > fees.bandwidth) {\n throw invalid(\"the fee estimate does not cover this transaction's bandwidth\");\n }\n const txId = toHex(sha256(fromHex(payload)));\n // The negative proof scans from the reference block to the signed expiration; the\n // height is the head's claim, so the signed hash bytes go with it, and the proof\n // trusts the height only where the attested block carries them.\n const ordering: TronExpiryOrdering = {\n kind: 'expiry',\n expiresAtMs: expiration,\n lastValidHeight: reference + TAPOS_WINDOW,\n refBlockHash: raw.refBlockHash,\n };\n return {\n payload: { encoding: 'hex', data: payload },\n expectedRef: { id: txId, idKind: 'tx-hash', canonical: true },\n signingRequests: [\n {\n id: 'r0',\n scheme: 'secp256k1-ecdsa',\n payload: fromHex(txId),\n payloadKind: 'digest',\n publicKey: key.publicKey,\n ...(key.keyRef ? { keyRef: key.keyRef } : {}),\n },\n ],\n ordering,\n fee,\n summary: {\n asset: assetId(ctx.chain.id, ctx.network.id, intent.asset),\n outputs: [{ to: p.to, amount: p.amount.toString() }],\n ...(intent.memo !== undefined ? { memo: intent.memo } : {}),\n },\n };\n },\n\n async assemble(unsigned, signatures) {\n const fail = (message: string) => new SigningError('SIGNING_FAILED', message);\n const request = unsigned.signingRequests[0];\n const signature = signatures.find((s) => s.requestId === 'r0');\n if (\n !request ||\n request.id !== 'r0' ||\n unsigned.signingRequests.length !== 1 ||\n !signature ||\n signature.bytes.length !== 64 ||\n (signature.recovery !== 0 && signature.recovery !== 1)\n ) {\n throw fail('missing or malformed signature for request r0');\n }\n const mismatch = () => fail('the unsigned payload does not match its txID');\n if (unsigned.payload.encoding !== 'hex') throw mismatch();\n let raw: Uint8Array;\n try {\n raw = fromHex(unsigned.payload.data);\n } catch {\n throw mismatch();\n }\n const txId = toHex(sha256(raw));\n if (txId !== toHex(request.payload) || txId !== unsigned.expectedRef?.id) {\n throw mismatch();\n }\n // The stored bytes decode strictly, and their owner is the signing key's\n // account, so a signature never authorizes another account's transaction.\n let decoded: TronRawData;\n try {\n decoded = codec.decodeRaw(unsigned.payload.data);\n } catch {\n throw fail('the unsigned payload is not a Tron transfer');\n }\n let signer: string;\n try {\n signer = toHexAddress(addressFromPublicKey(request.publicKey));\n } catch {\n throw fail('the signing request has no valid public key');\n }\n if (decoded.contract.owner !== signer) {\n throw fail(\"the payload's owner is not the signing key's account\");\n }\n // Only a signature the node will take for the owner's goes out, low s and\n // recovery bit included, as the core's scheme checks it; a signer fault is a signing\n // failure here, never a refusal on chain.\n if (\n !secp256k1Ecdsa.verify({\n publicKey: request.publicKey,\n payload: fromHex(txId),\n signature: signature.bytes,\n recovery: signature.recovery,\n })\n ) {\n throw fail('the signature does not verify against the signing key');\n }\n // The bytes carry the authorized summary; the proofs read the expiration and the\n // reference height from the ordering; only the named fee field is read (the core may\n // add others).\n const expected = summaryTransfer(ctx, unsigned.summary, signer);\n const feeLimit = (unsigned.fee.details as Partial<TronFeeDetails>).feeLimit;\n if (\n !expected ||\n !carries(decoded, expected) ||\n expiresAt(unsigned.ordering) !== decoded.expiration ||\n !boundToReference(unsigned.ordering, decoded) ||\n unsigned.fee.kind !== 'tron' ||\n (expected.token === undefined\n ? decoded.feeLimit !== undefined\n : typeof feeLimit !== 'bigint' ||\n decoded.feeLimit === undefined ||\n BigInt(decoded.feeLimit) !== feeLimit)\n ) {\n throw fail(\n 'the unsigned payload does not match its summary, expiry or fee limit',\n );\n }\n const sig = concatBytes(signature.bytes, Uint8Array.of(27 + signature.recovery));\n return {\n raw: { encoding: 'hex', data: toHex(signedTransaction(raw, sig)) },\n ref: { id: txId, idKind: 'tx-hash', canonical: true },\n };\n },\n };\n\n const broadcaster: Broadcaster = {\n async broadcast(signed, options = {}) {\n const { raw } = signed;\n if (\n raw.encoding !== 'hex' ||\n typeof raw.data !== 'string' ||\n raw.data.length % 2 !== 0 ||\n !HEX_DIGITS.test(raw.data)\n ) {\n throw new UnsupportedCapabilityError(\n 'UNSUPPORTED_CAPABILITY',\n 'Tron broadcasts take the signed transaction as hex',\n );\n }\n // The broadcast tags carry no quorum: one node's answer is classified, never compared.\n const hex = raw.data.toLowerCase();\n const answer = await api.broadcastHex(hex, {\n ...BROADCAST,\n ...(options.fanout !== undefined ? { fanout: options.fanout } : {}),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n // Inside the broadcaster, so a possibly-sent throw reaches the engine's recordAmbiguous.\n // A rejection stands only when its reason holds for these bytes.\n return classifyOwnBroadcast(answer, txBytesOf(hex));\n },\n };\n\n return { builder, broadcaster };\n}\n"]}
|
|
@@ -18,11 +18,13 @@
|
|
|
18
18
|
* stored reason must never hold either.
|
|
19
19
|
*/
|
|
20
20
|
import type { DriverTransaction } from '../../core/driver/types';
|
|
21
|
+
import type { TxFailure } from '../../core/model/transaction';
|
|
21
22
|
import { type TronTxInfo, type TronTxJson } from './http';
|
|
22
23
|
import type { TronCodec, TronRawData } from './types';
|
|
23
24
|
export interface TxVerdict {
|
|
24
25
|
readonly success: boolean;
|
|
25
26
|
readonly reason?: string;
|
|
27
|
+
readonly failure?: TxFailure;
|
|
26
28
|
}
|
|
27
29
|
/**
|
|
28
30
|
* A TRC-20 `transfer(to, …)` counts only if the called token
|
|
@@ -143,7 +143,7 @@ function verdictOf(codec, tx, info) {
|
|
|
143
143
|
throw (0, http_1.malformed)('Transfer log');
|
|
144
144
|
return evidence === 'landed'
|
|
145
145
|
? chain
|
|
146
|
-
: { success: false, reason: 'token transfer not evidenced' };
|
|
146
|
+
: { success: false, reason: 'token transfer not evidenced', failure: 'unevidenced' };
|
|
147
147
|
}
|
|
148
148
|
const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
149
149
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decode.js","sourceRoot":"","sources":["../../../src/adapters/tron/decode.ts"],"names":[],"mappings":";;AAgIA,wCAEC;AAGD,oCAMC;AASD,8BA6BC;AA+BD,8CAwGC;AAhSD,iDAAgD;AAChD,+BAA8E;AAC9E,uCAA4C;AAC5C,iCAAkF;AAQlF,mFAAmF;AACnF,MAAM,eAAe,GAAgC,IAAI,GAAG,CAAC;IAC3D,CAAC,eAAe,EAAE,eAAe,CAAC;IAClC,CAAC,QAAQ,EAAE,UAAU,CAAC;CACvB,CAAC,CAAC;AAEH,4FAA4F;AAC5F,SAAS,YAAY,CAAC,QAAsB;IAC1C,OAAO,CACL,QAAQ,CAAC,IAAI,KAAK,sBAAsB;QACxC,CAAC,QAAQ,CAAC,SAAS,KAAK,SA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QAAQ,EAAE,GAAG,EAAE,QAAQ,CAAC,IAAI,IAAI,SAAS;YACzC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC3B,GAAG,CAAC,EAAE,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACnE,GAAG,CAAC,IAAI,EAAE,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC7E,GAAG,CAAC,GAAG,EAAE,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC1E,GAAG,CAAC,IAAI,EAAE,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACvE,GAAG,CAAC,IAAI,EAAE,cAAc,KAAK,SAAS;gBACpC,CAAC,CAAC,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE;gBACzC,CAAC,CAAC,EAAE,CAAC;YACP,GAAG,CAAC,IAAI,EAAE,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAClE;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Chain transactions into `DriverTransaction`s, and the verdict of our own transfers.\n * - General decoding (reads, scans, history) reports execution as the chain does: a TRX\n * transfer is `native`, and so is the TRX a contract call sends; each TRC-20 `Transfer`\n * log is a `token-event` (`log:<i>`); contract execution is `partial` (value may move\n * without a log), a failed transaction moved nothing and is `complete`, and a contract\n * type this model does not carry is `none`.\n * - The verdict of our own Attempts (observe with an ordering, and the proofs) also\n * requires on-chain evidence that value moved: a TRC-20 `transfer(to, amount)` counts\n * only with a `Transfer(owner, to, any positive amount)` log from the called contract.\n * Execution success alone proves nothing: a token can succeed and move nothing, and\n * USDT on Tron returns a zero word from `transfer`.\n * - Verdict fields are read strictly: a missing, ill-typed or contradicting one\n * is a malformed answer (retryable), which decides nothing, never a default. Decoding stays\n * lenient on what the chain accepts: an unknown contract type, a memo of any size or bytes.\n * - `readRaw`'s `timestamp` and `feeLimit` are display only: no verdict or amount uses them.\n * Failure reasons are fixed literals: a node's text can carry addresses or amounts, and a\n * stored reason must never hold either.\n */\nimport type {\n DriverTransaction,\n DriverTransfer,\n DriverTxObservation,\n} from '../../core/driver/types';\nimport { fromHex } from '../../core/util/bytes';\nimport { TRANSFER_TOPIC, decodeTransferCall, decodeTransferLog } from './abi';\nimport { toBase58Address } from './address';\nimport { malformed, notServable, type TronTxInfo, type TronTxJson } from './http';\nimport type { TronCodec, TronContract, TronRawData } from './types';\n\nexport interface TxVerdict {\n readonly success: boolean;\n readonly reason?: string;\n}\n\n/** VM receipt results with a reason of their own; any other failure is generic. */\nconst FAILURE_REASONS: ReadonlyMap<string, string> = new Map([\n ['OUT_OF_ENERGY', 'out of energy'],\n ['REVERT', 'reverted'],\n]);\n\n/** A contract call that also sends TRX or a TRC-10 token: never a plain TRC-20 transfer. */\nfunction carriesValue(contract: TronContract): boolean {\n return (\n contract.type === 'TriggerSmartContract' &&\n (contract.callValue !== undefined ||\n contract.callTokenValue !== undefined ||\n contract.tokenId !== undefined)\n );\n}\n\n/**\n * The chain's own verdict, from strictly read fields (no evidence check). The VM writes a\n * receipt result for every call it runs (`TransactionTrace.setResult`), `ret[0].contractRet`\n * repeats it, and the info's `FAILED` is set exactly when the call did not succeed\n * (`TransactionUtil.buildTransactionInfoInstance`, GreatVoyage-v4.8.2.2 `d5c3d1d1`). Other\n * contracts carry no receipt result: java-tron never includes one whose execution failed,\n * and blocks from 2018 carry no `ret` at all (mainnet block 2,000,000), so inclusion is\n * their success unless the node reports a failure.\n */\nfunction executed(raw: TronRawData | null, tx: TronTxJson, info: TronTxInfo): TxVerdict {\n // Bound to the id asked for: another transaction's receipt decides nothing.\n if (info.id !== tx.id) throw malformed('transaction info');\n const vm = raw\n ? raw.contract.type === 'TriggerSmartContract'\n : info.receiptResult !== undefined;\n if (vm) {\n const result = info.receiptResult;\n if (result === undefined) throw malformed('receipt result');\n if (tx.contractRet !== undefined && tx.contractRet !== result) {\n throw malformed('contractRet');\n }\n if (result !== 'SUCCESS') {\n return {\n success: false,\n reason: FAILURE_REASONS.get(result) ?? 'contract execution failed',\n };\n }\n if (info.failed) throw malformed('result');\n return { success: true };\n }\n if (info.failed || (tx.contractRet !== undefined && tx.contractRet !== 'SUCCESS')) {\n return { success: false, reason: 'execution failed' };\n }\n return { success: true };\n}\n\ntype Evidence = 'landed' | 'absent' | 'unreadable';\n\n/**\n * What the called token logged for a TRC-20 `transfer(to, …)`. `landed`: a `Transfer`\n * from the sender to that recipient of any positive amount, from the called contract.\n * `unreadable`: nothing landed, and the contract logged a `Transfer` event that does not\n * read as one (its value indexed, say).\n * A call with a value, or with data that is not a canonical `transfer`, is `absent`.\n */\nfunction transferEvidence(raw: TronRawData, info: TronTxInfo): Evidence {\n const { contract } = raw;\n if (contract.type !== 'TriggerSmartContract') return 'landed';\n if (carriesValue(contract)) return 'absent';\n const call = decodeTransferCall(contract.data);\n if (call === null) return 'absent';\n const emitter = contract.contract.slice(2);\n let unreadable = false;\n for (const log of info.logs) {\n if (log.address !== emitter) continue;\n const event = decodeTransferLog(log);\n if (event === null) {\n if (log.topics[0] === TRANSFER_TOPIC) unreadable = true;\n } else if (\n event.from === contract.owner &&\n event.to === call.to &&\n event.amount > 0n\n ) {\n return 'landed';\n }\n }\n return unreadable ? 'unreadable' : 'absent';\n}\n\n/**\n * A TRC-20 `transfer(to, …)` counts only if the called token\n * contract logged a `Transfer` from the sender to that recipient. Any positive amount counts:\n * a fee-on-transfer token (Tron USDT has a dormant fee switch) logs less than the call's\n * amount, and requiring the exact amount would prove a transfer that moved `failed`. A call\n * that also sends TRX or a TRC-10 token, or whose data is not a canonical `transfer`, is never\n * a plain TRC-20 transfer. Decoding reports the amounts that actually moved.\n */\nexport function transferLanded(raw: TronRawData, info: TronTxInfo): boolean {\n return transferEvidence(raw, info) === 'landed';\n}\n\n/** The chain's own view of an included transaction (no evidence check: not a verdict). */\nexport function chainVerdict(\n codec: TronCodec,\n tx: TronTxJson,\n info: TronTxInfo,\n): TxVerdict {\n return executed(codec.readRaw(tx.rawHex), tx, info);\n}\n\n/**\n * The verdict of our own included transaction (observe with an ordering, `includedFinal`).\n * The driver built it, so its bytes read, its call is a canonical `transfer` that sends no\n * value, a node's answer for it carries `contractRet`, and a TRX transfer in a block executed;\n * anything else contradicts the signed transaction or the chain's rules and decides nothing\n * (retryable), as does a token `Transfer` event that does not read.\n */\nexport function verdictOf(codec: TronCodec, tx: TronTxJson, info: TronTxInfo): TxVerdict {\n const raw = codec.readRaw(tx.rawHex);\n if (raw === null) throw malformed('raw_data_hex');\n if (tx.contractRet === undefined) throw malformed('contractRet');\n if (carriesValue(raw.contract)) throw malformed('call value');\n // An included TransferContract executed (java-tron never includes one that\n // failed), so any other answer on our own is impossible: a false `failed` on a proof path\n // would invite a second payment. The chain's view reports what the node says.\n if (\n raw.contract.type === 'TransferContract' &&\n (tx.contractRet !== 'SUCCESS' || info.failed)\n ) {\n throw malformed('contractRet');\n }\n // Our own TRC-20 call is a canonical `transfer(to, amount)` (the builder\n // writes nothing else), so other call data contradicts the signed transaction.\n if (\n raw.contract.type === 'TriggerSmartContract' &&\n decodeTransferCall(raw.contract.data) === null\n ) {\n throw malformed('call data');\n }\n const chain = executed(raw, tx, info);\n if (!chain.success) return chain;\n const evidence = transferEvidence(raw, info);\n if (evidence === 'unreadable') throw malformed('Transfer log');\n return evidence === 'landed'\n ? chain\n : { success: false, reason: 'token transfer not evidenced' };\n}\n\nconst UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });\n\n/**\n * The memo (`raw_data.data`) as text: `undefined` without one, `null` when its bytes are not\n * UTF-8 (replacement characters would make two different memos read the same). Any size the\n * chain accepts reads: the driver's own 256-byte cap applies to what it writes.\n */\nfunction memoOf(raw: TronRawData): string | null | undefined {\n if (raw.data === undefined) return undefined;\n try {\n return UTF8.decode(fromHex(raw.data));\n } catch {\n return null;\n }\n}\n\n/** A canonical `T…` address, or `null` for bytes that are not one (never thrown). */\nfunction base58(hex: string): string | null {\n try {\n return toBase58Address(hex);\n } catch {\n return null;\n }\n}\n\n/**\n * Any transaction as the chain reports it. `info` and `blockHash` come together for an\n * included transaction; `pending` marks one the node holds in its pool.\n */\nexport function decodeTransaction(\n codec: TronCodec,\n tx: TronTxJson,\n info: TronTxInfo | null,\n blockHash: string | undefined,\n pending = false,\n): DriverTransaction {\n if (info !== null && blockHash === undefined) throw notServable();\n const raw = codec.readRaw(tx.rawHex);\n const chain = info ? executed(raw, tx, info) : undefined;\n const observation: DriverTxObservation =\n info && chain && blockHash !== undefined\n ? {\n seen: 'block',\n txHash: tx.id,\n blockHeight: info.blockNumber,\n blockHash,\n success: chain.success,\n ...(chain.reason ? { reason: chain.reason } : {}),\n }\n : pending\n ? { seen: 'mempool', txHash: tx.id }\n : { seen: 'none' };\n const memo = raw ? memoOf(raw) : undefined;\n const owner = raw ? base58(raw.contract.owner) : null;\n const transfers: DriverTransfer[] = [];\n let decoding: DriverTransaction['decoding'] = 'complete';\n /** A movement with the memo; `null` (an address that does not read) is left out. */\n const add = (transfer: Omit<DriverTransfer, 'memo'> | null): void => {\n if (!transfer) decoding = 'partial';\n else transfers.push(typeof memo === 'string' ? { ...transfer, memo } : transfer);\n };\n const native = (to: string, amount: bigint) => {\n const recipient = base58(to);\n add(\n owner && recipient\n ? {\n locator: 'native',\n from: [owner],\n to: recipient,\n asset: 'native',\n amount,\n source: 'native',\n }\n : null,\n );\n };\n if (raw === null) {\n decoding = 'none';\n } else if (!info) {\n decoding = 'partial';\n } else if (chain?.success) {\n if (memo === null) decoding = 'partial';\n const { contract } = raw;\n if (contract.type === 'TransferContract') {\n native(contract.to, contract.amount);\n } else {\n // Value can move without a log (internal transfers), and a TRC-10 value has no asset\n // here: a contract call is partial.\n decoding = 'partial';\n if (contract.callValue !== undefined) native(contract.contract, contract.callValue);\n info.logs.forEach((log, index) => {\n const event = decodeTransferLog(log);\n if (!event) return;\n const from = base58(event.from);\n const to = base58(event.to);\n const token = base58(`41${log.address}`);\n add(\n from && to && token\n ? {\n locator: `log:${index}`,\n from: [from],\n to,\n asset: { standard: 'trc20', contract: token },\n amount: event.amount,\n source: 'token-event',\n }\n : null,\n );\n });\n }\n }\n const call = raw?.contract.type === 'TriggerSmartContract' ? raw.contract : undefined;\n return {\n id: tx.id,\n observation,\n ...(info ? { fee: [{ asset: 'native' as const, amount: info.fee }] } : {}),\n transfers,\n decoding,\n // The block's time: the client-set `raw_data.timestamp` is display only.\n ...(info ? { timestamp: info.blockTimestamp } : {}),\n details: {\n contract: raw?.contract.type ?? 'unknown',\n ...(owner ? { owner } : {}),\n ...(tx.contractRet !== undefined ? { result: tx.contractRet } : {}),\n ...(info?.receiptResult !== undefined ? { receipt: info.receiptResult } : {}),\n ...(raw?.feeLimit !== undefined ? { feeLimit: BigInt(raw.feeLimit) } : {}),\n ...(call?.callValue !== undefined ? { callValue: call.callValue } : {}),\n ...(call?.callTokenValue !== undefined\n ? { callTokenValue: call.callTokenValue }\n : {}),\n ...(call?.tokenId !== undefined ? { tokenId: call.tokenId } : {}),\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"decode.js","sourceRoot":"","sources":["../../../src/adapters/tron/decode.ts"],"names":[],"mappings":";;AAkIA,wCAEC;AAGD,oCAMC;AASD,8BA6BC;AA+BD,8CAwGC;AAjSD,iDAAgD;AAChD,+BAA8E;AAC9E,uCAA4C;AAC5C,iCAAkF;AASlF,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CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAClE;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Chain transactions into `DriverTransaction`s, and the verdict of our own transfers.\n * - General decoding (reads, scans, history) reports execution as the chain does: a TRX\n * transfer is `native`, and so is the TRX a contract call sends; each TRC-20 `Transfer`\n * log is a `token-event` (`log:<i>`); contract execution is `partial` (value may move\n * without a log), a failed transaction moved nothing and is `complete`, and a contract\n * type this model does not carry is `none`.\n * - The verdict of our own Attempts (observe with an ordering, and the proofs) also\n * requires on-chain evidence that value moved: a TRC-20 `transfer(to, amount)` counts\n * only with a `Transfer(owner, to, any positive amount)` log from the called contract.\n * Execution success alone proves nothing: a token can succeed and move nothing, and\n * USDT on Tron returns a zero word from `transfer`.\n * - Verdict fields are read strictly: a missing, ill-typed or contradicting one\n * is a malformed answer (retryable), which decides nothing, never a default. Decoding stays\n * lenient on what the chain accepts: an unknown contract type, a memo of any size or bytes.\n * - `readRaw`'s `timestamp` and `feeLimit` are display only: no verdict or amount uses them.\n * Failure reasons are fixed literals: a node's text can carry addresses or amounts, and a\n * stored reason must never hold either.\n */\nimport type {\n DriverTransaction,\n DriverTransfer,\n DriverTxObservation,\n} from '../../core/driver/types';\nimport type { TxFailure } from '../../core/model/transaction';\nimport { fromHex } from '../../core/util/bytes';\nimport { TRANSFER_TOPIC, decodeTransferCall, decodeTransferLog } from './abi';\nimport { toBase58Address } from './address';\nimport { malformed, notServable, type TronTxInfo, type TronTxJson } from './http';\nimport type { TronCodec, TronContract, TronRawData } from './types';\n\nexport interface TxVerdict {\n readonly success: boolean;\n readonly reason?: string;\n readonly failure?: TxFailure;\n}\n\n/** VM receipt results with a reason of their own; any other failure is generic. */\nconst FAILURE_REASONS: ReadonlyMap<string, string> = new Map([\n ['OUT_OF_ENERGY', 'out of energy'],\n ['REVERT', 'reverted'],\n]);\n\n/** A contract call that also sends TRX or a TRC-10 token: never a plain TRC-20 transfer. */\nfunction carriesValue(contract: TronContract): boolean {\n return (\n contract.type === 'TriggerSmartContract' &&\n (contract.callValue !== undefined ||\n contract.callTokenValue !== undefined ||\n contract.tokenId !== undefined)\n );\n}\n\n/**\n * The chain's own verdict, from strictly read fields (no evidence check). The VM writes a\n * receipt result for every call it runs (`TransactionTrace.setResult`), `ret[0].contractRet`\n * repeats it, and the info's `FAILED` is set exactly when the call did not succeed\n * (`TransactionUtil.buildTransactionInfoInstance`, GreatVoyage-v4.8.2.2 `d5c3d1d1`). Other\n * contracts carry no receipt result: java-tron never includes one whose execution failed,\n * and blocks from 2018 carry no `ret` at all (mainnet block 2,000,000), so inclusion is\n * their success unless the node reports a failure.\n */\nfunction executed(raw: TronRawData | null, tx: TronTxJson, info: TronTxInfo): TxVerdict {\n // Bound to the id asked for: another transaction's receipt decides nothing.\n if (info.id !== tx.id) throw malformed('transaction info');\n const vm = raw\n ? raw.contract.type === 'TriggerSmartContract'\n : info.receiptResult !== undefined;\n if (vm) {\n const result = info.receiptResult;\n if (result === undefined) throw malformed('receipt result');\n if (tx.contractRet !== undefined && tx.contractRet !== result) {\n throw malformed('contractRet');\n }\n if (result !== 'SUCCESS') {\n return {\n success: false,\n reason: FAILURE_REASONS.get(result) ?? 'contract execution failed',\n };\n }\n if (info.failed) throw malformed('result');\n return { success: true };\n }\n if (info.failed || (tx.contractRet !== undefined && tx.contractRet !== 'SUCCESS')) {\n return { success: false, reason: 'execution failed' };\n }\n return { success: true };\n}\n\ntype Evidence = 'landed' | 'absent' | 'unreadable';\n\n/**\n * What the called token logged for a TRC-20 `transfer(to, …)`. `landed`: a `Transfer`\n * from the sender to that recipient of any positive amount, from the called contract.\n * `unreadable`: nothing landed, and the contract logged a `Transfer` event that does not\n * read as one (its value indexed, say).\n * A call with a value, or with data that is not a canonical `transfer`, is `absent`.\n */\nfunction transferEvidence(raw: TronRawData, info: TronTxInfo): Evidence {\n const { contract } = raw;\n if (contract.type !== 'TriggerSmartContract') return 'landed';\n if (carriesValue(contract)) return 'absent';\n const call = decodeTransferCall(contract.data);\n if (call === null) return 'absent';\n const emitter = contract.contract.slice(2);\n let unreadable = false;\n for (const log of info.logs) {\n if (log.address !== emitter) continue;\n const event = decodeTransferLog(log);\n if (event === null) {\n if (log.topics[0] === TRANSFER_TOPIC) unreadable = true;\n } else if (\n event.from === contract.owner &&\n event.to === call.to &&\n event.amount > 0n\n ) {\n return 'landed';\n }\n }\n return unreadable ? 'unreadable' : 'absent';\n}\n\n/**\n * A TRC-20 `transfer(to, …)` counts only if the called token\n * contract logged a `Transfer` from the sender to that recipient. Any positive amount counts:\n * a fee-on-transfer token (Tron USDT has a dormant fee switch) logs less than the call's\n * amount, and requiring the exact amount would prove a transfer that moved `failed`. A call\n * that also sends TRX or a TRC-10 token, or whose data is not a canonical `transfer`, is never\n * a plain TRC-20 transfer. Decoding reports the amounts that actually moved.\n */\nexport function transferLanded(raw: TronRawData, info: TronTxInfo): boolean {\n return transferEvidence(raw, info) === 'landed';\n}\n\n/** The chain's own view of an included transaction (no evidence check: not a verdict). */\nexport function chainVerdict(\n codec: TronCodec,\n tx: TronTxJson,\n info: TronTxInfo,\n): TxVerdict {\n return executed(codec.readRaw(tx.rawHex), tx, info);\n}\n\n/**\n * The verdict of our own included transaction (observe with an ordering, `includedFinal`).\n * The driver built it, so its bytes read, its call is a canonical `transfer` that sends no\n * value, a node's answer for it carries `contractRet`, and a TRX transfer in a block executed;\n * anything else contradicts the signed transaction or the chain's rules and decides nothing\n * (retryable), as does a token `Transfer` event that does not read.\n */\nexport function verdictOf(codec: TronCodec, tx: TronTxJson, info: TronTxInfo): TxVerdict {\n const raw = codec.readRaw(tx.rawHex);\n if (raw === null) throw malformed('raw_data_hex');\n if (tx.contractRet === undefined) throw malformed('contractRet');\n if (carriesValue(raw.contract)) throw malformed('call value');\n // An included TransferContract executed (java-tron never includes one that\n // failed), so any other answer on our own is impossible: a false `failed` on a proof path\n // would invite a second payment. The chain's view reports what the node says.\n if (\n raw.contract.type === 'TransferContract' &&\n (tx.contractRet !== 'SUCCESS' || info.failed)\n ) {\n throw malformed('contractRet');\n }\n // Our own TRC-20 call is a canonical `transfer(to, amount)` (the builder\n // writes nothing else), so other call data contradicts the signed transaction.\n if (\n raw.contract.type === 'TriggerSmartContract' &&\n decodeTransferCall(raw.contract.data) === null\n ) {\n throw malformed('call data');\n }\n const chain = executed(raw, tx, info);\n if (!chain.success) return chain;\n const evidence = transferEvidence(raw, info);\n if (evidence === 'unreadable') throw malformed('Transfer log');\n return evidence === 'landed'\n ? chain\n : { success: false, reason: 'token transfer not evidenced', failure: 'unevidenced' };\n}\n\nconst UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });\n\n/**\n * The memo (`raw_data.data`) as text: `undefined` without one, `null` when its bytes are not\n * UTF-8 (replacement characters would make two different memos read the same). Any size the\n * chain accepts reads: the driver's own 256-byte cap applies to what it writes.\n */\nfunction memoOf(raw: TronRawData): string | null | undefined {\n if (raw.data === undefined) return undefined;\n try {\n return UTF8.decode(fromHex(raw.data));\n } catch {\n return null;\n }\n}\n\n/** A canonical `T…` address, or `null` for bytes that are not one (never thrown). */\nfunction base58(hex: string): string | null {\n try {\n return toBase58Address(hex);\n } catch {\n return null;\n }\n}\n\n/**\n * Any transaction as the chain reports it. `info` and `blockHash` come together for an\n * included transaction; `pending` marks one the node holds in its pool.\n */\nexport function decodeTransaction(\n codec: TronCodec,\n tx: TronTxJson,\n info: TronTxInfo | null,\n blockHash: string | undefined,\n pending = false,\n): DriverTransaction {\n if (info !== null && blockHash === undefined) throw notServable();\n const raw = codec.readRaw(tx.rawHex);\n const chain = info ? executed(raw, tx, info) : undefined;\n const observation: DriverTxObservation =\n info && chain && blockHash !== undefined\n ? {\n seen: 'block',\n txHash: tx.id,\n blockHeight: info.blockNumber,\n blockHash,\n success: chain.success,\n ...(chain.reason ? { reason: chain.reason } : {}),\n }\n : pending\n ? { seen: 'mempool', txHash: tx.id }\n : { seen: 'none' };\n const memo = raw ? memoOf(raw) : undefined;\n const owner = raw ? base58(raw.contract.owner) : null;\n const transfers: DriverTransfer[] = [];\n let decoding: DriverTransaction['decoding'] = 'complete';\n /** A movement with the memo; `null` (an address that does not read) is left out. */\n const add = (transfer: Omit<DriverTransfer, 'memo'> | null): void => {\n if (!transfer) decoding = 'partial';\n else transfers.push(typeof memo === 'string' ? { ...transfer, memo } : transfer);\n };\n const native = (to: string, amount: bigint) => {\n const recipient = base58(to);\n add(\n owner && recipient\n ? {\n locator: 'native',\n from: [owner],\n to: recipient,\n asset: 'native',\n amount,\n source: 'native',\n }\n : null,\n );\n };\n if (raw === null) {\n decoding = 'none';\n } else if (!info) {\n decoding = 'partial';\n } else if (chain?.success) {\n if (memo === null) decoding = 'partial';\n const { contract } = raw;\n if (contract.type === 'TransferContract') {\n native(contract.to, contract.amount);\n } else {\n // Value can move without a log (internal transfers), and a TRC-10 value has no asset\n // here: a contract call is partial.\n decoding = 'partial';\n if (contract.callValue !== undefined) native(contract.contract, contract.callValue);\n info.logs.forEach((log, index) => {\n const event = decodeTransferLog(log);\n if (!event) return;\n const from = base58(event.from);\n const to = base58(event.to);\n const token = base58(`41${log.address}`);\n add(\n from && to && token\n ? {\n locator: `log:${index}`,\n from: [from],\n to,\n asset: { standard: 'trc20', contract: token },\n amount: event.amount,\n source: 'token-event',\n }\n : null,\n );\n });\n }\n }\n const call = raw?.contract.type === 'TriggerSmartContract' ? raw.contract : undefined;\n return {\n id: tx.id,\n observation,\n ...(info ? { fee: [{ asset: 'native' as const, amount: info.fee }] } : {}),\n transfers,\n decoding,\n // The block's time: the client-set `raw_data.timestamp` is display only.\n ...(info ? { timestamp: info.blockTimestamp } : {}),\n details: {\n contract: raw?.contract.type ?? 'unknown',\n ...(owner ? { owner } : {}),\n ...(tx.contractRet !== undefined ? { result: tx.contractRet } : {}),\n ...(info?.receiptResult !== undefined ? { receipt: info.receiptResult } : {}),\n ...(raw?.feeLimit !== undefined ? { feeLimit: BigInt(raw.feeLimit) } : {}),\n ...(call?.callValue !== undefined ? { callValue: call.callValue } : {}),\n ...(call?.callTokenValue !== undefined\n ? { callTokenValue: call.callTokenValue }\n : {}),\n ...(call?.tokenId !== undefined ? { tokenId: call.tokenId } : {}),\n },\n };\n}\n"]}
|
|
@@ -255,6 +255,7 @@ function createTronProofs(ctx) {
|
|
|
255
255
|
blockHash: header.id,
|
|
256
256
|
txHash: id,
|
|
257
257
|
...(verdict.reason !== undefined ? { reason: verdict.reason } : {}),
|
|
258
|
+
...(verdict.failure !== undefined ? { failure: verdict.failure } : {}),
|
|
258
259
|
};
|
|
259
260
|
}
|
|
260
261
|
const bounds = attemptBounds(ordering);
|