@hwlt/era-connect 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/README.md +25 -5
- package/dist/index.cjs +49 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +22 -2
- package/dist/index.d.ts +22 -2
- package/dist/index.js +47 -1
- package/dist/index.js.map +1 -1
- package/dist/ton-5Uvi5ifg.js +86 -0
- package/dist/ton-5Uvi5ifg.js.map +1 -0
- package/dist/ton-C0UP-cf_.d.ts +51 -0
- package/dist/ton-DUJGXdGa.cjs +97 -0
- package/dist/ton-DUJGXdGa.cjs.map +1 -0
- package/dist/ton-DmeIvknN.d.cts +51 -0
- package/dist/ton.cjs +10 -0
- package/dist/ton.d.cts +3 -0
- package/dist/ton.d.ts +3 -0
- package/dist/ton.js +3 -0
- package/dist/verify.cjs +154 -13
- package/dist/verify.cjs.map +1 -1
- package/dist/verify.d.cts +24 -1
- package/dist/verify.d.ts +24 -1
- package/dist/verify.js +153 -14
- package/dist/verify.js.map +1 -1
- package/package.json +20 -8
- package/ton/package.json +6 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["UrValue","EraAccountsClass","UrValue"],"sources":["../src/registry/multi-accounts.ts","../src/accounts/derive.ts","../src/accounts/accounts.ts","../src/hardware-call/key-derivation.ts","../src/raw.ts","../src/index.ts"],"sourcesContent":["import { cborDecode } from '../cbor/decode';\nimport type { CborValue } from '../cbor/model';\nimport { asArray, asBytes, asMap, asText, asUint, mapGet } from '../cbor/model';\nimport { EraSdkError } from '../core/errors';\nimport { parseUrString, type Ur } from '../ur/ur';\nimport type { PathLevel } from './keypath';\nimport { parsePathComponents } from './keypath';\n\n/**\n * Raw account entry parsed from a `crypto-multi-accounts` (1103) export.\n *\n * `xfp` is the entry's ORIGIN source fingerprint (`crypto-keypath` key 2) —\n * the value a `*-sign-request` keypath must carry. It is NOT the top-level\n * master fingerprint, although the two often coincide.\n */\nexport interface RawAccountEntry {\n readonly path: readonly PathLevel[];\n readonly xfp: number;\n /**\n * Nullable and length-unconstrained, as in the reference implementation: an\n * entry without a usable key still resolves its xfp for signing — only the\n * address-derivation views require the 33/32-byte forms.\n */\n readonly publicKey: Uint8Array | null;\n readonly chainCode: Uint8Array | null;\n readonly parentFingerprint: number | null;\n readonly name: string | null;\n /** A label string (`account.standard`, ...) — NEVER chain metadata. */\n readonly note: string | null;\n}\n\nexport interface RawMultiAccounts {\n readonly masterFingerprint: number;\n readonly deviceName: string | null;\n readonly deviceId: string | null;\n readonly deviceVersion: string | null;\n readonly entries: readonly RawAccountEntry[];\n}\n\n/** UR types a device links a watch-only wallet with. */\nexport const WALLET_UR_TYPES: ReadonlySet<string> = new Set([\n 'crypto-multi-accounts',\n 'crypto-account',\n 'crypto-hdkey',\n]);\n\n/**\n * Parse a wallet-export UR.\n *\n * Of the three admitted link types only the `crypto-multi-accounts` shape\n * yields derivable accounts; an export that yields none is refused rather\n * than stored as an unusable wallet. Malformed entries are skipped\n * individually so one foreign item does not abort the rest.\n */\nexport function parseMultiAccountsUr(input: Ur | string): RawMultiAccounts {\n let type: string;\n let cbor: Uint8Array;\n if (typeof input === 'string') {\n const parsed = parseUrString(input);\n if (parsed.seq !== null) {\n throw new EraSdkError(\n 'invalid-props',\n 'multi-part UR string: assemble it with a UrScanner first',\n );\n }\n type = parsed.type;\n cbor = parsed.payload;\n } else {\n type = input.type;\n cbor = input.cbor;\n }\n\n if (!WALLET_UR_TYPES.has(type)) {\n // The type is attacker-sized (the UR grammar allows an unbounded letter\n // run) — truncate before it reaches a message or error data.\n const shown = type.length > 32 ? `${type.slice(0, 32)}…` : type;\n throw new EraSdkError(\n 'wrong-ur-type',\n `\"${shown}\" is not a wallet export; expected one of ${[...WALLET_UR_TYPES].join(', ')}`,\n { received: shown },\n );\n }\n\n let decoded: CborValue;\n try {\n decoded = cborDecode(cbor);\n } catch (e) {\n throw new EraSdkError('malformed-cbor', `cannot decode wallet UR: ${(e as Error).message}`);\n }\n const root = asMap(decoded);\n if (!root) {\n throw new EraSdkError('malformed-cbor', 'wallet UR is not a CBOR map');\n }\n\n const master = asUint(mapGet(root, 1));\n const list = asArray(mapGet(root, 2));\n if (master === undefined || !list) {\n throw new EraSdkError(\n 'malformed-reply',\n 'wallet UR missing master fingerprint (key 1) or accounts (key 2)',\n );\n }\n\n const entries: RawAccountEntry[] = [];\n for (const item of list) {\n const entry = tryParseEntry(item);\n if (entry) entries.push(entry);\n }\n if (entries.length === 0) {\n throw new EraSdkError(\n 'malformed-reply',\n 'wallet UR carries no account this SDK can derive an address from',\n );\n }\n\n return {\n masterFingerprint: Number(master & 0xffffffffn),\n deviceName: asText(mapGet(root, 3)) ?? null,\n deviceId: asText(mapGet(root, 4)) ?? null,\n deviceVersion: asText(mapGet(root, 5)) ?? null,\n entries,\n };\n}\n\nfunction tryParseEntry(item: CborValue): RawAccountEntry | null {\n const map = asMap(item);\n if (!map) return null;\n const origin = asMap(mapGet(map, 6));\n if (!origin) return null;\n\n const path = parsePathComponents(mapGet(origin, 1));\n const xfp = asUint(mapGet(origin, 2));\n if (!path || path.length === 0 || xfp === undefined || xfp > 0xffffffffn) return null;\n\n const parentFp = asUint(mapGet(map, 8));\n return {\n path,\n xfp: Number(xfp),\n publicKey: asBytes(mapGet(map, 3)) ?? null,\n chainCode: asBytes(mapGet(map, 4)) ?? null,\n parentFingerprint: parentFp !== undefined && parentFp <= 0xffffffffn ? Number(parentFp) : null,\n name: asText(mapGet(map, 9)) ?? null,\n note: asText(mapGet(map, 10)) ?? null,\n };\n}\n","import { secp256k1 } from '@noble/curves/secp256k1';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\nimport { sha256 } from '@noble/hashes/sha2';\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { base58, bech32, createBase58check } from '@scure/base';\nimport { HDKey } from '@scure/bip32';\nimport { bytesToHex, concatBytes, u32be } from '../core/bytes';\nimport { EraSdkError } from '../core/errors';\n\nconst base58check = createBase58check(sha256);\n\n/** Non-hardened BIP-32 child public key from an account-level (publicKey, chainCode). */\nexport function derivePublicKey(\n publicKey: Uint8Array,\n chainCode: Uint8Array,\n change: number,\n index: number,\n): Uint8Array {\n const node = new HDKey({ publicKey, chainCode });\n const child = node.deriveChild(change).deriveChild(index);\n if (!child.publicKey) {\n throw new EraSdkError('invalid-props', 'child derivation produced no public key');\n }\n return child.publicKey;\n}\n\nfunction uncompressed(publicKey33: Uint8Array): Uint8Array {\n return secp256k1.ProjectivePoint.fromHex(publicKey33).toRawBytes(false);\n}\n\n/** EIP-55 checksummed address from a compressed secp256k1 public key. */\nexport function evmAddressFromPublicKey(publicKey33: Uint8Array): `0x${string}` {\n const hash = keccak_256(uncompressed(publicKey33).slice(1));\n const addr = bytesToHex(hash.slice(12));\n const check = keccak_256(new Uint8Array([...addr].map((c) => c.charCodeAt(0))));\n let out = '';\n for (let i = 0; i < addr.length; i++) {\n const nibble = i % 2 === 0 ? check[i >> 1]! >> 4 : check[i >> 1]! & 0x0f;\n out += nibble >= 8 ? addr[i]!.toUpperCase() : addr[i]!;\n }\n return `0x${out}`;\n}\n\nfunction hash160(data: Uint8Array): Uint8Array {\n return ripemd160(sha256(data));\n}\n\n/** P2WPKH (witness v0) bech32 address. */\nexport function btcP2wpkhAddressFromPublicKey(\n publicKey33: Uint8Array,\n hrp: 'bc' | 'tb' = 'bc',\n): string {\n return bech32.encode(hrp, [0, ...bech32.toWords(hash160(publicKey33))]);\n}\n\n/** Legacy P2PKH base58check address (`1...`) — the kind the device signs messages for. */\nexport function btcP2pkhAddressFromPublicKey(publicKey33: Uint8Array, testnet = false): string {\n return base58check.encode(\n concatBytes(new Uint8Array([testnet ? 0x6f : 0x00]), hash160(publicKey33)),\n );\n}\n\n/** Nested segwit (P2SH-P2WPKH) base58check address (`3...`). */\nexport function btcNestedSegwitAddressFromPublicKey(\n publicKey33: Uint8Array,\n testnet = false,\n): string {\n const redeemScript = concatBytes(new Uint8Array([0x00, 0x14]), hash160(publicKey33));\n return base58check.encode(\n concatBytes(new Uint8Array([testnet ? 0xc4 : 0x05]), hash160(redeemScript)),\n );\n}\n\n/** Tron base58check address (0x41-prefixed keccak hash). */\nexport function tronAddressFromPublicKey(publicKey33: Uint8Array): string {\n const hash = keccak_256(uncompressed(publicKey33).slice(1));\n return base58check.encode(concatBytes(new Uint8Array([0x41]), hash.slice(12)));\n}\n\n/** A Solana address IS the Ed25519 public key, base58. */\nexport function solanaAddressFromPublicKey(publicKey32: Uint8Array): string {\n return base58.encode(publicKey32);\n}\n\nconst XPUB_VERSION = 0x0488b21e;\nconst ZPUB_VERSION = 0x04b24746; // SLIP-132, BIP-84 P2WPKH\n\n/** BIP-32 extended public key serialization. */\nexport function serializeExtendedPublicKey(args: {\n version?: number;\n depth: number;\n parentFingerprint: number;\n childNumber: number;\n chainCode: Uint8Array;\n publicKey: Uint8Array;\n}): string {\n const {\n version = XPUB_VERSION,\n depth,\n parentFingerprint,\n childNumber,\n chainCode,\n publicKey,\n } = args;\n if (chainCode.length !== 32 || publicKey.length !== 33) {\n throw new EraSdkError(\n 'invalid-props',\n 'extended key needs a 32-byte chain code and 33-byte key',\n );\n }\n return base58check.encode(\n concatBytes(\n u32be(version),\n new Uint8Array([depth & 0xff]),\n u32be(parentFingerprint),\n u32be(childNumber),\n chainCode,\n publicKey,\n ),\n );\n}\n\nexport { XPUB_VERSION, ZPUB_VERSION };\n","import { EraSdkError } from '../core/errors';\nimport type { PathLevel } from '../registry/keypath';\nimport { formatPath, parsePath, pathEquals, xfpToHex } from '../registry/keypath';\nimport type { RawAccountEntry, RawMultiAccounts } from '../registry/multi-accounts';\nimport { parseMultiAccountsUr } from '../registry/multi-accounts';\nimport type { Ur } from '../ur/ur';\nimport {\n btcNestedSegwitAddressFromPublicKey,\n btcP2pkhAddressFromPublicKey,\n btcP2wpkhAddressFromPublicKey,\n derivePublicKey,\n evmAddressFromPublicKey,\n serializeExtendedPublicKey,\n solanaAddressFromPublicKey,\n tronAddressFromPublicKey,\n ZPUB_VERSION,\n} from './derive';\n\n/** Chain family of an exported account, matched by its derivation path — never by the note label. */\nexport type AccountChain = 'evm' | 'btc' | 'solana' | 'tron' | 'unknown';\n\nexport interface AccountKey {\n readonly chain: AccountChain;\n /** Account-level derivation path, e.g. `m/44'/60'/0'`. */\n readonly path: string;\n /**\n * The source fingerprint a `*-sign-request` keypath must carry for this\n * account (lowercase 8-hex). NOT necessarily the master fingerprint.\n */\n readonly xfp: string;\n /** 33-byte compressed secp256k1, or 32-byte Ed25519 (Solana); absent when the export omitted it. */\n readonly publicKey: Uint8Array | undefined;\n readonly chainCode: Uint8Array | undefined;\n readonly name: string | undefined;\n /** Derivation-scheme label (`account.standard`, ...) — display only. */\n readonly note: string | undefined;\n}\n\nexport interface DeviceInfo {\n readonly name: string | undefined;\n readonly id: string | undefined;\n readonly firmwareVersion: string | undefined;\n}\n\nfunction classify(path: readonly PathLevel[]): AccountChain {\n const p0 = path[0];\n const p1 = path[1];\n if (!p0 || !p1 || !p0.hardened || !p1.hardened) return 'unknown';\n if (p0.index === 44 && p1.index === 60) return 'evm';\n if (\n p1.index === 0 &&\n (p0.index === 84 || p0.index === 49 || p0.index === 44 || p0.index === 86)\n ) {\n return 'btc';\n }\n if (p0.index === 44 && p1.index === 501) return 'solana';\n if (p0.index === 44 && p1.index === 195) return 'tron';\n return 'unknown';\n}\n\nfunction withChainCode(entry: RawAccountEntry): Uint8Array {\n if (!entry.chainCode) {\n throw new EraSdkError(\n 'account-not-found',\n `account ${formatPath([...entry.path])} carries no chain code; cannot derive children`,\n );\n }\n return entry.chainCode;\n}\n\n/** The entry's key at the required length, or a typed refusal (derivation only). */\nfunction requireKey(entry: RawAccountEntry, length: number): Uint8Array {\n if (!entry.publicKey || entry.publicKey.length !== length) {\n throw new EraSdkError(\n 'invalid-props',\n `account ${formatPath([...entry.path])} carries no ${length}-byte public key; ` +\n 'xfp lookup still works, address derivation does not',\n );\n }\n return entry.publicKey;\n}\n\n/** EVM view over the linked wallet: one account xpub, addresses derived at `0/index`. */\nexport class EvmAccountView {\n constructor(private readonly entry: RawAccountEntry) {}\n\n get xfp(): string {\n return xfpToHex(this.entry.xfp);\n }\n\n get accountPath(): string {\n return formatPath([...this.entry.path]);\n }\n\n /** Signing path for address `index`: `<account>/0/<index>`. */\n pathFor(index: number): string {\n return `${this.accountPath}/0/${index}`;\n }\n\n deriveAddress(index: number): `0x${string}` {\n return evmAddressFromPublicKey(\n derivePublicKey(requireKey(this.entry, 33), withChainCode(this.entry), 0, index),\n );\n }\n\n xpub(): string {\n return extendedKeyOf(this.entry);\n }\n}\n\nexport type BtcPurpose = 44 | 49 | 84 | 86;\n\n/**\n * Bitcoin view over one exported account. The default is the BIP-84\n * native-segwit account; pass `purpose` to reach the other script types the\n * device exports (44 = legacy P2PKH — the kind the device signs MESSAGES for,\n * 49 = nested segwit, 86 = taproot).\n */\nexport class BtcAccountView {\n constructor(\n private readonly entry: RawAccountEntry,\n private readonly testnet: boolean,\n readonly purpose: BtcPurpose,\n ) {}\n\n get xfp(): string {\n return xfpToHex(this.entry.xfp);\n }\n\n get accountPath(): string {\n return formatPath([...this.entry.path]);\n }\n\n receivePath(index: number): string {\n return `${this.accountPath}/0/${index}`;\n }\n\n changePath(index: number): string {\n return `${this.accountPath}/1/${index}`;\n }\n\n deriveAddress(index: number, options?: { change?: boolean }): string {\n const change = options?.change ? 1 : 0;\n const child = derivePublicKey(\n requireKey(this.entry, 33),\n withChainCode(this.entry),\n change,\n index,\n );\n switch (this.purpose) {\n case 84:\n return btcP2wpkhAddressFromPublicKey(child, this.testnet ? 'tb' : 'bc');\n case 44:\n return btcP2pkhAddressFromPublicKey(child, this.testnet);\n case 49:\n return btcNestedSegwitAddressFromPublicKey(child, this.testnet);\n case 86:\n throw new EraSdkError(\n 'invalid-props',\n 'taproot addresses need the BIP-341 output-key tweak; derive them from xpub() with your Bitcoin library',\n );\n }\n }\n\n xpub(): string {\n return extendedKeyOf(this.entry);\n }\n\n /** SLIP-132 zpub form of the BIP-84 key, for tools that require it. */\n zpub(): string {\n if (this.purpose !== 84) {\n throw new EraSdkError(\n 'invalid-props',\n 'zpub is the SLIP-132 form of the BIP-84 account only',\n );\n }\n return extendedKeyOf(this.entry, ZPUB_VERSION);\n }\n}\n\n/** Tron view: addresses derived at `0/index`. */\nexport class TronAccountView {\n constructor(private readonly entry: RawAccountEntry) {}\n\n get xfp(): string {\n return xfpToHex(this.entry.xfp);\n }\n\n get accountPath(): string {\n return formatPath([...this.entry.path]);\n }\n\n pathFor(index: number): string {\n return `${this.accountPath}/0/${index}`;\n }\n\n deriveAddress(index: number): string {\n return tronAddressFromPublicKey(\n derivePublicKey(requireKey(this.entry, 33), withChainCode(this.entry), 0, index),\n );\n }\n}\n\n/**\n * Solana view: Ed25519 has no public child derivation, so the device\n * pre-derives hardened accounts (`m/44'/501'/idx'`) and each entry IS a\n * signer. The public key, base58, IS the address.\n */\nexport class SolanaAccountView {\n constructor(private readonly entry: RawAccountEntry) {}\n\n get xfp(): string {\n return xfpToHex(this.entry.xfp);\n }\n\n get path(): string {\n return formatPath([...this.entry.path]);\n }\n\n /** The hardened account index (third path level). */\n get index(): number {\n return this.entry.path[2]?.index ?? 0;\n }\n\n get publicKey(): Uint8Array {\n return requireKey(this.entry, 32);\n }\n\n get address(): string {\n return solanaAddressFromPublicKey(requireKey(this.entry, 32));\n }\n}\n\nfunction extendedKeyOf(entry: RawAccountEntry, version?: number): string {\n const chainCode = withChainCode(entry);\n const publicKey = requireKey(entry, 33);\n const last = entry.path[entry.path.length - 1]!;\n const args = {\n depth: entry.path.length,\n parentFingerprint: entry.parentFingerprint ?? 0,\n childNumber: last.hardened ? last.index + 0x80000000 : last.index,\n chainCode,\n publicKey,\n };\n return version === undefined\n ? serializeExtendedPublicKey(args)\n : serializeExtendedPublicKey({ ...args, version });\n}\n\n/**\n * The linked wallet: everything a software wallet extracts from the device's\n * `crypto-multi-accounts` QR. Parse once, store the source UR string, derive\n * addresses locally — the device is not needed again until signing.\n */\nexport class EraAccounts {\n private constructor(\n private readonly raw: RawMultiAccounts,\n readonly sourceUr: string | undefined,\n ) {}\n\n static fromUr(input: Ur | string): EraAccounts {\n const raw = parseMultiAccountsUr(input);\n return new EraAccounts(raw, typeof input === 'string' ? input : input.toString());\n }\n\n /** Master fingerprint, lowercase 8-hex. */\n get masterFingerprint(): string {\n return xfpToHex(this.raw.masterFingerprint);\n }\n\n get device(): DeviceInfo {\n return {\n name: this.raw.deviceName ?? undefined,\n id: this.raw.deviceId ?? undefined,\n firmwareVersion: this.raw.deviceVersion ?? undefined,\n };\n }\n\n get keys(): AccountKey[] {\n return this.raw.entries.map((entry) => ({\n chain: classify(entry.path),\n path: formatPath([...entry.path]),\n xfp: xfpToHex(entry.xfp),\n publicKey: entry.publicKey ?? undefined,\n chainCode: entry.chainCode ?? undefined,\n name: entry.name ?? undefined,\n note: entry.note ?? undefined,\n }));\n }\n\n /**\n * The xfp a sign request must carry for the account whose path exactly\n * equals `accountPath`. Throws `account-not-found` — never a silent zero.\n */\n xfpFor(accountPath: string): string {\n return xfpToHex(this.entryFor(accountPath).xfp);\n }\n\n /** The EVM account (standard `m/44'/60'/...` scheme), if the export carries one. */\n evm(): EvmAccountView | undefined {\n const entry =\n this.raw.entries.find(\n (e) => classify(e.path) === 'evm' && (e.note === null || e.note === 'account.standard'),\n ) ?? this.raw.entries.find((e) => classify(e.path) === 'evm');\n return entry ? new EvmAccountView(entry) : undefined;\n }\n\n /**\n * A Bitcoin account view. Defaults to the BIP-84 native-segwit account;\n * pass `purpose: 44` for the legacy P2PKH account (message signing), 49 for\n * nested segwit, 86 for taproot — if the export carries them.\n */\n btc(options?: { testnet?: boolean; purpose?: BtcPurpose }): BtcAccountView | undefined {\n const purpose = options?.purpose ?? 84;\n const entry = this.raw.entries.find(\n (e) => classify(e.path) === 'btc' && e.path[0]?.index === purpose,\n );\n return entry ? new BtcAccountView(entry, options?.testnet ?? false, purpose) : undefined;\n }\n\n tron(): TronAccountView | undefined {\n const entry = this.raw.entries.find((e) => classify(e.path) === 'tron');\n return entry ? new TronAccountView(entry) : undefined;\n }\n\n /** All pre-derived Solana signers (usually `m/44'/501'/0'..9'`). */\n solana(): SolanaAccountView[] {\n return this.raw.entries\n .filter((e) => classify(e.path) === 'solana' && e.publicKey?.length === 32)\n .map((e) => new SolanaAccountView(e));\n }\n\n private entryFor(accountPath: string): RawAccountEntry {\n const levels = parsePath(accountPath);\n const entry = this.raw.entries.find((e) => pathEquals(e.path, levels));\n if (!entry) {\n throw new EraSdkError(\n 'account-not-found',\n `the linked wallet carries no account at ${accountPath}`,\n { path: accountPath },\n );\n }\n return entry;\n }\n}\n","import type { EraAccounts } from '../accounts/accounts';\nimport { EraAccounts as EraAccountsClass } from '../accounts/accounts';\nimport { cborEncode } from '../cbor/encode';\nimport type { CborValue } from '../cbor/model';\nimport { cbArray, cbMap, cbTag, cbText, cbUint } from '../cbor/model';\nimport type { ChainContext } from '../chains/shared';\nimport { EraSdkError } from '../core/errors';\nimport type { AnimatedUrOptions } from '../qr/animated-ur';\nimport { AnimatedUr } from '../qr/animated-ur';\nimport { keypath304, parsePath } from '../registry/keypath';\nimport { WALLET_UR_TYPES } from '../registry/multi-accounts';\nimport { TypedUrScanner } from '../scan/ur-scanner';\nimport type { Ur } from '../ur/ur';\nimport { Ur as UrValue } from '../ur/ur';\n\nexport type DerivationCurve = 'secp256k1' | 'ed25519';\nexport type DerivationAlgorithm = 'slip10' | 'bip32ed25519';\n\nexport interface KeyDerivationSchema {\n /** The derivation path to request, e.g. `m/44'/60'/0'`. */\n readonly path: string;\n /** Defaults to `secp256k1`. */\n readonly curve?: DerivationCurve;\n /** Defaults to `slip10`. */\n readonly algo?: DerivationAlgorithm;\n /** Optional chain hint shown by the device. */\n readonly chainType?: string;\n}\n\nexport interface KeyDerivationCallProps {\n readonly schemas: readonly KeyDerivationSchema[];\n readonly origin?: string;\n}\n\n/** The pull-model linking request: display it, then scan the device's account export back. */\nexport interface HardwareCallRequest {\n readonly ur: Ur;\n readonly replyTypes: readonly string[];\n toAnimated(options?: AnimatedUrOptions): AnimatedUr;\n scanner(): TypedUrScanner<EraAccounts>;\n}\n\nconst CURVES: Record<DerivationCurve, number> = { secp256k1: 0, ed25519: 1 };\nconst ALGOS: Record<DerivationAlgorithm, number> = { slip10: 0, bip32ed25519: 1 };\n\n/**\n * Build a `qr-hardware-call` (1201) wrapping a `key-derivation-call` (1301):\n * the WALLET asks the device for specific derivation paths, curves and\n * algorithms instead of accepting whatever the device's sync screen\n * volunteers. The device answers with a `crypto-multi-accounts` export, which\n * closes the loop through `parseAccounts`.\n *\n * Registry shape (Keystone-standard):\n * `1201({1: type=0, 2: 1301({1: [1302({1: 304(keypath), 2: curve, 3: algo, 4?: chainType})...]}), 3?: origin})`.\n */\nexport function generateKeyDerivationCall(\n context: ChainContext,\n props: KeyDerivationCallProps,\n): HardwareCallRequest {\n if (props.schemas.length === 0) {\n throw new EraSdkError('invalid-props', 'at least one derivation schema is required');\n }\n const schemas: CborValue[] = props.schemas.map((schema) => {\n const levels = parsePath(schema.path);\n const entries: [number, CborValue][] = [\n [1, keypath304(levels)],\n [2, cbUint(CURVES[schema.curve ?? 'secp256k1'])],\n [3, cbUint(ALGOS[schema.algo ?? 'slip10'])],\n ];\n if (schema.chainType !== undefined) entries.push([4, cbText(schema.chainType)]);\n return cbTag(1302, cbMap(entries));\n });\n\n const call = cbTag(1301, cbMap([[1, cbArray(schemas)]]));\n const root = cbMap([\n [1, cbUint(0)], // type: KeyDerivation\n [2, call],\n [3, cbText(props.origin ?? context.origin)],\n ]);\n\n const ur = new UrValue('qr-hardware-call', cborEncode(root));\n const replyTypes = [...WALLET_UR_TYPES];\n return {\n ur,\n replyTypes,\n toAnimated: (options?: AnimatedUrOptions) =>\n new AnimatedUr(ur, {\n maxFragmentLength: options?.maxFragmentLength ?? context.maxFragmentLength,\n }),\n scanner: () =>\n new TypedUrScanner<EraAccounts>({ expectedTypes: replyTypes }, (reply) =>\n EraAccountsClass.fromUr(reply),\n ),\n };\n}\n","import type { ChainContext } from './chains/shared';\nimport { toUr } from './chains/shared';\nimport type { AnimatedUrOptions } from './qr/animated-ur';\nimport { AnimatedUr } from './qr/animated-ur';\nimport type { Ur } from './ur/ur';\nimport { Ur as UrValue } from './ur/ur';\n\n/**\n * Escape hatch for UR types this SDK has no dedicated module for (future\n * chains, custom registry items). You bring the CBOR; the SDK brings the UR\n * plumbing, fountain frames and the hardened scanner\n * (`EraConnect.scanner({expectedTypes})`).\n */\nexport class RawModule {\n constructor(private readonly context: ChainContext) {}\n\n /** Wrap raw CBOR bytes in a UR of the given registry type. */\n ur(type: string, cbor: Uint8Array): Ur {\n return new UrValue(type, cbor);\n }\n\n /** Parse a single-part `ur:` string into a Ur. */\n parse(text: string): Ur {\n return toUr(text);\n }\n\n /** Fragment + animate any UR. */\n animate(ur: Ur, options?: AnimatedUrOptions): AnimatedUr {\n return new AnimatedUr(ur, {\n maxFragmentLength: options?.maxFragmentLength ?? this.context.maxFragmentLength,\n });\n }\n}\n","/**\n * ERA Connect SDK — air-gapped UR/QR linking and signing for the ERA\n * hardware wallet.\n *\n * Headless by design: you render the QR codes and own the camera; the SDK\n * owns every byte of the protocol. No network I/O, no Node built-ins,\n * `Uint8Array` end-to-end.\n */\n\nimport type { EraAccounts as EraAccountsType } from './accounts/accounts';\nimport { EraAccounts } from './accounts/accounts';\nimport { BtcChain } from './chains/btc';\nimport { EvmChain } from './chains/evm';\nimport type { ChainContext, EraConnectConfig } from './chains/shared';\nimport { resolveContext } from './chains/shared';\nimport { SolanaChain } from './chains/solana';\nimport { TronChain } from './chains/tron';\nimport type { HardwareCallRequest, KeyDerivationCallProps } from './hardware-call/key-derivation';\nimport { generateKeyDerivationCall } from './hardware-call/key-derivation';\nimport { RawModule } from './raw';\nimport type { UrScannerOptions } from './scan/ur-scanner';\nimport { UrScanner } from './scan/ur-scanner';\nimport type { Ur } from './ur/ur';\n\n/** Timing/size constants of the device's own QR pipeline, for progress UI and timeouts. */\nexport const DeviceProfile = {\n /** What the phone displays to the device: ~200 wire bytes per frame at 8 fps. */\n phoneToDevice: { fragmentBytesOnWire: 200, payloadBytes: 180, frameIntervalMs: 125 },\n /**\n * What the device displays back: 150-byte fragments at 2.5 fps. Receiving\n * is SLOWER than sending — budget scan timeouts accordingly.\n */\n deviceToPhone: { fragmentBytesOnWire: 150, frameIntervalMs: 400 },\n} as const;\n\n/** The SDK facade. Cheap to construct; chain modules are created lazily. */\nexport class EraConnect {\n private readonly context: ChainContext;\n private _evm: EvmChain | undefined;\n private _btc: BtcChain | undefined;\n private _solana: SolanaChain | undefined;\n private _tron: TronChain | undefined;\n private _raw: RawModule | undefined;\n\n constructor(config?: EraConnectConfig) {\n this.context = resolveContext(config);\n }\n\n get evm(): EvmChain {\n this._evm ??= new EvmChain(this.context);\n return this._evm;\n }\n\n get btc(): BtcChain {\n this._btc ??= new BtcChain(this.context);\n return this._btc;\n }\n\n get solana(): SolanaChain {\n this._solana ??= new SolanaChain(this.context);\n return this._solana;\n }\n\n get tron(): TronChain {\n this._tron ??= new TronChain(this.context);\n return this._tron;\n }\n\n /** Escape hatch for UR types without a dedicated module. */\n get raw(): RawModule {\n this._raw ??= new RawModule(this.context);\n return this._raw;\n }\n\n /**\n * Linking: parse the device's `crypto-multi-accounts` export (a `Ur` from a\n * scanner, or a single-part `ur:` string).\n */\n parseAccounts(input: Ur | string): EraAccountsType {\n return EraAccounts.fromUr(input);\n }\n\n /**\n * Pull-model linking: ask the device for SPECIFIC derivations\n * (`qr-hardware-call` 1201). The device answers with a\n * `crypto-multi-accounts` export.\n */\n generateKeyDerivationCall(props: KeyDerivationCallProps): HardwareCallRequest {\n return generateKeyDerivationCall(this.context, props);\n }\n\n /** A type-agnostic hardened scanner (linking flows, raw flows). */\n scanner(options?: UrScannerOptions): UrScanner {\n return new UrScanner(options);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public types & modules\n// ---------------------------------------------------------------------------\n\nexport type { AccountChain, AccountKey, BtcPurpose, DeviceInfo } from './accounts/accounts';\nexport {\n BtcAccountView,\n EraAccounts,\n EvmAccountView,\n SolanaAccountView,\n TronAccountView,\n} from './accounts/accounts';\nexport type {\n BtcMessageSignatureResult,\n BtcMessageSignRequestProps,\n BtcPsbtResult,\n BtcPsbtSignRequestProps,\n} from './chains/btc';\nexport { BtcChain } from './chains/btc';\nexport type { EvmSignatureResult, EvmSignRequestProps } from './chains/evm';\nexport { EvmChain, EvmDataType } from './chains/evm';\nexport type {\n ChainContext,\n EraConnectConfig,\n ExpectedReply,\n SignRequest,\n} from './chains/shared';\nexport { DEFAULT_ORIGIN } from './chains/shared';\nexport type { SolSignatureResult, SolSignRequestProps } from './chains/solana';\nexport { SolanaChain, SolSignType } from './chains/solana';\nexport type { TronLatestBlock, TronSignatureResult, TronSignRequestProps } from './chains/tron';\nexport { TronChain } from './chains/tron';\n// UTF-8 helpers that work on every Hermes version (TextEncoder does not):\nexport { utf8Decode, utf8Encode } from './core/bytes';\nexport type { EraErrorCode } from './core/errors';\nexport { EraSdkError } from './core/errors';\nexport type { RandomBytesFn } from './core/rand';\nexport type {\n DerivationAlgorithm,\n DerivationCurve,\n HardwareCallRequest,\n KeyDerivationCallProps,\n KeyDerivationSchema,\n} from './hardware-call/key-derivation';\nexport type { AnimatedUrOptions } from './qr/animated-ur';\nexport { AnimatedUr, DEFAULT_FRAGMENT_LENGTH } from './qr/animated-ur';\nexport { RawModule } from './raw';\nexport type { ScanFeedResult, ScanRejection, UrScannerOptions } from './scan/ur-scanner';\nexport { TypedUrScanner, UrScanner } from './scan/ur-scanner';\nexport { UrLimits } from './ur/limits';\nexport { Ur } from './ur/ur';\n"],"mappings":";;;;;;;;;;;;;AAwCA,MAAa,kCAAuC,IAAI,IAAI;CAC1D;CACA;CACA;AACF,CAAC;;;;;;;;;AAUD,SAAgB,qBAAqB,OAAsC;CACzE,IAAI;CACJ,IAAI;CACJ,IAAI,OAAO,UAAU,UA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AAK,OAAS,IAAI,SAAS,KAAK,OAAO;EACvC,OAAO,KAAK;CACd;CAEA,IAAI,MAAgB;EAClB,KAAK,SAAL,KAAK,OAAS,IAAI,SAAS,KAAK,OAAO;EACvC,OAAO,KAAK;CACd;CAEA,IAAI,SAAsB;EACxB,KAAK,YAAL,KAAK,UAAY,IAAI,YAAY,KAAK,OAAO;EAC7C,OAAO,KAAK;CACd;CAEA,IAAI,OAAkB;EACpB,KAAK,UAAL,KAAK,QAAU,IAAI,UAAU,KAAK,OAAO;EACzC,OAAO,KAAK;CACd;;CAGA,IAAI,MAAiB;EACnB,KAAK,SAAL,KAAK,OAAS,IAAI,UAAU,KAAK,OAAO;EACxC,OAAO,KAAK;CACd;;;;;CAMA,cAAc,OAAqC;EACjD,OAAO,YAAY,OAAO,KAAK;CACjC;;;;;;CAOA,0BAA0B,OAAoD;EAC5E,OAAO,0BAA0B,KAAK,SAAS,KAAK;CACtD;;CAGA,QAAQ,SAAuC;EAC7C,OAAO,IAAI,UAAU,OAAO;CAC9B;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["UrValue","EraAccountsClass","UrValue"],"sources":["../src/registry/multi-accounts.ts","../src/accounts/derive.ts","../src/accounts/accounts.ts","../src/hardware-call/key-derivation.ts","../src/raw.ts","../src/index.ts"],"sourcesContent":["import { cborDecode } from '../cbor/decode';\nimport type { CborValue } from '../cbor/model';\nimport { asArray, asBytes, asMap, asText, asUint, mapGet } from '../cbor/model';\nimport { EraSdkError } from '../core/errors';\nimport { parseUrString, type Ur } from '../ur/ur';\nimport type { PathLevel } from './keypath';\nimport { parsePathComponents } from './keypath';\n\n/**\n * Raw account entry parsed from a `crypto-multi-accounts` (1103) export.\n *\n * `xfp` is the entry's ORIGIN source fingerprint (`crypto-keypath` key 2) —\n * the value a `*-sign-request` keypath must carry. It is NOT the top-level\n * master fingerprint, although the two often coincide.\n */\nexport interface RawAccountEntry {\n readonly path: readonly PathLevel[];\n readonly xfp: number;\n /**\n * Nullable and length-unconstrained, as in the reference implementation: an\n * entry without a usable key still resolves its xfp for signing — only the\n * address-derivation views require the 33/32-byte forms.\n */\n readonly publicKey: Uint8Array | null;\n readonly chainCode: Uint8Array | null;\n readonly parentFingerprint: number | null;\n readonly name: string | null;\n /** A label string (`account.standard`, ...) — NEVER chain metadata. */\n readonly note: string | null;\n}\n\nexport interface RawMultiAccounts {\n readonly masterFingerprint: number;\n readonly deviceName: string | null;\n readonly deviceId: string | null;\n readonly deviceVersion: string | null;\n readonly entries: readonly RawAccountEntry[];\n}\n\n/** UR types a device links a watch-only wallet with. */\nexport const WALLET_UR_TYPES: ReadonlySet<string> = new Set([\n 'crypto-multi-accounts',\n 'crypto-account',\n 'crypto-hdkey',\n]);\n\n/**\n * Parse a wallet-export UR.\n *\n * Of the three admitted link types only the `crypto-multi-accounts` shape\n * yields derivable accounts; an export that yields none is refused rather\n * than stored as an unusable wallet. Malformed entries are skipped\n * individually so one foreign item does not abort the rest.\n */\nexport function parseMultiAccountsUr(input: Ur | string): RawMultiAccounts {\n let type: string;\n let cbor: Uint8Array;\n if (typeof input === 'string') {\n const parsed = parseUrString(input);\n if (parsed.seq !== null) {\n throw new EraSdkError(\n 'invalid-props',\n 'multi-part UR string: assemble it with a UrScanner first',\n );\n }\n type = parsed.type;\n cbor = parsed.payload;\n } else {\n type = input.type;\n cbor = input.cbor;\n }\n\n if (!WALLET_UR_TYPES.has(type)) {\n // The type is attacker-sized (the UR grammar allows an unbounded letter\n // run) — truncate before it reaches a message or error data.\n const shown = type.length > 32 ? `${type.slice(0, 32)}…` : type;\n throw new EraSdkError(\n 'wrong-ur-type',\n `\"${shown}\" is not a wallet export; expected one of ${[...WALLET_UR_TYPES].join(', ')}`,\n { received: shown },\n );\n }\n\n let decoded: CborValue;\n try {\n decoded = cborDecode(cbor);\n } catch (e) {\n throw new EraSdkError('malformed-cbor', `cannot decode wallet UR: ${(e as Error).message}`);\n }\n const root = asMap(decoded);\n if (!root) {\n throw new EraSdkError('malformed-cbor', 'wallet UR is not a CBOR map');\n }\n\n // A standalone `crypto-hdkey` export (the single-account link some wallet\n // profiles use — e.g. the TON one: `{3: key, 6: keypath, 10: name}`) IS the\n // entry map itself: no master-fingerprint/list wrapper. The entry's origin\n // fingerprint doubles as the master fingerprint.\n if (type === 'crypto-hdkey') {\n const entry = tryParseEntry(decoded);\n if (!entry) {\n throw new EraSdkError(\n 'malformed-reply',\n 'crypto-hdkey export carries no derivable account (missing origin keypath)',\n );\n }\n return {\n masterFingerprint: entry.xfp,\n deviceName: null,\n deviceId: null,\n deviceVersion: null,\n entries: [entry],\n };\n }\n\n const master = asUint(mapGet(root, 1));\n const list = asArray(mapGet(root, 2));\n if (master === undefined || !list) {\n throw new EraSdkError(\n 'malformed-reply',\n 'wallet UR missing master fingerprint (key 1) or accounts (key 2)',\n );\n }\n\n const entries: RawAccountEntry[] = [];\n for (const item of list) {\n const entry = tryParseEntry(item);\n if (entry) entries.push(entry);\n }\n if (entries.length === 0) {\n throw new EraSdkError(\n 'malformed-reply',\n 'wallet UR carries no account this SDK can derive an address from',\n );\n }\n\n return {\n masterFingerprint: Number(master & 0xffffffffn),\n deviceName: asText(mapGet(root, 3)) ?? null,\n deviceId: asText(mapGet(root, 4)) ?? null,\n deviceVersion: asText(mapGet(root, 5)) ?? null,\n entries,\n };\n}\n\nfunction tryParseEntry(item: CborValue): RawAccountEntry | null {\n const map = asMap(item);\n if (!map) return null;\n const origin = asMap(mapGet(map, 6));\n if (!origin) return null;\n\n const path = parsePathComponents(mapGet(origin, 1));\n const xfp = asUint(mapGet(origin, 2));\n if (!path || path.length === 0 || xfp === undefined || xfp > 0xffffffffn) return null;\n\n const parentFp = asUint(mapGet(map, 8));\n return {\n path,\n xfp: Number(xfp),\n publicKey: asBytes(mapGet(map, 3)) ?? null,\n chainCode: asBytes(mapGet(map, 4)) ?? null,\n parentFingerprint: parentFp !== undefined && parentFp <= 0xffffffffn ? Number(parentFp) : null,\n name: asText(mapGet(map, 9)) ?? null,\n note: asText(mapGet(map, 10)) ?? null,\n };\n}\n","import { secp256k1 } from '@noble/curves/secp256k1';\nimport { ripemd160 } from '@noble/hashes/ripemd160';\nimport { sha256 } from '@noble/hashes/sha2';\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { base58, bech32, createBase58check } from '@scure/base';\nimport { HDKey } from '@scure/bip32';\nimport { bytesToHex, concatBytes, u32be } from '../core/bytes';\nimport { EraSdkError } from '../core/errors';\n\nconst base58check = createBase58check(sha256);\n\n/** Non-hardened BIP-32 child public key from an account-level (publicKey, chainCode). */\nexport function derivePublicKey(\n publicKey: Uint8Array,\n chainCode: Uint8Array,\n change: number,\n index: number,\n): Uint8Array {\n const node = new HDKey({ publicKey, chainCode });\n const child = node.deriveChild(change).deriveChild(index);\n if (!child.publicKey) {\n throw new EraSdkError('invalid-props', 'child derivation produced no public key');\n }\n return child.publicKey;\n}\n\nfunction uncompressed(publicKey33: Uint8Array): Uint8Array {\n return secp256k1.ProjectivePoint.fromHex(publicKey33).toRawBytes(false);\n}\n\n/** EIP-55 checksummed address from a compressed secp256k1 public key. */\nexport function evmAddressFromPublicKey(publicKey33: Uint8Array): `0x${string}` {\n const hash = keccak_256(uncompressed(publicKey33).slice(1));\n const addr = bytesToHex(hash.slice(12));\n const check = keccak_256(new Uint8Array([...addr].map((c) => c.charCodeAt(0))));\n let out = '';\n for (let i = 0; i < addr.length; i++) {\n const nibble = i % 2 === 0 ? check[i >> 1]! >> 4 : check[i >> 1]! & 0x0f;\n out += nibble >= 8 ? addr[i]!.toUpperCase() : addr[i]!;\n }\n return `0x${out}`;\n}\n\nfunction hash160(data: Uint8Array): Uint8Array {\n return ripemd160(sha256(data));\n}\n\n/** P2WPKH (witness v0) bech32 address. */\nexport function btcP2wpkhAddressFromPublicKey(\n publicKey33: Uint8Array,\n hrp: 'bc' | 'tb' = 'bc',\n): string {\n return bech32.encode(hrp, [0, ...bech32.toWords(hash160(publicKey33))]);\n}\n\n/** Legacy P2PKH base58check address (`1...`) — the kind the device signs messages for. */\nexport function btcP2pkhAddressFromPublicKey(publicKey33: Uint8Array, testnet = false): string {\n return base58check.encode(\n concatBytes(new Uint8Array([testnet ? 0x6f : 0x00]), hash160(publicKey33)),\n );\n}\n\n/** Nested segwit (P2SH-P2WPKH) base58check address (`3...`). */\nexport function btcNestedSegwitAddressFromPublicKey(\n publicKey33: Uint8Array,\n testnet = false,\n): string {\n const redeemScript = concatBytes(new Uint8Array([0x00, 0x14]), hash160(publicKey33));\n return base58check.encode(\n concatBytes(new Uint8Array([testnet ? 0xc4 : 0x05]), hash160(redeemScript)),\n );\n}\n\n/** Tron base58check address (0x41-prefixed keccak hash). */\nexport function tronAddressFromPublicKey(publicKey33: Uint8Array): string {\n const hash = keccak_256(uncompressed(publicKey33).slice(1));\n return base58check.encode(concatBytes(new Uint8Array([0x41]), hash.slice(12)));\n}\n\n/** A Solana address IS the Ed25519 public key, base58. */\nexport function solanaAddressFromPublicKey(publicKey32: Uint8Array): string {\n return base58.encode(publicKey32);\n}\n\nconst XPUB_VERSION = 0x0488b21e;\nconst ZPUB_VERSION = 0x04b24746; // SLIP-132, BIP-84 P2WPKH\n\n/** BIP-32 extended public key serialization. */\nexport function serializeExtendedPublicKey(args: {\n version?: number;\n depth: number;\n parentFingerprint: number;\n childNumber: number;\n chainCode: Uint8Array;\n publicKey: Uint8Array;\n}): string {\n const {\n version = XPUB_VERSION,\n depth,\n parentFingerprint,\n childNumber,\n chainCode,\n publicKey,\n } = args;\n if (chainCode.length !== 32 || publicKey.length !== 33) {\n throw new EraSdkError(\n 'invalid-props',\n 'extended key needs a 32-byte chain code and 33-byte key',\n );\n }\n return base58check.encode(\n concatBytes(\n u32be(version),\n new Uint8Array([depth & 0xff]),\n u32be(parentFingerprint),\n u32be(childNumber),\n chainCode,\n publicKey,\n ),\n );\n}\n\nexport { XPUB_VERSION, ZPUB_VERSION };\n","import { EraSdkError } from '../core/errors';\nimport type { PathLevel } from '../registry/keypath';\nimport { formatPath, parsePath, pathEquals, xfpToHex } from '../registry/keypath';\nimport type { RawAccountEntry, RawMultiAccounts } from '../registry/multi-accounts';\nimport { parseMultiAccountsUr } from '../registry/multi-accounts';\nimport type { Ur } from '../ur/ur';\nimport {\n btcNestedSegwitAddressFromPublicKey,\n btcP2pkhAddressFromPublicKey,\n btcP2wpkhAddressFromPublicKey,\n derivePublicKey,\n evmAddressFromPublicKey,\n serializeExtendedPublicKey,\n solanaAddressFromPublicKey,\n tronAddressFromPublicKey,\n ZPUB_VERSION,\n} from './derive';\n\n/** Chain family of an exported account, matched by its derivation path — never by the note label. */\nexport type AccountChain = 'evm' | 'btc' | 'solana' | 'tron' | 'ton' | 'unknown';\n\nexport interface AccountKey {\n readonly chain: AccountChain;\n /** Account-level derivation path, e.g. `m/44'/60'/0'`. */\n readonly path: string;\n /**\n * The source fingerprint a `*-sign-request` keypath must carry for this\n * account (lowercase 8-hex). NOT necessarily the master fingerprint.\n */\n readonly xfp: string;\n /** 33-byte compressed secp256k1, or 32-byte Ed25519 (Solana); absent when the export omitted it. */\n readonly publicKey: Uint8Array | undefined;\n readonly chainCode: Uint8Array | undefined;\n readonly name: string | undefined;\n /** Derivation-scheme label (`account.standard`, ...) — display only. */\n readonly note: string | undefined;\n}\n\nexport interface DeviceInfo {\n readonly name: string | undefined;\n readonly id: string | undefined;\n readonly firmwareVersion: string | undefined;\n}\n\nfunction classify(path: readonly PathLevel[]): AccountChain {\n const p0 = path[0];\n const p1 = path[1];\n if (!p0 || !p1 || !p0.hardened || !p1.hardened) return 'unknown';\n if (p0.index === 44 && p1.index === 60) return 'evm';\n if (\n p1.index === 0 &&\n (p0.index === 84 || p0.index === 49 || p0.index === 44 || p0.index === 86)\n ) {\n return 'btc';\n }\n if (p0.index === 44 && p1.index === 501) return 'solana';\n if (p0.index === 44 && p1.index === 195) return 'tron';\n if (p0.index === 44 && p1.index === 607) return 'ton';\n return 'unknown';\n}\n\nfunction withChainCode(entry: RawAccountEntry): Uint8Array {\n if (!entry.chainCode) {\n throw new EraSdkError(\n 'account-not-found',\n `account ${formatPath([...entry.path])} carries no chain code; cannot derive children`,\n );\n }\n return entry.chainCode;\n}\n\n/** The entry's key at the required length, or a typed refusal (derivation only). */\nfunction requireKey(entry: RawAccountEntry, length: number): Uint8Array {\n if (!entry.publicKey || entry.publicKey.length !== length) {\n throw new EraSdkError(\n 'invalid-props',\n `account ${formatPath([...entry.path])} carries no ${length}-byte public key; ` +\n 'xfp lookup still works, address derivation does not',\n );\n }\n return entry.publicKey;\n}\n\n/** EVM view over the linked wallet: one account xpub, addresses derived at `0/index`. */\nexport class EvmAccountView {\n constructor(private readonly entry: RawAccountEntry) {}\n\n get xfp(): string {\n return xfpToHex(this.entry.xfp);\n }\n\n get accountPath(): string {\n return formatPath([...this.entry.path]);\n }\n\n /** Signing path for address `index`: `<account>/0/<index>`. */\n pathFor(index: number): string {\n return `${this.accountPath}/0/${index}`;\n }\n\n deriveAddress(index: number): `0x${string}` {\n return evmAddressFromPublicKey(\n derivePublicKey(requireKey(this.entry, 33), withChainCode(this.entry), 0, index),\n );\n }\n\n xpub(): string {\n return extendedKeyOf(this.entry);\n }\n}\n\nexport type BtcPurpose = 44 | 49 | 84 | 86;\n\n/**\n * Bitcoin view over one exported account. The default is the BIP-84\n * native-segwit account; pass `purpose` to reach the other script types the\n * device exports (44 = legacy P2PKH — the kind the device signs MESSAGES for,\n * 49 = nested segwit, 86 = taproot).\n */\nexport class BtcAccountView {\n constructor(\n private readonly entry: RawAccountEntry,\n private readonly testnet: boolean,\n readonly purpose: BtcPurpose,\n ) {}\n\n get xfp(): string {\n return xfpToHex(this.entry.xfp);\n }\n\n get accountPath(): string {\n return formatPath([...this.entry.path]);\n }\n\n receivePath(index: number): string {\n return `${this.accountPath}/0/${index}`;\n }\n\n changePath(index: number): string {\n return `${this.accountPath}/1/${index}`;\n }\n\n deriveAddress(index: number, options?: { change?: boolean }): string {\n const change = options?.change ? 1 : 0;\n const child = derivePublicKey(\n requireKey(this.entry, 33),\n withChainCode(this.entry),\n change,\n index,\n );\n switch (this.purpose) {\n case 84:\n return btcP2wpkhAddressFromPublicKey(child, this.testnet ? 'tb' : 'bc');\n case 44:\n return btcP2pkhAddressFromPublicKey(child, this.testnet);\n case 49:\n return btcNestedSegwitAddressFromPublicKey(child, this.testnet);\n case 86:\n throw new EraSdkError(\n 'invalid-props',\n 'taproot addresses need the BIP-341 output-key tweak; derive them from xpub() with your Bitcoin library',\n );\n }\n }\n\n xpub(): string {\n return extendedKeyOf(this.entry);\n }\n\n /** SLIP-132 zpub form of the BIP-84 key, for tools that require it. */\n zpub(): string {\n if (this.purpose !== 84) {\n throw new EraSdkError(\n 'invalid-props',\n 'zpub is the SLIP-132 form of the BIP-84 account only',\n );\n }\n return extendedKeyOf(this.entry, ZPUB_VERSION);\n }\n}\n\n/** Tron view: addresses derived at `0/index`. */\nexport class TronAccountView {\n constructor(private readonly entry: RawAccountEntry) {}\n\n get xfp(): string {\n return xfpToHex(this.entry.xfp);\n }\n\n get accountPath(): string {\n return formatPath([...this.entry.path]);\n }\n\n pathFor(index: number): string {\n return `${this.accountPath}/0/${index}`;\n }\n\n deriveAddress(index: number): string {\n return tronAddressFromPublicKey(\n derivePublicKey(requireKey(this.entry, 33), withChainCode(this.entry), 0, index),\n );\n }\n}\n\n/**\n * TON view: one Ed25519 key per account (`m/44'/607'/0'`), shared by the\n * V4R2 and V5R1 wallet contracts — the contract version affects only the\n * ADDRESS, which this SDK leaves to TON tooling (derive it from `publicKey`\n * with @ton/core or equivalent).\n */\nexport class TonAccountView {\n constructor(private readonly entry: RawAccountEntry) {}\n\n get xfp(): string {\n return xfpToHex(this.entry.xfp);\n }\n\n get accountPath(): string {\n return formatPath([...this.entry.path]);\n }\n\n /** 32-byte Ed25519 public key — the signer for both wallet-contract versions. */\n get publicKey(): Uint8Array {\n return requireKey(this.entry, 32);\n }\n\n get name(): string | undefined {\n return this.entry.name ?? this.entry.note ?? undefined;\n }\n}\n\n/**\n * Solana view: Ed25519 has no public child derivation, so the device\n * pre-derives hardened accounts (`m/44'/501'/idx'`) and each entry IS a\n * signer. The public key, base58, IS the address.\n */\nexport class SolanaAccountView {\n constructor(private readonly entry: RawAccountEntry) {}\n\n get xfp(): string {\n return xfpToHex(this.entry.xfp);\n }\n\n get path(): string {\n return formatPath([...this.entry.path]);\n }\n\n /** The hardened account index (third path level). */\n get index(): number {\n return this.entry.path[2]?.index ?? 0;\n }\n\n get publicKey(): Uint8Array {\n return requireKey(this.entry, 32);\n }\n\n get address(): string {\n return solanaAddressFromPublicKey(requireKey(this.entry, 32));\n }\n}\n\nfunction extendedKeyOf(entry: RawAccountEntry, version?: number): string {\n const chainCode = withChainCode(entry);\n const publicKey = requireKey(entry, 33);\n const last = entry.path[entry.path.length - 1]!;\n const args = {\n depth: entry.path.length,\n parentFingerprint: entry.parentFingerprint ?? 0,\n childNumber: last.hardened ? last.index + 0x80000000 : last.index,\n chainCode,\n publicKey,\n };\n return version === undefined\n ? serializeExtendedPublicKey(args)\n : serializeExtendedPublicKey({ ...args, version });\n}\n\n/**\n * The linked wallet: everything a software wallet extracts from the device's\n * `crypto-multi-accounts` QR. Parse once, store the source UR string, derive\n * addresses locally — the device is not needed again until signing.\n */\nexport class EraAccounts {\n private constructor(\n private readonly raw: RawMultiAccounts,\n readonly sourceUr: string | undefined,\n ) {}\n\n static fromUr(input: Ur | string): EraAccounts {\n const raw = parseMultiAccountsUr(input);\n return new EraAccounts(raw, typeof input === 'string' ? input : input.toString());\n }\n\n /** Master fingerprint, lowercase 8-hex. */\n get masterFingerprint(): string {\n return xfpToHex(this.raw.masterFingerprint);\n }\n\n get device(): DeviceInfo {\n return {\n name: this.raw.deviceName ?? undefined,\n id: this.raw.deviceId ?? undefined,\n firmwareVersion: this.raw.deviceVersion ?? undefined,\n };\n }\n\n get keys(): AccountKey[] {\n return this.raw.entries.map((entry) => ({\n chain: classify(entry.path),\n path: formatPath([...entry.path]),\n xfp: xfpToHex(entry.xfp),\n publicKey: entry.publicKey ?? undefined,\n chainCode: entry.chainCode ?? undefined,\n name: entry.name ?? undefined,\n note: entry.note ?? undefined,\n }));\n }\n\n /**\n * The xfp a sign request must carry for the account whose path exactly\n * equals `accountPath`. Throws `account-not-found` — never a silent zero.\n */\n xfpFor(accountPath: string): string {\n return xfpToHex(this.entryFor(accountPath).xfp);\n }\n\n /** The EVM account (standard `m/44'/60'/...` scheme), if the export carries one. */\n evm(): EvmAccountView | undefined {\n const entry =\n this.raw.entries.find(\n (e) => classify(e.path) === 'evm' && (e.note === null || e.note === 'account.standard'),\n ) ?? this.raw.entries.find((e) => classify(e.path) === 'evm');\n return entry ? new EvmAccountView(entry) : undefined;\n }\n\n /**\n * A Bitcoin account view. Defaults to the BIP-84 native-segwit account;\n * pass `purpose: 44` for the legacy P2PKH account (message signing), 49 for\n * nested segwit, 86 for taproot — if the export carries them.\n */\n btc(options?: { testnet?: boolean; purpose?: BtcPurpose }): BtcAccountView | undefined {\n const purpose = options?.purpose ?? 84;\n const entry = this.raw.entries.find(\n (e) => classify(e.path) === 'btc' && e.path[0]?.index === purpose,\n );\n return entry ? new BtcAccountView(entry, options?.testnet ?? false, purpose) : undefined;\n }\n\n tron(): TronAccountView | undefined {\n const entry = this.raw.entries.find((e) => classify(e.path) === 'tron');\n return entry ? new TronAccountView(entry) : undefined;\n }\n\n /** The TON account (linked via the Tonkeeper-style `crypto-hdkey` export). */\n ton(): TonAccountView | undefined {\n const entry = this.raw.entries.find(\n (e) => classify(e.path) === 'ton' && e.publicKey?.length === 32,\n );\n return entry ? new TonAccountView(entry) : undefined;\n }\n\n /** All pre-derived Solana signers (usually `m/44'/501'/0'..9'`). */\n solana(): SolanaAccountView[] {\n return this.raw.entries\n .filter((e) => classify(e.path) === 'solana' && e.publicKey?.length === 32)\n .map((e) => new SolanaAccountView(e));\n }\n\n private entryFor(accountPath: string): RawAccountEntry {\n const levels = parsePath(accountPath);\n const entry = this.raw.entries.find((e) => pathEquals(e.path, levels));\n if (!entry) {\n throw new EraSdkError(\n 'account-not-found',\n `the linked wallet carries no account at ${accountPath}`,\n { path: accountPath },\n );\n }\n return entry;\n }\n}\n","import type { EraAccounts } from '../accounts/accounts';\nimport { EraAccounts as EraAccountsClass } from '../accounts/accounts';\nimport { cborEncode } from '../cbor/encode';\nimport type { CborValue } from '../cbor/model';\nimport { cbArray, cbMap, cbTag, cbText, cbUint } from '../cbor/model';\nimport type { ChainContext } from '../chains/shared';\nimport { EraSdkError } from '../core/errors';\nimport type { AnimatedUrOptions } from '../qr/animated-ur';\nimport { AnimatedUr } from '../qr/animated-ur';\nimport { keypath304, parsePath } from '../registry/keypath';\nimport { WALLET_UR_TYPES } from '../registry/multi-accounts';\nimport { TypedUrScanner } from '../scan/ur-scanner';\nimport type { Ur } from '../ur/ur';\nimport { Ur as UrValue } from '../ur/ur';\n\nexport type DerivationCurve = 'secp256k1' | 'ed25519';\nexport type DerivationAlgorithm = 'slip10' | 'bip32ed25519';\n\nexport interface KeyDerivationSchema {\n /** The derivation path to request, e.g. `m/44'/60'/0'`. */\n readonly path: string;\n /** Defaults to `secp256k1`. */\n readonly curve?: DerivationCurve;\n /** Defaults to `slip10`. */\n readonly algo?: DerivationAlgorithm;\n /** Optional chain hint shown by the device. */\n readonly chainType?: string;\n}\n\nexport interface KeyDerivationCallProps {\n readonly schemas: readonly KeyDerivationSchema[];\n readonly origin?: string;\n}\n\n/** The pull-model linking request: display it, then scan the device's account export back. */\nexport interface HardwareCallRequest {\n readonly ur: Ur;\n readonly replyTypes: readonly string[];\n toAnimated(options?: AnimatedUrOptions): AnimatedUr;\n scanner(): TypedUrScanner<EraAccounts>;\n}\n\nconst CURVES: Record<DerivationCurve, number> = { secp256k1: 0, ed25519: 1 };\nconst ALGOS: Record<DerivationAlgorithm, number> = { slip10: 0, bip32ed25519: 1 };\n\n/**\n * Build a `qr-hardware-call` (1201) wrapping a `key-derivation-call` (1301):\n * the WALLET asks the device for specific derivation paths, curves and\n * algorithms instead of accepting whatever the device's sync screen\n * volunteers. The device answers with a `crypto-multi-accounts` export, which\n * closes the loop through `parseAccounts`.\n *\n * Registry shape (Keystone-standard):\n * `1201({1: type=0, 2: 1301({1: [1302({1: 304(keypath), 2: curve, 3: algo, 4?: chainType})...]}), 3?: origin})`.\n */\nexport function generateKeyDerivationCall(\n context: ChainContext,\n props: KeyDerivationCallProps,\n): HardwareCallRequest {\n if (props.schemas.length === 0) {\n throw new EraSdkError('invalid-props', 'at least one derivation schema is required');\n }\n const schemas: CborValue[] = props.schemas.map((schema) => {\n const levels = parsePath(schema.path);\n const entries: [number, CborValue][] = [\n [1, keypath304(levels)],\n [2, cbUint(CURVES[schema.curve ?? 'secp256k1'])],\n [3, cbUint(ALGOS[schema.algo ?? 'slip10'])],\n ];\n if (schema.chainType !== undefined) entries.push([4, cbText(schema.chainType)]);\n return cbTag(1302, cbMap(entries));\n });\n\n const call = cbTag(1301, cbMap([[1, cbArray(schemas)]]));\n const root = cbMap([\n [1, cbUint(0)], // type: KeyDerivation\n [2, call],\n [3, cbText(props.origin ?? context.origin)],\n ]);\n\n const ur = new UrValue('qr-hardware-call', cborEncode(root));\n const replyTypes = [...WALLET_UR_TYPES];\n return {\n ur,\n replyTypes,\n toAnimated: (options?: AnimatedUrOptions) =>\n new AnimatedUr(ur, {\n maxFragmentLength: options?.maxFragmentLength ?? context.maxFragmentLength,\n }),\n scanner: () =>\n new TypedUrScanner<EraAccounts>({ expectedTypes: replyTypes }, (reply) =>\n EraAccountsClass.fromUr(reply),\n ),\n };\n}\n","import type { ChainContext } from './chains/shared';\nimport { toUr } from './chains/shared';\nimport type { AnimatedUrOptions } from './qr/animated-ur';\nimport { AnimatedUr } from './qr/animated-ur';\nimport type { Ur } from './ur/ur';\nimport { Ur as UrValue } from './ur/ur';\n\n/**\n * Escape hatch for UR types this SDK has no dedicated module for (future\n * chains, custom registry items). You bring the CBOR; the SDK brings the UR\n * plumbing, fountain frames and the hardened scanner\n * (`EraConnect.scanner({expectedTypes})`).\n */\nexport class RawModule {\n constructor(private readonly context: ChainContext) {}\n\n /** Wrap raw CBOR bytes in a UR of the given registry type. */\n ur(type: string, cbor: Uint8Array): Ur {\n return new UrValue(type, cbor);\n }\n\n /** Parse a single-part `ur:` string into a Ur. */\n parse(text: string): Ur {\n return toUr(text);\n }\n\n /** Fragment + animate any UR. */\n animate(ur: Ur, options?: AnimatedUrOptions): AnimatedUr {\n return new AnimatedUr(ur, {\n maxFragmentLength: options?.maxFragmentLength ?? this.context.maxFragmentLength,\n });\n }\n}\n","/**\n * ERA Connect SDK — air-gapped UR/QR linking and signing for the ERA\n * hardware wallet.\n *\n * Headless by design: you render the QR codes and own the camera; the SDK\n * owns every byte of the protocol. No network I/O, no Node built-ins,\n * `Uint8Array` end-to-end.\n */\n\nimport type { EraAccounts as EraAccountsType } from './accounts/accounts';\nimport { EraAccounts } from './accounts/accounts';\nimport { BtcChain } from './chains/btc';\nimport { EvmChain } from './chains/evm';\nimport type { ChainContext, EraConnectConfig } from './chains/shared';\nimport { resolveContext } from './chains/shared';\nimport { SolanaChain } from './chains/solana';\nimport { TonChain } from './chains/ton';\nimport { TronChain } from './chains/tron';\nimport type { HardwareCallRequest, KeyDerivationCallProps } from './hardware-call/key-derivation';\nimport { generateKeyDerivationCall } from './hardware-call/key-derivation';\nimport { RawModule } from './raw';\nimport type { UrScannerOptions } from './scan/ur-scanner';\nimport { UrScanner } from './scan/ur-scanner';\nimport type { Ur } from './ur/ur';\n\n/** Timing/size constants of the device's own QR pipeline, for progress UI and timeouts. */\nexport const DeviceProfile = {\n /** What the phone displays to the device: ~200 wire bytes per frame at 8 fps. */\n phoneToDevice: { fragmentBytesOnWire: 200, payloadBytes: 180, frameIntervalMs: 125 },\n /**\n * What the device displays back: 150-byte fragments at 2.5 fps. Receiving\n * is SLOWER than sending — budget scan timeouts accordingly.\n */\n deviceToPhone: { fragmentBytesOnWire: 150, frameIntervalMs: 400 },\n} as const;\n\n/** The SDK facade. Cheap to construct; chain modules are created lazily. */\nexport class EraConnect {\n private readonly context: ChainContext;\n private _evm: EvmChain | undefined;\n private _btc: BtcChain | undefined;\n private _solana: SolanaChain | undefined;\n private _tron: TronChain | undefined;\n private _ton: TonChain | undefined;\n private _raw: RawModule | undefined;\n\n constructor(config?: EraConnectConfig) {\n this.context = resolveContext(config);\n }\n\n get evm(): EvmChain {\n this._evm ??= new EvmChain(this.context);\n return this._evm;\n }\n\n get btc(): BtcChain {\n this._btc ??= new BtcChain(this.context);\n return this._btc;\n }\n\n get solana(): SolanaChain {\n this._solana ??= new SolanaChain(this.context);\n return this._solana;\n }\n\n get tron(): TronChain {\n this._tron ??= new TronChain(this.context);\n return this._tron;\n }\n\n get ton(): TonChain {\n this._ton ??= new TonChain(this.context);\n return this._ton;\n }\n\n /** Escape hatch for UR types without a dedicated module. */\n get raw(): RawModule {\n this._raw ??= new RawModule(this.context);\n return this._raw;\n }\n\n /**\n * Linking: parse the device's `crypto-multi-accounts` export (a `Ur` from a\n * scanner, or a single-part `ur:` string).\n */\n parseAccounts(input: Ur | string): EraAccountsType {\n return EraAccounts.fromUr(input);\n }\n\n /**\n * Pull-model linking: ask the device for SPECIFIC derivations\n * (`qr-hardware-call` 1201). The device answers with a\n * `crypto-multi-accounts` export.\n */\n generateKeyDerivationCall(props: KeyDerivationCallProps): HardwareCallRequest {\n return generateKeyDerivationCall(this.context, props);\n }\n\n /** A type-agnostic hardened scanner (linking flows, raw flows). */\n scanner(options?: UrScannerOptions): UrScanner {\n return new UrScanner(options);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public types & modules\n// ---------------------------------------------------------------------------\n\nexport type { AccountChain, AccountKey, BtcPurpose, DeviceInfo } from './accounts/accounts';\nexport {\n BtcAccountView,\n EraAccounts,\n EvmAccountView,\n SolanaAccountView,\n TonAccountView,\n TronAccountView,\n} from './accounts/accounts';\nexport type {\n BtcMessageSignatureResult,\n BtcMessageSignRequestProps,\n BtcPsbtResult,\n BtcPsbtSignRequestProps,\n} from './chains/btc';\nexport { BtcChain } from './chains/btc';\nexport type { EvmSignatureResult, EvmSignRequestProps } from './chains/evm';\nexport { EvmChain, EvmDataType } from './chains/evm';\nexport type {\n ChainContext,\n EraConnectConfig,\n ExpectedReply,\n SignRequest,\n} from './chains/shared';\nexport { DEFAULT_ORIGIN } from './chains/shared';\nexport type { SolSignatureResult, SolSignRequestProps } from './chains/solana';\nexport { SolanaChain, SolSignType } from './chains/solana';\nexport type { TonSignatureResult, TonSignRequestProps } from './chains/ton';\nexport { TonChain, TonDataType } from './chains/ton';\nexport type { TronLatestBlock, TronSignatureResult, TronSignRequestProps } from './chains/tron';\nexport { TronChain } from './chains/tron';\n// UTF-8 helpers that work on every Hermes version (TextEncoder does not):\nexport { utf8Decode, utf8Encode } from './core/bytes';\nexport type { EraErrorCode } from './core/errors';\nexport { EraSdkError } from './core/errors';\nexport type { RandomBytesFn } from './core/rand';\nexport type {\n DerivationAlgorithm,\n DerivationCurve,\n HardwareCallRequest,\n KeyDerivationCallProps,\n KeyDerivationSchema,\n} from './hardware-call/key-derivation';\nexport type { AnimatedUrOptions } from './qr/animated-ur';\nexport { AnimatedUr, DEFAULT_FRAGMENT_LENGTH } from './qr/animated-ur';\nexport { RawModule } from './raw';\nexport type { ScanFeedResult, ScanRejection, UrScannerOptions } from './scan/ur-scanner';\nexport { TypedUrScanner, UrScanner } from './scan/ur-scanner';\nexport { UrLimits } from './ur/limits';\nexport { Ur } from './ur/ur';\n"],"mappings":";;;;;;;;;;;;;;AAwCA,MAAa,kCAAuC,IAAI,IAAI;CAC1D;CACA;CACA;AACF,CAAC;;;;;;;;;AAUD,SAAgB,qBAAqB,OAAsC;CACzE,IAAI;CACJ,IAAI;CACJ,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,SAAS,cAAc,KAAK;EAClC,IAAI,OAAO,QAAQ,MACjB,MAAM,IAAI,YACR,iBACA,0DACF;EAEF,OAAO,OAAO;EACd,OAAO,OAAO;CAChB,OAAO;EACL,OAAO,MAAM;EACb,OAAO,MAAM;CACf;CAEA,IAAI,CAAC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AA0B,OAAoD;EAC5E,OAAO,0BAA0B,KAAK,SAAS,KAAK;CACtD;;CAGA,QAAQ,SAAuC;EAC7C,OAAO,IAAI,UAAU,OAAO;CAC9B;AACF"}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { A as utf8Encode, E as equalBytes, G as cbMap, J as cbUint, K as cbTag, M as keypath304, N as normalizeXfp, P as parsePath, W as cbBytes, X as stripTags, Y as mapGet, Z as EraSdkError, _ as Ur, c as resolveRequestId, g as uuidStringify, h as normalizeRequestId, l as toUr, n as makeSignRequest, o as requireUrType, q as cbText, r as requireReplyMap, s as resolveContext, x as cborEncode } from "./shared-B8Wc7ViU.js";
|
|
2
|
+
//#region src/chains/ton.ts
|
|
3
|
+
/** `ton-sign-request` dataType (CBOR key 3). */
|
|
4
|
+
const TonDataType = {
|
|
5
|
+
/** `signData` is a Bag-of-Cells; the device signs the ROOT CELL's representation hash. */
|
|
6
|
+
transaction: 1,
|
|
7
|
+
/**
|
|
8
|
+
* TON Connect proof: the device signs
|
|
9
|
+
* `sha256(0xFFFF || "ton-connect" || sha256(signData))`.
|
|
10
|
+
*/
|
|
11
|
+
tonProof: 2
|
|
12
|
+
};
|
|
13
|
+
const REPLY_TYPES = ["ton-signature"];
|
|
14
|
+
var TonChain = class {
|
|
15
|
+
constructor(config) {
|
|
16
|
+
this.context = resolveContext(config);
|
|
17
|
+
}
|
|
18
|
+
/** Build a `ton-sign-request` (7201). Reply: `ton-signature` (7202). */
|
|
19
|
+
generateSignRequest(props) {
|
|
20
|
+
const requestId = resolveRequestId(this.context, props.requestId);
|
|
21
|
+
const path = parsePath(props.path);
|
|
22
|
+
const xfp = normalizeXfp(props.xfp);
|
|
23
|
+
if (props.signData.length === 0) throw new EraSdkError("invalid-props", "signData must not be empty");
|
|
24
|
+
const entries = [
|
|
25
|
+
[1, cbTag(37, cbBytes(utf8Encode(uuidStringify(requestId))))],
|
|
26
|
+
[2, cbBytes(props.signData)],
|
|
27
|
+
[3, cbUint(props.dataType ?? TonDataType.transaction)],
|
|
28
|
+
[4, keypath304(path, xfp)]
|
|
29
|
+
];
|
|
30
|
+
if (props.address !== void 0) entries.push([5, cbText(props.address)]);
|
|
31
|
+
entries.push([6, cbText(props.origin ?? this.context.origin)]);
|
|
32
|
+
const ur = new Ur("ton-sign-request", cborEncode(cbMap(entries)));
|
|
33
|
+
return makeSignRequest({
|
|
34
|
+
ur,
|
|
35
|
+
requestId,
|
|
36
|
+
replyTypes: REPLY_TYPES,
|
|
37
|
+
context: this.context,
|
|
38
|
+
parse: (reply) => parseTonSignature(reply, requestId)
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
/** Parse a `ton-signature` standalone. Prefer `SignRequest.scanner().parse()`. */
|
|
42
|
+
parseSignature(input, expect) {
|
|
43
|
+
return parseTonSignature(toUr(input), expect?.requestId === void 0 ? void 0 : normalizeRequestId(expect.requestId));
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
TonChain.DataType = TonDataType;
|
|
47
|
+
function parseTonSignature(ur, expectedRequestId) {
|
|
48
|
+
requireUrType(ur, [...REPLY_TYPES], "ton-signature");
|
|
49
|
+
const map = requireReplyMap(ur, "ton-signature");
|
|
50
|
+
const echoedValue = mapGet(map, 1);
|
|
51
|
+
const echoed = echoedValue === void 0 ? void 0 : stripTags(echoedValue);
|
|
52
|
+
if (echoed?.kind !== "bytes") throw new EraSdkError("malformed-reply", "ton-signature does not echo the request id (key 1)");
|
|
53
|
+
const requestId = normalizeEchoedId(echoed.value);
|
|
54
|
+
if (expectedRequestId !== void 0) {
|
|
55
|
+
if (requestId === null || !equalBytes(requestId, expectedRequestId)) throw new EraSdkError("request-id-mismatch", "ton-signature echoes a different request id — it answers another sign request, not this one");
|
|
56
|
+
}
|
|
57
|
+
const sigValue = mapGet(map, 2);
|
|
58
|
+
const sig = sigValue === void 0 ? void 0 : stripTags(sigValue);
|
|
59
|
+
if (sig?.kind !== "bytes") throw new EraSdkError("malformed-reply", "ton-signature is missing the signature (key 2)");
|
|
60
|
+
if (sig.value.length !== 64) throw new EraSdkError("malformed-reply", `ton-signature signature is ${sig.value.length} bytes, expected 64`);
|
|
61
|
+
return {
|
|
62
|
+
requestId: requestId ?? /* @__PURE__ */ new Uint8Array(16),
|
|
63
|
+
signature: sig.value
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/** ASCII-UUID-string bytes (36) or raw binary (16) → 16-byte id; null if neither. */
|
|
67
|
+
function normalizeEchoedId(echoed) {
|
|
68
|
+
if (echoed.length === 16) return echoed;
|
|
69
|
+
if (echoed.length === 36) {
|
|
70
|
+
let text = "";
|
|
71
|
+
for (const b of echoed) {
|
|
72
|
+
if (b > 127) return null;
|
|
73
|
+
text += String.fromCharCode(b);
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
return normalizeRequestId(text);
|
|
77
|
+
} catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
export { TonDataType as n, TonChain as t };
|
|
85
|
+
|
|
86
|
+
//# sourceMappingURL=ton-5Uvi5ifg.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ton-5Uvi5ifg.js","names":["UrValue"],"sources":["../src/chains/ton.ts"],"sourcesContent":["import { cborEncode } from '../cbor/encode';\nimport type { CborValue } from '../cbor/model';\nimport { cbBytes, cbMap, cbTag, cbText, cbUint, mapGet, stripTags } from '../cbor/model';\nimport { equalBytes, utf8Encode } from '../core/bytes';\nimport { EraSdkError } from '../core/errors';\nimport { normalizeRequestId, uuidStringify } from '../core/rand';\nimport { keypath304, normalizeXfp, parsePath } from '../registry/keypath';\nimport type { Ur } from '../ur/ur';\nimport { Ur as UrValue } from '../ur/ur';\nimport type { ChainContext, EraConnectConfig, ExpectedReply, SignRequest } from './shared';\nimport {\n makeSignRequest,\n requireReplyMap,\n requireUrType,\n resolveContext,\n resolveRequestId,\n toUr,\n} from './shared';\n\n/** `ton-sign-request` dataType (CBOR key 3). */\nexport const TonDataType = {\n /** `signData` is a Bag-of-Cells; the device signs the ROOT CELL's representation hash. */\n transaction: 1,\n /**\n * TON Connect proof: the device signs\n * `sha256(0xFFFF || \"ton-connect\" || sha256(signData))`.\n */\n tonProof: 2,\n} as const;\nexport type TonDataType = (typeof TonDataType)[keyof typeof TonDataType];\n\nexport interface TonSignRequestProps {\n readonly requestId?: Uint8Array | string;\n /** BoC bytes (transaction) or the raw proof payload (tonProof). */\n readonly signData: Uint8Array;\n /** Defaults to `transaction`. */\n readonly dataType?: TonDataType;\n /** The account path, e.g. `m/44'/607'/0'` (V4R2 and V5R1 share it — the wallet-contract version affects only the address). */\n readonly path: string;\n readonly xfp: string | number;\n /** User-friendly bounceable address TEXT (`UQ…`/`EQ…`) — shown on the device. */\n readonly address?: string;\n readonly origin?: string;\n}\n\nexport interface TonSignatureResult {\n readonly requestId: Uint8Array;\n /** 64-byte Ed25519 signature over the digest for the request's dataType. */\n readonly signature: Uint8Array;\n}\n\nconst REPLY_TYPES = ['ton-signature'] as const;\n\nexport class TonChain {\n static readonly DataType = TonDataType;\n\n private readonly context: ChainContext;\n\n constructor(config?: EraConnectConfig) {\n this.context = resolveContext(config);\n }\n\n /** Build a `ton-sign-request` (7201). Reply: `ton-signature` (7202). */\n generateSignRequest(props: TonSignRequestProps): SignRequest<TonSignatureResult> {\n const requestId = resolveRequestId(this.context, props.requestId);\n const path = parsePath(props.path);\n const xfp = normalizeXfp(props.xfp);\n if (props.signData.length === 0) {\n throw new EraSdkError('invalid-props', 'signData must not be empty');\n }\n\n const entries: [number, CborValue][] = [\n // TON ecosystem quirk: the request id travels as the ASCII BYTES of the\n // hyphenated UUID string, wrapped in tag 37 (that is what Tonkeeper-\n // style integrations emit and what the device echoes back verbatim).\n [1, cbTag(37, cbBytes(utf8Encode(uuidStringify(requestId))))],\n [2, cbBytes(props.signData)],\n [3, cbUint(props.dataType ?? TonDataType.transaction)],\n [4, keypath304(path, xfp)],\n ];\n if (props.address !== undefined) entries.push([5, cbText(props.address)]);\n entries.push([6, cbText(props.origin ?? this.context.origin)]);\n\n const ur = new UrValue('ton-sign-request', cborEncode(cbMap(entries)));\n return makeSignRequest({\n ur,\n requestId,\n replyTypes: REPLY_TYPES,\n context: this.context,\n parse: (reply) => parseTonSignature(reply, requestId),\n });\n }\n\n /** Parse a `ton-signature` standalone. Prefer `SignRequest.scanner().parse()`. */\n parseSignature(input: Ur | string, expect?: ExpectedReply): TonSignatureResult {\n return parseTonSignature(\n toUr(input),\n expect?.requestId === undefined ? undefined : normalizeRequestId(expect.requestId),\n );\n }\n}\n\nfunction parseTonSignature(ur: Ur, expectedRequestId: Uint8Array | undefined): TonSignatureResult {\n requireUrType(ur, [...REPLY_TYPES], 'ton-signature');\n const map = requireReplyMap(ur, 'ton-signature');\n\n // The device echoes the request id BYTES verbatim (tag-37 wrapped). On this\n // chain those bytes are normally the ASCII of the UUID string; a bare\n // 16-byte binary echo is accepted too for forward compatibility.\n const echoedValue = mapGet(map, 1);\n const echoed = echoedValue === undefined ? undefined : stripTags(echoedValue);\n if (echoed?.kind !== 'bytes') {\n throw new EraSdkError('malformed-reply', 'ton-signature does not echo the request id (key 1)');\n }\n const requestId = normalizeEchoedId(echoed.value);\n if (expectedRequestId !== undefined) {\n if (requestId === null || !equalBytes(requestId, expectedRequestId)) {\n throw new EraSdkError(\n 'request-id-mismatch',\n 'ton-signature echoes a different request id — it answers another sign request, not this one',\n );\n }\n }\n\n const sigValue = mapGet(map, 2);\n const sig = sigValue === undefined ? undefined : stripTags(sigValue);\n if (sig?.kind !== 'bytes') {\n throw new EraSdkError('malformed-reply', 'ton-signature is missing the signature (key 2)');\n }\n if (sig.value.length !== 64) {\n throw new EraSdkError(\n 'malformed-reply',\n `ton-signature signature is ${sig.value.length} bytes, expected 64`,\n );\n }\n return { requestId: requestId ?? new Uint8Array(16), signature: sig.value };\n}\n\n/** ASCII-UUID-string bytes (36) or raw binary (16) → 16-byte id; null if neither. */\nfunction normalizeEchoedId(echoed: Uint8Array): Uint8Array | null {\n if (echoed.length === 16) return echoed;\n if (echoed.length === 36) {\n let text = '';\n for (const b of echoed) {\n if (b > 0x7f) return null;\n text += String.fromCharCode(b);\n }\n try {\n return normalizeRequestId(text);\n } catch {\n return null;\n }\n }\n return null;\n}\n"],"mappings":";;;AAoBA,MAAa,cAAc;;CAEzB,aAAa;;;;;CAKb,UAAU;AACZ;AAuBA,MAAM,cAAc,CAAC,eAAe;AAEpC,IAAa,WAAb,MAAsB;CAKpB,YAAY,QAA2B;EACrC,KAAK,UAAU,eAAe,MAAM;CACtC;;CAGA,oBAAoB,OAA6D;EAC/E,MAAM,YAAY,iBAAiB,KAAK,SAAS,MAAM,SAAS;EAChE,MAAM,OAAO,UAAU,MAAM,IAAI;EACjC,MAAM,MAAM,aAAa,MAAM,GAAG;EAClC,IAAI,MAAM,SAAS,WAAW,GAC5B,MAAM,IAAI,YAAY,iBAAiB,4BAA4B;EAGrE,MAAM,UAAiC;GAIrC,CAAC,GAAG,MAAM,IAAI,QAAQ,WAAW,cAAc,SAAS,CAAC,CAAC,CAAC,CAAC;GAC5D,CAAC,GAAG,QAAQ,MAAM,QAAQ,CAAC;GAC3B,CAAC,GAAG,OAAO,MAAM,YAAY,YAAY,WAAW,CAAC;GACrD,CAAC,GAAG,WAAW,MAAM,GAAG,CAAC;EAC3B;EACA,IAAI,MAAM,YAAY,KAAA,GAAW,QAAQ,KAAK,CAAC,GAAG,OAAO,MAAM,OAAO,CAAC,CAAC;EACxE,QAAQ,KAAK,CAAC,GAAG,OAAO,MAAM,UAAU,KAAK,QAAQ,MAAM,CAAC,CAAC;EAE7D,MAAM,KAAK,IAAIA,GAAQ,oBAAoB,WAAW,MAAM,OAAO,CAAC,CAAC;EACrE,OAAO,gBAAgB;GACrB;GACA;GACA,YAAY;GACZ,SAAS,KAAK;GACd,QAAQ,UAAU,kBAAkB,OAAO,SAAS;EACtD,CAAC;CAC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CACA,OAAO;AACT"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { _ as Ur, a as SignRequest, i as ExpectedReply, r as EraConnectConfig } from "./shared-CI8zhQiE.js";
|
|
2
|
+
//#region src/chains/ton.d.ts
|
|
3
|
+
/** `ton-sign-request` dataType (CBOR key 3). */
|
|
4
|
+
declare const TonDataType: {
|
|
5
|
+
/** `signData` is a Bag-of-Cells; the device signs the ROOT CELL's representation hash. */
|
|
6
|
+
readonly transaction: 1;
|
|
7
|
+
/**
|
|
8
|
+
* TON Connect proof: the device signs
|
|
9
|
+
* `sha256(0xFFFF || "ton-connect" || sha256(signData))`.
|
|
10
|
+
*/
|
|
11
|
+
readonly tonProof: 2;
|
|
12
|
+
};
|
|
13
|
+
type TonDataType = (typeof TonDataType)[keyof typeof TonDataType];
|
|
14
|
+
interface TonSignRequestProps {
|
|
15
|
+
readonly requestId?: Uint8Array | string;
|
|
16
|
+
/** BoC bytes (transaction) or the raw proof payload (tonProof). */
|
|
17
|
+
readonly signData: Uint8Array;
|
|
18
|
+
/** Defaults to `transaction`. */
|
|
19
|
+
readonly dataType?: TonDataType;
|
|
20
|
+
/** The account path, e.g. `m/44'/607'/0'` (V4R2 and V5R1 share it — the wallet-contract version affects only the address). */
|
|
21
|
+
readonly path: string;
|
|
22
|
+
readonly xfp: string | number;
|
|
23
|
+
/** User-friendly bounceable address TEXT (`UQ…`/`EQ…`) — shown on the device. */
|
|
24
|
+
readonly address?: string;
|
|
25
|
+
readonly origin?: string;
|
|
26
|
+
}
|
|
27
|
+
interface TonSignatureResult {
|
|
28
|
+
readonly requestId: Uint8Array;
|
|
29
|
+
/** 64-byte Ed25519 signature over the digest for the request's dataType. */
|
|
30
|
+
readonly signature: Uint8Array;
|
|
31
|
+
}
|
|
32
|
+
declare class TonChain {
|
|
33
|
+
static readonly DataType: {
|
|
34
|
+
/** `signData` is a Bag-of-Cells; the device signs the ROOT CELL's representation hash. */
|
|
35
|
+
readonly transaction: 1;
|
|
36
|
+
/**
|
|
37
|
+
* TON Connect proof: the device signs
|
|
38
|
+
* `sha256(0xFFFF || "ton-connect" || sha256(signData))`.
|
|
39
|
+
*/
|
|
40
|
+
readonly tonProof: 2;
|
|
41
|
+
};
|
|
42
|
+
private readonly context;
|
|
43
|
+
constructor(config?: EraConnectConfig);
|
|
44
|
+
/** Build a `ton-sign-request` (7201). Reply: `ton-signature` (7202). */
|
|
45
|
+
generateSignRequest(props: TonSignRequestProps): SignRequest<TonSignatureResult>;
|
|
46
|
+
/** Parse a `ton-signature` standalone. Prefer `SignRequest.scanner().parse()`. */
|
|
47
|
+
parseSignature(input: Ur | string, expect?: ExpectedReply): TonSignatureResult;
|
|
48
|
+
}
|
|
49
|
+
//#endregion
|
|
50
|
+
export { TonSignatureResult as i, TonDataType as n, TonSignRequestProps as r, TonChain as t };
|
|
51
|
+
//# sourceMappingURL=ton-C0UP-cf_.d.ts.map
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
const require_shared = require("./shared-nISrEktU.cjs");
|
|
2
|
+
//#region src/chains/ton.ts
|
|
3
|
+
/** `ton-sign-request` dataType (CBOR key 3). */
|
|
4
|
+
const TonDataType = {
|
|
5
|
+
/** `signData` is a Bag-of-Cells; the device signs the ROOT CELL's representation hash. */
|
|
6
|
+
transaction: 1,
|
|
7
|
+
/**
|
|
8
|
+
* TON Connect proof: the device signs
|
|
9
|
+
* `sha256(0xFFFF || "ton-connect" || sha256(signData))`.
|
|
10
|
+
*/
|
|
11
|
+
tonProof: 2
|
|
12
|
+
};
|
|
13
|
+
const REPLY_TYPES = ["ton-signature"];
|
|
14
|
+
var TonChain = class {
|
|
15
|
+
constructor(config) {
|
|
16
|
+
this.context = require_shared.resolveContext(config);
|
|
17
|
+
}
|
|
18
|
+
/** Build a `ton-sign-request` (7201). Reply: `ton-signature` (7202). */
|
|
19
|
+
generateSignRequest(props) {
|
|
20
|
+
const requestId = require_shared.resolveRequestId(this.context, props.requestId);
|
|
21
|
+
const path = require_shared.parsePath(props.path);
|
|
22
|
+
const xfp = require_shared.normalizeXfp(props.xfp);
|
|
23
|
+
if (props.signData.length === 0) throw new require_shared.EraSdkError("invalid-props", "signData must not be empty");
|
|
24
|
+
const entries = [
|
|
25
|
+
[1, require_shared.cbTag(37, require_shared.cbBytes(require_shared.utf8Encode(require_shared.uuidStringify(requestId))))],
|
|
26
|
+
[2, require_shared.cbBytes(props.signData)],
|
|
27
|
+
[3, require_shared.cbUint(props.dataType ?? TonDataType.transaction)],
|
|
28
|
+
[4, require_shared.keypath304(path, xfp)]
|
|
29
|
+
];
|
|
30
|
+
if (props.address !== void 0) entries.push([5, require_shared.cbText(props.address)]);
|
|
31
|
+
entries.push([6, require_shared.cbText(props.origin ?? this.context.origin)]);
|
|
32
|
+
const ur = new require_shared.Ur("ton-sign-request", require_shared.cborEncode(require_shared.cbMap(entries)));
|
|
33
|
+
return require_shared.makeSignRequest({
|
|
34
|
+
ur,
|
|
35
|
+
requestId,
|
|
36
|
+
replyTypes: REPLY_TYPES,
|
|
37
|
+
context: this.context,
|
|
38
|
+
parse: (reply) => parseTonSignature(reply, requestId)
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
/** Parse a `ton-signature` standalone. Prefer `SignRequest.scanner().parse()`. */
|
|
42
|
+
parseSignature(input, expect) {
|
|
43
|
+
return parseTonSignature(require_shared.toUr(input), expect?.requestId === void 0 ? void 0 : require_shared.normalizeRequestId(expect.requestId));
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
TonChain.DataType = TonDataType;
|
|
47
|
+
function parseTonSignature(ur, expectedRequestId) {
|
|
48
|
+
require_shared.requireUrType(ur, [...REPLY_TYPES], "ton-signature");
|
|
49
|
+
const map = require_shared.requireReplyMap(ur, "ton-signature");
|
|
50
|
+
const echoedValue = require_shared.mapGet(map, 1);
|
|
51
|
+
const echoed = echoedValue === void 0 ? void 0 : require_shared.stripTags(echoedValue);
|
|
52
|
+
if (echoed?.kind !== "bytes") throw new require_shared.EraSdkError("malformed-reply", "ton-signature does not echo the request id (key 1)");
|
|
53
|
+
const requestId = normalizeEchoedId(echoed.value);
|
|
54
|
+
if (expectedRequestId !== void 0) {
|
|
55
|
+
if (requestId === null || !require_shared.equalBytes(requestId, expectedRequestId)) throw new require_shared.EraSdkError("request-id-mismatch", "ton-signature echoes a different request id — it answers another sign request, not this one");
|
|
56
|
+
}
|
|
57
|
+
const sigValue = require_shared.mapGet(map, 2);
|
|
58
|
+
const sig = sigValue === void 0 ? void 0 : require_shared.stripTags(sigValue);
|
|
59
|
+
if (sig?.kind !== "bytes") throw new require_shared.EraSdkError("malformed-reply", "ton-signature is missing the signature (key 2)");
|
|
60
|
+
if (sig.value.length !== 64) throw new require_shared.EraSdkError("malformed-reply", `ton-signature signature is ${sig.value.length} bytes, expected 64`);
|
|
61
|
+
return {
|
|
62
|
+
requestId: requestId ?? /* @__PURE__ */ new Uint8Array(16),
|
|
63
|
+
signature: sig.value
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/** ASCII-UUID-string bytes (36) or raw binary (16) → 16-byte id; null if neither. */
|
|
67
|
+
function normalizeEchoedId(echoed) {
|
|
68
|
+
if (echoed.length === 16) return echoed;
|
|
69
|
+
if (echoed.length === 36) {
|
|
70
|
+
let text = "";
|
|
71
|
+
for (const b of echoed) {
|
|
72
|
+
if (b > 127) return null;
|
|
73
|
+
text += String.fromCharCode(b);
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
return require_shared.normalizeRequestId(text);
|
|
77
|
+
} catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
Object.defineProperty(exports, "TonChain", {
|
|
85
|
+
enumerable: true,
|
|
86
|
+
get: function() {
|
|
87
|
+
return TonChain;
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
Object.defineProperty(exports, "TonDataType", {
|
|
91
|
+
enumerable: true,
|
|
92
|
+
get: function() {
|
|
93
|
+
return TonDataType;
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
//# sourceMappingURL=ton-DUJGXdGa.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ton-DUJGXdGa.cjs","names":["resolveContext","resolveRequestId","parsePath","normalizeXfp","EraSdkError","cbTag","cbBytes","utf8Encode","uuidStringify","cbUint","keypath304","cbText","UrValue","cborEncode","cbMap","makeSignRequest","toUr","normalizeRequestId","requireReplyMap","mapGet","stripTags","equalBytes"],"sources":["../src/chains/ton.ts"],"sourcesContent":["import { cborEncode } from '../cbor/encode';\nimport type { CborValue } from '../cbor/model';\nimport { cbBytes, cbMap, cbTag, cbText, cbUint, mapGet, stripTags } from '../cbor/model';\nimport { equalBytes, utf8Encode } from '../core/bytes';\nimport { EraSdkError } from '../core/errors';\nimport { normalizeRequestId, uuidStringify } from '../core/rand';\nimport { keypath304, normalizeXfp, parsePath } from '../registry/keypath';\nimport type { Ur } from '../ur/ur';\nimport { Ur as UrValue } from '../ur/ur';\nimport type { ChainContext, EraConnectConfig, ExpectedReply, SignRequest } from './shared';\nimport {\n makeSignRequest,\n requireReplyMap,\n requireUrType,\n resolveContext,\n resolveRequestId,\n toUr,\n} from './shared';\n\n/** `ton-sign-request` dataType (CBOR key 3). */\nexport const TonDataType = {\n /** `signData` is a Bag-of-Cells; the device signs the ROOT CELL's representation hash. */\n transaction: 1,\n /**\n * TON Connect proof: the device signs\n * `sha256(0xFFFF || \"ton-connect\" || sha256(signData))`.\n */\n tonProof: 2,\n} as const;\nexport type TonDataType = (typeof TonDataType)[keyof typeof TonDataType];\n\nexport interface TonSignRequestProps {\n readonly requestId?: Uint8Array | string;\n /** BoC bytes (transaction) or the raw proof payload (tonProof). */\n readonly signData: Uint8Array;\n /** Defaults to `transaction`. */\n readonly dataType?: TonDataType;\n /** The account path, e.g. `m/44'/607'/0'` (V4R2 and V5R1 share it — the wallet-contract version affects only the address). */\n readonly path: string;\n readonly xfp: string | number;\n /** User-friendly bounceable address TEXT (`UQ…`/`EQ…`) — shown on the device. */\n readonly address?: string;\n readonly origin?: string;\n}\n\nexport interface TonSignatureResult {\n readonly requestId: Uint8Array;\n /** 64-byte Ed25519 signature over the digest for the request's dataType. */\n readonly signature: Uint8Array;\n}\n\nconst REPLY_TYPES = ['ton-signature'] as const;\n\nexport class TonChain {\n static readonly DataType = TonDataType;\n\n private readonly context: ChainContext;\n\n constructor(config?: EraConnectConfig) {\n this.context = resolveContext(config);\n }\n\n /** Build a `ton-sign-request` (7201). Reply: `ton-signature` (7202). */\n generateSignRequest(props: TonSignRequestProps): SignRequest<TonSignatureResult> {\n const requestId = resolveRequestId(this.context, props.requestId);\n const path = parsePath(props.path);\n const xfp = normalizeXfp(props.xfp);\n if (props.signData.length === 0) {\n throw new EraSdkError('invalid-props', 'signData must not be empty');\n }\n\n const entries: [number, CborValue][] = [\n // TON ecosystem quirk: the request id travels as the ASCII BYTES of the\n // hyphenated UUID string, wrapped in tag 37 (that is what Tonkeeper-\n // style integrations emit and what the device echoes back verbatim).\n [1, cbTag(37, cbBytes(utf8Encode(uuidStringify(requestId))))],\n [2, cbBytes(props.signData)],\n [3, cbUint(props.dataType ?? TonDataType.transaction)],\n [4, keypath304(path, xfp)],\n ];\n if (props.address !== undefined) entries.push([5, cbText(props.address)]);\n entries.push([6, cbText(props.origin ?? this.context.origin)]);\n\n const ur = new UrValue('ton-sign-request', cborEncode(cbMap(entries)));\n return makeSignRequest({\n ur,\n requestId,\n replyTypes: REPLY_TYPES,\n context: this.context,\n parse: (reply) => parseTonSignature(reply, requestId),\n });\n }\n\n /** Parse a `ton-signature` standalone. Prefer `SignRequest.scanner().parse()`. */\n parseSignature(input: Ur | string, expect?: ExpectedReply): TonSignatureResult {\n return parseTonSignature(\n toUr(input),\n expect?.requestId === undefined ? undefined : normalizeRequestId(expect.requestId),\n );\n }\n}\n\nfunction parseTonSignature(ur: Ur, expectedRequestId: Uint8Array | undefined): TonSignatureResult {\n requireUrType(ur, [...REPLY_TYPES], 'ton-signature');\n const map = requireReplyMap(ur, 'ton-signature');\n\n // The device echoes the request id BYTES verbatim (tag-37 wrapped). On this\n // chain those bytes are normally the ASCII of the UUID string; a bare\n // 16-byte binary echo is accepted too for forward compatibility.\n const echoedValue = mapGet(map, 1);\n const echoed = echoedValue === undefined ? undefined : stripTags(echoedValue);\n if (echoed?.kind !== 'bytes') {\n throw new EraSdkError('malformed-reply', 'ton-signature does not echo the request id (key 1)');\n }\n const requestId = normalizeEchoedId(echoed.value);\n if (expectedRequestId !== undefined) {\n if (requestId === null || !equalBytes(requestId, expectedRequestId)) {\n throw new EraSdkError(\n 'request-id-mismatch',\n 'ton-signature echoes a different request id — it answers another sign request, not this one',\n );\n }\n }\n\n const sigValue = mapGet(map, 2);\n const sig = sigValue === undefined ? undefined : stripTags(sigValue);\n if (sig?.kind !== 'bytes') {\n throw new EraSdkError('malformed-reply', 'ton-signature is missing the signature (key 2)');\n }\n if (sig.value.length !== 64) {\n throw new EraSdkError(\n 'malformed-reply',\n `ton-signature signature is ${sig.value.length} bytes, expected 64`,\n );\n }\n return { requestId: requestId ?? new Uint8Array(16), signature: sig.value };\n}\n\n/** ASCII-UUID-string bytes (36) or raw binary (16) → 16-byte id; null if neither. */\nfunction normalizeEchoedId(echoed: Uint8Array): Uint8Array | null {\n if (echoed.length === 16) return echoed;\n if (echoed.length === 36) {\n let text = '';\n for (const b of echoed) {\n if (b > 0x7f) return null;\n text += String.fromCharCode(b);\n }\n try {\n return normalizeRequestId(text);\n } catch {\n return null;\n }\n }\n return null;\n}\n"],"mappings":";;;AAoBA,MAAa,cAAc;;CAEzB,aAAa;;;;;CAKb,UAAU;AACZ;AAuBA,MAAM,cAAc,CAAC,eAAe;AAEpC,IAAa,WAAb,MAAsB;CAKpB,YAAY,QAA2B;EACrC,KAAK,UAAUA,eAAAA,eAAe,MAAM;CACtC;;CAGA,oBAAoB,OAA6D;EAC/E,M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sign-request` dataType (CBOR key 3). */
|
|
4
|
+
declare const TonDataType: {
|
|
5
|
+
/** `signData` is a Bag-of-Cells; the device signs the ROOT CELL's representation hash. */
|
|
6
|
+
readonly transaction: 1;
|
|
7
|
+
/**
|
|
8
|
+
* TON Connect proof: the device signs
|
|
9
|
+
* `sha256(0xFFFF || "ton-connect" || sha256(signData))`.
|
|
10
|
+
*/
|
|
11
|
+
readonly tonProof: 2;
|
|
12
|
+
};
|
|
13
|
+
type TonDataType = (typeof TonDataType)[keyof typeof TonDataType];
|
|
14
|
+
interface TonSignRequestProps {
|
|
15
|
+
readonly requestId?: Uint8Array | string;
|
|
16
|
+
/** BoC bytes (transaction) or the raw proof payload (tonProof). */
|
|
17
|
+
readonly signData: Uint8Array;
|
|
18
|
+
/** Defaults to `transaction`. */
|
|
19
|
+
readonly dataType?: TonDataType;
|
|
20
|
+
/** The account path, e.g. `m/44'/607'/0'` (V4R2 and V5R1 share it — the wallet-contract version affects only the address). */
|
|
21
|
+
readonly path: string;
|
|
22
|
+
readonly xfp: string | number;
|
|
23
|
+
/** User-friendly bounceable address TEXT (`UQ…`/`EQ…`) — shown on the device. */
|
|
24
|
+
readonly address?: string;
|
|
25
|
+
readonly origin?: string;
|
|
26
|
+
}
|
|
27
|
+
interface TonSignatureResult {
|
|
28
|
+
readonly requestId: Uint8Array;
|
|
29
|
+
/** 64-byte Ed25519 signature over the digest for the request's dataType. */
|
|
30
|
+
readonly signature: Uint8Array;
|
|
31
|
+
}
|
|
32
|
+
declare class TonChain {
|
|
33
|
+
static readonly DataType: {
|
|
34
|
+
/** `signData` is a Bag-of-Cells; the device signs the ROOT CELL's representation hash. */
|
|
35
|
+
readonly transaction: 1;
|
|
36
|
+
/**
|
|
37
|
+
* TON Connect proof: the device signs
|
|
38
|
+
* `sha256(0xFFFF || "ton-connect" || sha256(signData))`.
|
|
39
|
+
*/
|
|
40
|
+
readonly tonProof: 2;
|
|
41
|
+
};
|
|
42
|
+
private readonly context;
|
|
43
|
+
constructor(config?: EraConnectConfig);
|
|
44
|
+
/** Build a `ton-sign-request` (7201). Reply: `ton-signature` (7202). */
|
|
45
|
+
generateSignRequest(props: TonSignRequestProps): SignRequest<TonSignatureResult>;
|
|
46
|
+
/** Parse a `ton-signature` standalone. Prefer `SignRequest.scanner().parse()`. */
|
|
47
|
+
parseSignature(input: Ur | string, expect?: ExpectedReply): TonSignatureResult;
|
|
48
|
+
}
|
|
49
|
+
//#endregion
|
|
50
|
+
export { TonSignatureResult as i, TonDataType as n, TonSignRequestProps as r, TonChain as t };
|
|
51
|
+
//# sourceMappingURL=ton-DmeIvknN.d.cts.map
|
package/dist/ton.cjs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_shared = require("./shared-nISrEktU.cjs");
|
|
3
|
+
const require_ton = require("./ton-DUJGXdGa.cjs");
|
|
4
|
+
exports.AnimatedUr = require_shared.AnimatedUr;
|
|
5
|
+
exports.EraSdkError = require_shared.EraSdkError;
|
|
6
|
+
exports.TonChain = require_ton.TonChain;
|
|
7
|
+
exports.TonDataType = require_ton.TonDataType;
|
|
8
|
+
exports.TypedUrScanner = require_shared.TypedUrScanner;
|
|
9
|
+
exports.Ur = require_shared.Ur;
|
|
10
|
+
exports.UrScanner = require_shared.UrScanner;
|
package/dist/ton.d.cts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { _ as Ur, a as SignRequest, c as TypedUrScanner, d as EraErrorCode, f as EraSdkError, i as ExpectedReply, l as UrScanner, p as AnimatedUr, r as EraConnectConfig } from "./shared-CI8zhQiE.cjs";
|
|
2
|
+
import { i as TonSignatureResult, n as TonDataType, r as TonSignRequestProps, t as TonChain } from "./ton-DmeIvknN.cjs";
|
|
3
|
+
export { AnimatedUr, type EraConnectConfig, type EraErrorCode, EraSdkError, type ExpectedReply, type SignRequest, TonChain, TonDataType, type TonSignRequestProps, type TonSignatureResult, TypedUrScanner, Ur, UrScanner };
|
package/dist/ton.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { _ as Ur, a as SignRequest, c as TypedUrScanner, d as EraErrorCode, f as EraSdkError, i as ExpectedReply, l as UrScanner, p as AnimatedUr, r as EraConnectConfig } from "./shared-CI8zhQiE.js";
|
|
2
|
+
import { i as TonSignatureResult, n as TonDataType, r as TonSignRequestProps, t as TonChain } from "./ton-C0UP-cf_.js";
|
|
3
|
+
export { AnimatedUr, type EraConnectConfig, type EraErrorCode, EraSdkError, type ExpectedReply, type SignRequest, TonChain, TonDataType, type TonSignRequestProps, type TonSignatureResult, TypedUrScanner, Ur, UrScanner };
|
package/dist/ton.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { Z as EraSdkError, _ as Ur, d as UrScanner, f as AnimatedUr, u as TypedUrScanner } from "./shared-B8Wc7ViU.js";
|
|
2
|
+
import { n as TonDataType, t as TonChain } from "./ton-5Uvi5ifg.js";
|
|
3
|
+
export { AnimatedUr, EraSdkError, TonChain, TonDataType, TypedUrScanner, Ur, UrScanner };
|