@rango-dev/provider-trezor 0.31.2-next.1 → 0.31.2-next.2
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/dist/chunk-O4PNQGPF.js +2 -0
- package/dist/chunk-O4PNQGPF.js.map +7 -0
- package/dist/ethereum-2MCIGHOG.js +2 -0
- package/dist/ethereum-2MCIGHOG.js.map +7 -0
- package/dist/mod.js +1 -1
- package/dist/mod.js.map +3 -3
- package/dist/utils.d.ts +2 -0
- package/dist/{utxo-L7GRAPNY.js → utxo-P2GSGU6B.js} +2 -2
- package/package.json +9 -9
- package/src/namespaces/evm.ts +61 -1
- package/src/signers/ethereum.ts +70 -15
- package/src/utils.ts +19 -0
- package/dist/chunk-PCTGR6CA.js +0 -2
- package/dist/chunk-PCTGR6CA.js.map +0 -7
- package/dist/ethereum-INXKZXQW.js +0 -2
- package/dist/ethereum-INXKZXQW.js.map +0 -7
- /package/dist/{utxo-L7GRAPNY.js.map → utxo-P2GSGU6B.js.map} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var l=Object.defineProperty;var t=(e,r)=>l(e,"name",{value:r,configurable:!0});var s="";function N(e){s=e}t(N,"setDerivationPath");function p(){return s}t(p,"getDerivationPath");var c="";function C(e){c=e}t(C,"setBitcoinDerivationPath");function x(){return c}t(x,"getBitcoinDerivationPath");import{DEFAULT_ETHEREUM_RPC_URL as D}from"@rango-dev/signer-evm";import{JsonRpcProvider as h}from"ethers";import{CAIP_BITCOIN_CHAIN_ID as E,isChainSupported as T}from"@hub3js/bip122";import{CAIP_ETHEREUM_CHAIN_ID as d,isEvmNamespace as v}from"@hub3js/evm";import{getChainIdFromCaip2ChainId as P}from"@hub3js/std/utils";import{DefaultSignerFactory as S,TransactionType as u}from"rango-types";async function o(){let e=new S,{EthereumSigner:r}=await import("./ethereum-2MCIGHOG.js"),{BTCSigner:i}=await import("./utxo-P2GSGU6B.js");return e.registerSigner(u.EVM,new r),e.registerSigner(u.TRANSFER,new i),e}t(o,"getSigners");var z="btc",n=[{id:"native-segwit",label:"Native SegWit",purpose:84,inputScriptType:"SPENDWITNESS"},{id:"nested-segwit",label:"Nested SegWit",purpose:49,inputScriptType:"SPENDP2SHWITNESS"},{id:"legacy",label:"Legacy",purpose:44,inputScriptType:"SPENDADDRESS"},{id:"taproot",label:"Taproot",purpose:86,inputScriptType:"SPENDTAPROOT"}];function M(e){let r=Number.parseInt(e.replace(/^m\//,"").split("/")[0]?.replace(/['h]$/,"")??"",10),i=n.find(g=>g.purpose===r);if(!i)throw new Error(`Unsupported Bitcoin derivation path: ${e}`);return i.inputScriptType}t(M,"resolveBitcoinScriptType");var F="trezor",f=16,m=`0x${Number(d).toString(f)}`,V={name:"Trezor",icon:"https://raw.githubusercontent.com/rango-exchange/assets/main/wallets/trezor/icon.svg",extensions:{homepage:"https://trezor.io/learn/a/download-verify-trezor-suite"},properties:[{name:"namespaces",value:{selection:"single",data:[{label:"Ethereum",value:"EVM",id:"ETH",isChainSupported:e=>v(e)&&P(e)===d},{label:"Bitcoin",value:"UTXO",id:"BTC",isChainSupported:T([E])}]}},{name:"derivationPath",value:{data:[{id:"metamask",label:"Metamask (m/44'/60'/0'/0/index)",namespace:"EVM",generateDerivationPath:e=>`44'/60'/0'/0/${e}`},{id:"ledgerLive",label:"LedgerLive (m/44'/60'/index'/0/0)",namespace:"EVM",generateDerivationPath:e=>`44'/60'/${e}'/0/0`},{id:"legacy",label:"Legacy (m/44'/60'/0'/index)",namespace:"EVM",generateDerivationPath:e=>`44'/60'/0'/${e}`},...n.map(e=>({id:`bitcoin-${e.id}`,label:`${e.label} (m/${e.purpose}'/0'/index')`,namespace:"UTXO",generateDerivationPath:r=>`${e.purpose}'/0'/${r}'/0/0`}))]}},{name:"signers",value:{getSigners:async()=>o()}}]};var a;function G(){return a||(a=new h(D)),a}t(G,"getEvmRpcProvider");var q={Failure_ActionCancelled:"User rejected the transaction."};async function y(){let e=await import("@trezor/connect-web");return e.default.default?e.default.default:e.default}t(y,"getTrezorModule");async function K(){let e=await y(),r=p(),i=await e.ethereumGetAddress({path:r});if(!i.success)throw new Error(i.payload.error);return{accounts:[i.payload.address],chainId:m,derivationPath:r}}t(K,"getEthereumAccounts");var Q=t(e=>e&&!e.startsWith("m/")?"m/"+e:e,"getTrezorNormalizedDerivationPath");export{t as a,N as b,p as c,C as d,x as e,G as f,q as g,y as h,K as i,Q as j,z as k,M as l,F as m,m as n,V as o};
|
|
2
|
+
//# sourceMappingURL=chunk-O4PNQGPF.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/state.ts", "../src/utils.ts", "../src/constants.ts", "../src/signer.ts", "../src/utxo/config.ts"],
|
|
4
|
+
"sourcesContent": ["// We keep derivationPath here because we need to maintain it for signing transactions after it is set in connect method\nlet derivationPath = '';\n\nexport function setDerivationPath(path: string) {\n derivationPath = path;\n}\n\nexport function getDerivationPath() {\n return derivationPath;\n}\n\n/*\n * Bitcoin's connect-time path, kept for the same reason as the EVM one: Rango's PSBT\n * carries no derivation data, so the signer must remember which path to sign with. Kept\n * separate from the EVM path so the two namespaces never collide.\n */\nlet bitcoinDerivationPath = '';\n\nexport function setBitcoinDerivationPath(path: string) {\n bitcoinDerivationPath = path;\n}\n\nexport function getBitcoinDerivationPath() {\n return bitcoinDerivationPath;\n}\n", "import type { TrezorConnect } from '@trezor/connect-web';\n\nimport { DEFAULT_ETHEREUM_RPC_URL } from '@rango-dev/signer-evm';\nimport { JsonRpcProvider } from 'ethers';\n\nimport { ETHEREUM_CHAIN_ID } from './constants.js';\nimport { getDerivationPath } from './state.js';\n\ntype DeviceAccounts = {\n accounts: string[];\n chainId: string;\n derivationPath: string;\n};\n\n/**\n * Trezor EVM is Ethereum-only today and has no injected provider, so a single\n * JSON-RPC provider over the Ethereum endpoint serves both the signer (nonce +\n * broadcast) and the read-only namespace actions (allowance, receipt).\n *\n * NOTE: If Trezor EVM support ever expands beyond Ethereum, this must select\n * the RPC per chain instead of the single Ethereum endpoint.\n */\nlet evmRpcProvider: JsonRpcProvider | undefined;\nexport function getEvmRpcProvider(): JsonRpcProvider {\n if (!evmRpcProvider) {\n evmRpcProvider = new JsonRpcProvider(DEFAULT_ETHEREUM_RPC_URL);\n }\n return evmRpcProvider;\n}\n\nexport const trezorErrorMessages: { [statusCode: string]: string } = {\n Failure_ActionCancelled: 'User rejected the transaction.',\n};\n\n// `@trezor/connect-web` is commonjs, when we are importing it dynamically, it has some differences in different tooling. for example vite (you can check widget-examples), goes throw error. this is a workaround for solving this interop issue.\nexport async function getTrezorModule() {\n const mod = await import('@trezor/connect-web');\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n if (mod.default.default) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return mod.default.default as unknown as TrezorConnect;\n }\n\n return mod.default;\n}\n\nexport async function getEthereumAccounts(): Promise<DeviceAccounts> {\n const TrezorConnect = await getTrezorModule();\n const derivationPath = getDerivationPath();\n const result = await TrezorConnect.ethereumGetAddress({\n path: derivationPath,\n });\n\n if (!result.success) {\n throw new Error(result.payload.error);\n }\n\n return {\n accounts: [result.payload.address],\n chainId: ETHEREUM_CHAIN_ID,\n derivationPath,\n };\n}\n\nexport const getTrezorNormalizedDerivationPath = (\n path: string // TrezorConnect needs master node to be added to derivation path\n) => (path && !path.startsWith('m/') ? 'm/' + path : path);\n", "import type { ProviderMetadata } from '@hub3js/core';\n\nimport {\n CAIP_BITCOIN_CHAIN_ID,\n isChainSupported as isBip122ChainSupported,\n} from '@hub3js/bip122';\nimport { CAIP_ETHEREUM_CHAIN_ID, isEvmNamespace } from '@hub3js/evm';\nimport { getChainIdFromCaip2ChainId } from '@hub3js/std/utils';\n\nimport getSigners from './signer.js';\nimport { BITCOIN_ADDRESS_TYPES } from './utxo/config.js';\n\nexport const WALLET_ID = 'trezor';\n\nconst HEXADECIMAL_BASE = 16;\nexport const ETHEREUM_CHAIN_ID = `0x${Number(CAIP_ETHEREUM_CHAIN_ID).toString(\n HEXADECIMAL_BASE\n)}`;\n\nexport const metadata: ProviderMetadata = {\n name: 'Trezor',\n icon: 'https://raw.githubusercontent.com/rango-exchange/assets/main/wallets/trezor/icon.svg',\n extensions: {\n homepage: 'https://trezor.io/learn/a/download-verify-trezor-suite',\n },\n properties: [\n {\n name: 'namespaces',\n value: {\n selection: 'single',\n data: [\n {\n label: 'Ethereum',\n value: 'EVM',\n id: 'ETH',\n isChainSupported: (chainId: string) =>\n isEvmNamespace(chainId) &&\n getChainIdFromCaip2ChainId(chainId) === CAIP_ETHEREUM_CHAIN_ID,\n },\n {\n label: 'Bitcoin',\n value: 'UTXO',\n id: 'BTC',\n isChainSupported: isBip122ChainSupported([CAIP_BITCOIN_CHAIN_ID]),\n },\n ],\n },\n },\n {\n name: 'derivationPath',\n value: {\n data: [\n {\n id: 'metamask',\n label: `Metamask (m/44'/60'/0'/0/index)`,\n namespace: 'EVM',\n generateDerivationPath: (index: string) => `44'/60'/0'/0/${index}`,\n },\n {\n id: 'ledgerLive',\n label: `LedgerLive (m/44'/60'/index'/0/0)`,\n namespace: 'EVM',\n generateDerivationPath: (index: string) => `44'/60'/${index}'/0/0`,\n },\n {\n id: 'legacy',\n label: `Legacy (m/44'/60'/0'/index)`,\n namespace: 'EVM',\n generateDerivationPath: (index: string) => `44'/60'/0'/${index}`,\n },\n /*\n * Bitcoin derivation templates. The BIP-43 purpose (and thus the address\n * type) is what the user picks here; `index` selects the account.\n */\n ...BITCOIN_ADDRESS_TYPES.map((addressType) => ({\n id: `bitcoin-${addressType.id}`,\n label: `${addressType.label} (m/${addressType.purpose}'/0'/index')`,\n namespace: 'UTXO',\n generateDerivationPath: (index: string) =>\n `${addressType.purpose}'/0'/${index}'/0/0`,\n })),\n ],\n },\n },\n {\n name: 'signers',\n value: { getSigners: async () => getSigners() },\n },\n ],\n};\n", "import type { SignerFactory } from 'rango-types';\n\nimport { DefaultSignerFactory, TransactionType as TxType } from 'rango-types';\n\nexport default async function getSigners(): Promise<SignerFactory> {\n const signers = new DefaultSignerFactory();\n const { EthereumSigner } = await import('./signers/ethereum.js');\n const { BTCSigner } = await import('./signers/utxo.js');\n signers.registerSigner(TxType.EVM, new EthereumSigner());\n signers.registerSigner(TxType.TRANSFER, new BTCSigner());\n return signers;\n}\n", "/*\n * Trezor needs the input `script_type` to sign a Bitcoin input. It is determined by the\n * BIP-43 `purpose` of the derivation path the address was derived from, so we expose the\n * four common address types and let the user connect whichever one they hold funds on.\n */\nexport type TrezorInputScriptType =\n | 'SPENDADDRESS'\n | 'SPENDP2SHWITNESS'\n | 'SPENDWITNESS'\n | 'SPENDTAPROOT';\n\nexport interface BitcoinAddressType {\n /** Stable id used in the derivationPath metadata entries. */\n id: 'legacy' | 'nested-segwit' | 'native-segwit' | 'taproot';\n label: string;\n /** BIP-43 purpose: 44 legacy, 49 nested segwit, 84 native segwit, 86 taproot. */\n purpose: number;\n inputScriptType: TrezorInputScriptType;\n}\n\nexport const BITCOIN_COIN_NAME = 'btc';\n\nexport const BITCOIN_ADDRESS_TYPES: readonly BitcoinAddressType[] = [\n {\n id: 'native-segwit',\n label: 'Native SegWit',\n purpose: 84,\n inputScriptType: 'SPENDWITNESS',\n },\n {\n id: 'nested-segwit',\n label: 'Nested SegWit',\n purpose: 49,\n inputScriptType: 'SPENDP2SHWITNESS',\n },\n {\n id: 'legacy',\n label: 'Legacy',\n purpose: 44,\n inputScriptType: 'SPENDADDRESS',\n },\n {\n id: 'taproot',\n label: 'Taproot',\n purpose: 86,\n inputScriptType: 'SPENDTAPROOT',\n },\n] as const;\n\n/**\n * Resolve the Trezor input script type for a derivation path by reading its BIP-43\n * purpose (the first hardened level). The path always comes from one of our own\n * derivation templates, so an unknown purpose is a programming error.\n */\nexport function resolveBitcoinScriptType(path: string): TrezorInputScriptType {\n const purpose = Number.parseInt(\n path.replace(/^m\\//, '').split('/')[0]?.replace(/['h]$/, '') ?? '',\n 10\n );\n const addressType = BITCOIN_ADDRESS_TYPES.find(\n (type) => type.purpose === purpose\n );\n if (!addressType) {\n throw new Error(`Unsupported Bitcoin derivation path: ${path}`);\n }\n return addressType.inputScriptType;\n}\n"],
|
|
5
|
+
"mappings": "+EACA,IAAIA,EAAiB,GAEd,SAASC,EAAkBC,EAAc,CAC9CF,EAAiBE,CACnB,CAFgBC,EAAAF,EAAA,qBAIT,SAASG,GAAoB,CAClC,OAAOJ,CACT,CAFgBG,EAAAC,EAAA,qBAShB,IAAIC,EAAwB,GAErB,SAASC,EAAyBJ,EAAc,CACrDG,EAAwBH,CAC1B,CAFgBC,EAAAG,EAAA,4BAIT,SAASC,GAA2B,CACzC,OAAOF,CACT,CAFgBF,EAAAI,EAAA,4BCpBhB,OAAS,4BAAAC,MAAgC,wBACzC,OAAS,mBAAAC,MAAuB,SCDhC,OACE,yBAAAC,EACA,oBAAoBC,MACf,iBACP,OAAS,0BAAAC,EAAwB,kBAAAC,MAAsB,cACvD,OAAS,8BAAAC,MAAkC,oBCL3C,OAAS,wBAAAC,EAAsB,mBAAmBC,MAAc,cAEhE,eAAOC,GAA4D,CACjE,IAAMC,EAAU,IAAIC,EACd,CAAE,eAAAC,CAAe,EAAI,KAAM,QAAO,wBAAuB,EACzD,CAAE,UAAAC,CAAU,EAAI,KAAM,QAAO,oBAAmB,EACtD,OAAAH,EAAQ,eAAeI,EAAO,IAAK,IAAIF,CAAgB,EACvDF,EAAQ,eAAeI,EAAO,SAAU,IAAID,CAAW,EAChDH,CACT,CAP8BK,EAAAN,EAAA,cCgBvB,IAAMO,EAAoB,MAEpBC,EAAuD,CAClE,CACE,GAAI,gBACJ,MAAO,gBACP,QAAS,GACT,gBAAiB,cACnB,EACA,CACE,GAAI,gBACJ,MAAO,gBACP,QAAS,GACT,gBAAiB,kBACnB,EACA,CACE,GAAI,SACJ,MAAO,SACP,QAAS,GACT,gBAAiB,cACnB,EACA,CACE,GAAI,UACJ,MAAO,UACP,QAAS,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AO,QAAQF,CAAK,OACvC,EAAE,CACJ,CACF,CACF,EACA,CACE,KAAM,UACN,MAAO,CAAE,WAAY,SAAYG,EAAW,CAAE,CAChD,CACF,CACF,EDnEA,IAAIC,EACG,SAASC,GAAqC,CACnD,OAAKD,IACHA,EAAiB,IAAIE,EAAgBC,CAAwB,GAExDH,CACT,CALgBI,EAAAH,EAAA,qBAOT,IAAMI,EAAwD,CACnE,wBAAyB,gCAC3B,EAGA,eAAsBC,GAAkB,CACtC,IAAMC,EAAM,KAAM,QAAO,qBAAqB,EAG9C,OAAIA,EAAI,QAAQ,QAGPA,EAAI,QAAQ,QAGdA,EAAI,OACb,CAXsBH,EAAAE,EAAA,mBAatB,eAAsBE,GAA+C,CACnE,IAAMC,EAAgB,MAAMH,EAAgB,EACtCI,EAAiBC,EAAkB,EACnCC,EAAS,MAAMH,EAAc,mBAAmB,CACpD,KAAMC,CACR,CAAC,EAED,GAAI,CAACE,EAAO,QACV,MAAM,IAAI,MAAMA,EAAO,QAAQ,KAAK,EAGtC,MAAO,CACL,SAAU,CAACA,EAAO,QAAQ,OAAO,EACjC,QAASC,EACT,eAAAH,CACF,CACF,CAhBsBN,EAAAI,EAAA,uBAkBf,IAAMM,EAAoCV,EAC/CW,GACIA,GAAQ,CAACA,EAAK,WAAW,IAAI,EAAI,KAAOA,EAAOA,EAFJ",
|
|
6
|
+
"names": ["derivationPath", "setDerivationPath", "path", "__name", "getDerivationPath", "bitcoinDerivationPath", "setBitcoinDerivationPath", "getBitcoinDerivationPath", "DEFAULT_ETHEREUM_RPC_URL", "JsonRpcProvider", "CAIP_BITCOIN_CHAIN_ID", "isBip122ChainSupported", "CAIP_ETHEREUM_CHAIN_ID", "isEvmNamespace", "getChainIdFromCaip2ChainId", "DefaultSignerFactory", "TxType", "getSigners", "signers", "DefaultSignerFactory", "EthereumSigner", "BTCSigner", "TxType", "__name", "BITCOIN_COIN_NAME", "BITCOIN_ADDRESS_TYPES", "resolveBitcoinScriptType", "path", "purpose", "addressType", "type", "__name", "WALLET_ID", "HEXADECIMAL_BASE", "ETHEREUM_CHAIN_ID", "CAIP_ETHEREUM_CHAIN_ID", "metadata", "chainId", "isEvmNamespace", "getChainIdFromCaip2ChainId", "isBip122ChainSupported", "CAIP_BITCOIN_CHAIN_ID", "index", "BITCOIN_ADDRESS_TYPES", "addressType", "getSigners", "evmRpcProvider", "getEvmRpcProvider", "JsonRpcProvider", "DEFAULT_ETHEREUM_RPC_URL", "__name", "trezorErrorMessages", "getTrezorModule", "mod", "getEthereumAccounts", "TrezorConnect", "derivationPath", "getDerivationPath", "result", "ETHEREUM_CHAIN_ID", "getTrezorNormalizedDerivationPath", "path"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as i,c as u,g as l,h as p}from"./chunk-O4PNQGPF.js";import{cleanEvmError as x,DEFAULT_ETHEREUM_RPC_URL as M,toHexQuantity as s}from"@rango-dev/signer-evm";import{JsonRpcProvider as S,Transaction as b}from"ethers";import"rango-types";function z(e){return!!e.gasPrice||!!e.maxFeePerGas&&!!e.maxPriorityFeePerGas}i(z,"hasGasPricing");function D(e){return e.maxFeePerGas&&e.maxPriorityFeePerGas?{gasPrice:null,maxFeePerGas:e.maxFeePerGas.toString(),maxPriorityFeePerGas:e.maxPriorityFeePerGas.toString()}:{gasPrice:e.gasPrice?.toString()??null,maxFeePerGas:null,maxPriorityFeePerGas:null}}i(D,"pricingFromFeeData");function R(e){return typeof e=="object"&&e!==null&&"shortMessage"in e&&typeof e.shortMessage=="string"?new Error(e.shortMessage,{cause:e}):x(e)}i(R,"getTrezorErrorMessage");var F=class{static{i(this,"EthereumSigner")}async signMessage(r){let n=await p(),{success:c,payload:a}=await n.ethereumSignMessage({message:r,path:u()});if(!c)throw new Error(a.error);return a.signature}async signAndSendTx(r,n,c){try{let a=await p(),o=new S(M),G=await o.getTransactionCount(n),d=r.gasLimit??(await o.estimateGas({from:n,to:r.to,data:r.data??void 0,value:r.value??void 0})).toString(),t=z(r)?{gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas}:D(await o.getFeeData()),m=!!t.maxFeePerGas&&!!t.maxPriorityFeePerGas;if(!m&&!t.gasPrice)throw new Error("Missing gasPrice");let y=m?{maxFeePerGas:s(t.maxFeePerGas||"0"),maxPriorityFeePerGas:s(t.maxPriorityFeePerGas||"0")}:{gasPrice:s(t.gasPrice||"0")},g={to:r.to,data:r.data||"0x",value:s(r.value?.toString()||"0"),gasLimit:s(d),chainId:Number.parseInt(c),nonce:s(G.toString()),...y},{success:h,payload:P}=await a.ethereumSignTransaction({path:u(),transaction:g});if(!h){let v=l[P?.code||""]||P.error;throw new Error(v)}let{r:w,s:f,v:E}=P,T=b.from({...g,nonce:Number.parseInt(g.nonce),type:m?2:0,signature:{r:w,s:f,v:parseInt(E)}}).serialized;return{hash:(await o.broadcastTransaction(T)).hash}}catch(a){throw R(a)}}};export{F as EthereumSigner,R as getTrezorErrorMessage};
|
|
2
|
+
//# sourceMappingURL=ethereum-2MCIGHOG.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/signers/ethereum.ts"],
|
|
4
|
+
"sourcesContent": ["import type { FeeData } from 'ethers';\nimport type { EvmTransaction } from 'rango-types/mainApi';\n\nimport {\n cleanEvmError,\n DEFAULT_ETHEREUM_RPC_URL,\n toHexQuantity,\n} from '@rango-dev/signer-evm';\nimport { JsonRpcProvider, Transaction } from 'ethers';\nimport { type GenericSigner } from 'rango-types';\n\nimport { getDerivationPath } from '../state.js';\nimport { getTrezorModule, trezorErrorMessages } from '../utils.js';\n\n/** Whether a transaction already prices itself under either scheme. */\nfunction hasGasPricing(tx: EvmTransaction): boolean {\n return !!tx.gasPrice || (!!tx.maxFeePerGas && !!tx.maxPriorityFeePerGas);\n}\n\n/**\n * Picks one pricing scheme from what the node quotes. The two are mutually\n * exclusive in a signed transaction, so EIP-1559 is used wherever the chain\n * quotes it and a legacy price is the fallback.\n */\nfunction pricingFromFeeData(fees: FeeData) {\n if (fees.maxFeePerGas && fees.maxPriorityFeePerGas) {\n return {\n gasPrice: null,\n maxFeePerGas: fees.maxFeePerGas.toString(),\n maxPriorityFeePerGas: fees.maxPriorityFeePerGas.toString(),\n };\n }\n\n return {\n gasPrice: fees.gasPrice?.toString() ?? null,\n maxFeePerGas: null,\n maxPriorityFeePerGas: null,\n };\n}\n\nexport function getTrezorErrorMessage(error: unknown) {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'shortMessage' in error &&\n typeof error.shortMessage === 'string'\n ) {\n /*\n * Some error signs have lengthy, challenging-to-read messages.\n * shortMessage is used because it is shorter and easier to understand.\n */\n return new Error(error.shortMessage, { cause: error });\n }\n return cleanEvmError(error);\n}\n\nexport class EthereumSigner implements GenericSigner<EvmTransaction> {\n async signMessage(msg: string): Promise<string> {\n const TrezorConnect = await getTrezorModule();\n\n const { success, payload } = await TrezorConnect.ethereumSignMessage({\n message: msg,\n path: getDerivationPath(),\n });\n if (!success) {\n throw new Error(payload.error);\n }\n return payload.signature;\n }\n\n async signAndSendTx(\n tx: EvmTransaction,\n fromAddress: string,\n chainId: string\n ): Promise<{ hash: string }> {\n try {\n const TrezorConnect = await getTrezorModule();\n const provider = new JsonRpcProvider(DEFAULT_ETHEREUM_RPC_URL); // Provider to broadcast transaction\n const transactionCount = await provider.getTransactionCount(fromAddress); // Get nonce\n\n /*\n * Trezor signs a raw transaction on-device and does not estimate gas, so\n * a limit has to be present. Server-built transactions arrive with one;\n * client-built ones - approve prerequisites among them - do not, so it is\n * estimated here. Everything else is taken as the transaction sends it.\n */\n const gasLimit =\n tx.gasLimit ??\n (\n await provider.estimateGas({\n from: fromAddress,\n to: tx.to,\n data: tx.data ?? undefined,\n value: tx.value ?? undefined,\n })\n ).toString();\n /*\n * Whatever pricing the transaction came with wins - a server-built one\n * always carries it, and it is signed with exactly what it was created\n * with. Only a client-built transaction, which leaves both schemes null,\n * is priced from the node.\n */\n const pricing = hasGasPricing(tx)\n ? {\n gasPrice: tx.gasPrice,\n maxFeePerGas: tx.maxFeePerGas,\n maxPriorityFeePerGas: tx.maxPriorityFeePerGas,\n }\n : pricingFromFeeData(await provider.getFeeData());\n\n const isEIP1559 =\n !!pricing.maxFeePerGas && !!pricing.maxPriorityFeePerGas;\n\n if (!isEIP1559 && !pricing.gasPrice) {\n throw new Error('Missing gasPrice');\n }\n\n const additionalFields = isEIP1559\n ? {\n maxFeePerGas: toHexQuantity(pricing.maxFeePerGas || '0'),\n maxPriorityFeePerGas: toHexQuantity(\n pricing.maxPriorityFeePerGas || '0'\n ),\n }\n : {\n gasPrice: toHexQuantity(pricing.gasPrice || '0'),\n };\n\n const transaction = {\n to: tx.to,\n data: tx.data || '0x',\n value: toHexQuantity(tx.value?.toString() || '0'),\n gasLimit: toHexQuantity(gasLimit),\n chainId: Number.parseInt(chainId),\n nonce: toHexQuantity(transactionCount.toString()),\n ...additionalFields,\n };\n\n const { success, payload } = await TrezorConnect.ethereumSignTransaction({\n path: getDerivationPath(),\n transaction,\n });\n\n if (!success) {\n const errorMessage =\n trezorErrorMessages[payload?.code || ''] || payload.error;\n throw new Error(errorMessage);\n }\n const { r, s, v } = payload;\n\n const serializedTx = Transaction.from({\n ...transaction,\n nonce: Number.parseInt(transaction.nonce),\n /*\n * Type 0: This refers to the legacy transaction type that has been used since Ethereum's inception.\n * Type 2: This refers to the new transaction type introduced with the EIP-1559 (Ethereum Improvement Proposal 1559) update,\n * which was part of the London hard fork.\n */\n type: isEIP1559 ? 2 : 0,\n signature: { r, s, v: parseInt(v) },\n }).serialized;\n const broadcastResult = await provider.broadcastTransaction(serializedTx);\n\n return { hash: broadcastResult.hash };\n } catch (error) {\n throw getTrezorErrorMessage(error);\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "6DAGA,OACE,iBAAAA,EACA,4BAAAC,EACA,iBAAAC,MACK,wBACP,OAAS,mBAAAC,EAAi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qBAAqBe,CAAY,GAEzC,IAAK,CACtC,OAAS1B,EAAO,CACd,MAAMD,EAAsBC,CAAK,CACnC,CACF,CACF",
|
|
6
|
+
"names": ["cleanEvmError", "DEFAULT_ETHEREUM_RPC_URL", "toHexQuantity", "JsonRpcProvider", "Transaction", "hasGasPricing", "tx", "__name", "pricingFromFeeData", "fees", "getTrezorErrorMessage", "error", "cleanEvmError", "EthereumSigner", "msg", "TrezorConnect", "getTrezorModule", "success", "payload", "getDerivationPath", "fromAddress", "chainId", "provider", "JsonRpcProvider", "DEFAULT_ETHEREUM_RPC_URL", "transactionCount", "gasLimit", "pricing", "isEIP1559", "additionalFields", "toHexQuantity", "transaction", "errorMessage", "trezorErrorMessages", "r", "s", "v", "serializedTx", "Transaction"]
|
|
7
|
+
}
|
package/dist/mod.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as e,b as l,d as f,f as d,h as c,i as A,j as a,k as h,l as w,m as i,n as T,o as x}from"./chunk-O4PNQGPF.js";import{ProviderBuilder as G}from"@hub3js/core";import{NamespaceBuilder as _}from"@hub3js/core";import{builders as m,utils as B}from"@hub3js/evm";import*as E from"@hub3js/std/builders";import{standardizeAndThrowError as N}from"@hub3js/std/operators";import{Contract as D,toBeHex as L}from"ethers";var v=!1;async function s(){if(v)return;await(await c()).init({lazyLoad:!0,manifest:b()}),v=!0}e(s,"initTrezor");var M=["function allowance(address owner, address spender) view returns (uint256)"],R=m.connect().action(async function(r,o,t){if(!t?.derivationPath)throw new Error("Derivation Path can not be empty.");l(a(t.derivationPath)),await s();let n=await A();return{accounts:B.formatAccountsToCAIP(n.accounts,n.chainId),network:n.chainId}}).or(N).build(),U=E.disconnect().build(),W=m.getChainId().action(()=>T).build(),j=m.getAllowance().action(async(r,o)=>(await new D(o.token,M,d()).allowance(o.owner,o.spender)).toString()).build(),k=m.getTransactionReceipt().action(async(r,o)=>{let t=await d().getTransactionReceipt(o);return t?{status:t.status===1?"0x1":"0x0",transactionHash:t.hash,blockNumber:L(t.blockNumber)}:null}).build(),C=new _("EVM",i).action(R).action(U).action(W).action(j).action(k).build();import{builders as S,CAIP_BITCOIN_CHAIN_ID as F}from"@hub3js/bip122";import{NamespaceBuilder as q}from"@hub3js/core";import*as I from"@hub3js/std/builders";import{standardizeAndThrowError as V}from"@hub3js/std/operators";import{utils as O}from"@hub3js/bip122";function H(r){return async(o,t)=>{if(!t?.derivationPath)throw new Error("Derivation Path can not be empty.");await s();let n=a(t.derivationPath),p=w(n);f(n);let u=await(await c()).getAddress({path:n,coin:h,scriptType:p,showOnTrezor:!1});if(!u.success)throw new Error(u.payload.error);let{address:y}=u.payload;return O.formatAccountsToCAIP([y],r)}}e(H,"connect");var z={connect:H};var X=S.connect().action(z.connect(F)).or(V).build(),$=I.disconnect().build(),g=new q("UTXO",i).action(X).action($).build();var P,b=e(()=>P,"getTrezorManifest"),J=e(()=>new G(i).init(function(r,o){let[,t]=r.state();if(!o.manifest)throw new Error("Trezor manifest is required");P=o.manifest,t("installed",!0),console.debug("[trezor] instance detected.",r)}).config("metadata",x).add("evm",C).add("utxo",g).build(),"buildProvider");export{i as WALLET_ID,J as buildProvider};
|
|
2
2
|
//# sourceMappingURL=mod.js.map
|
package/dist/mod.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/provider.ts", "../src/namespaces/evm.ts", "../src/init.ts", "../src/namespaces/utxo.ts", "../src/actions/utxo.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Environments } from './types.js';\n\nimport { ProviderBuilder } from '@hub3js/core';\n\nimport { metadata, WALLET_ID } from './constants.js';\nimport { evm } from './namespaces/evm.js';\nimport { utxo } from './namespaces/utxo.js';\n\nlet trezorManifest: Environments['manifest'];\n\nexport const getTrezorManifest = () => trezorManifest;\n\nconst buildProvider = () =>\n new ProviderBuilder(WALLET_ID)\n .init(function (context, environments: Environments) {\n const [, setState] = context.state();\n\n if (!environments.manifest) {\n throw new Error('Trezor manifest is required');\n }\n\n trezorManifest = environments.manifest;\n setState('installed', true);\n console.debug('[trezor] instance detected.', context);\n })\n .config('metadata', metadata)\n .add('evm', evm)\n .add('utxo', utxo)\n .build();\n\nexport { buildProvider };\n", "import type {
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["ProviderBuilder", "NamespaceBuilder", "builders", "utils", "commonBuilders", "standardizeAndThrowError", "isTrezorInitialized", "initTrezor", "getTrezorModule", "getTrezorManifest", "__name", "connect", "builders", "_context", "_chain", "options", "setDerivationPath", "getTrezorNormalizedDerivationPath", "initTrezor", "result", "getEthereumAccounts", "utils", "standardizeAndThrowError", "disconnect", "getChainId", "ETHEREUM_CHAIN_ID", "evm", "NamespaceBuilder", "WALLET_ID", "builders", "CAIP_BITCOIN_CHAIN_ID", "NamespaceBuilder", "commonBuilders", "standardizeAndThrowError", "utils", "connect", "network", "_context", "options", "initTrezor", "path", "getTrezorNormalizedDerivationPath", "inputScriptType", "resolveBitcoinScriptType", "setBitcoinDerivationPath", "result", "getTrezorModule", "BITCOIN_COIN_NAME", "address", "utils", "__name", "utxoActions", "connect", "builders", "utxoActions", "CAIP_BITCOIN_CHAIN_ID", "standardizeAndThrowError", "disconnect", "utxo", "NamespaceBuilder", "WALLET_ID", "trezorManifest", "getTrezorManifest", "__name", "buildProvider", "ProviderBuilder", "WALLET_ID", "context", "environments", "setState", "metadata", "evm", "utxo"]
|
|
4
|
+
"sourcesContent": ["import type { Environments } from './types.js';\n\nimport { ProviderBuilder } from '@hub3js/core';\n\nimport { metadata, WALLET_ID } from './constants.js';\nimport { evm } from './namespaces/evm.js';\nimport { utxo } from './namespaces/utxo.js';\n\nlet trezorManifest: Environments['manifest'];\n\nexport const getTrezorManifest = () => trezorManifest;\n\nconst buildProvider = () =>\n new ProviderBuilder(WALLET_ID)\n .init(function (context, environments: Environments) {\n const [, setState] = context.state();\n\n if (!environments.manifest) {\n throw new Error('Trezor manifest is required');\n }\n\n trezorManifest = environments.manifest;\n setState('installed', true);\n console.debug('[trezor] instance detected.', context);\n })\n .config('metadata', metadata)\n .add('evm', evm)\n .add('utxo', utxo)\n .build();\n\nexport { buildProvider };\n", "import type { Context } from '@hub3js/core';\nimport type {\n AllowanceParams,\n EvmActions,\n EvmTransactionReceipt,\n} from '@hub3js/evm';\n\nimport { NamespaceBuilder } from '@hub3js/core';\nimport { builders, utils } from '@hub3js/evm';\nimport * as commonBuilders from '@hub3js/std/builders';\nimport { standardizeAndThrowError } from '@hub3js/std/operators';\nimport { Contract, toBeHex } from 'ethers';\n\nimport { ETHEREUM_CHAIN_ID, WALLET_ID } from '../constants.js';\nimport { initTrezor } from '../init.js';\nimport { setDerivationPath } from '../state.js';\nimport {\n getEthereumAccounts,\n getEvmRpcProvider,\n getTrezorNormalizedDerivationPath,\n} from '../utils.js';\n\nconst ERC20_ALLOWANCE_ABI = [\n 'function allowance(address owner, address spender) view returns (uint256)',\n];\n\nconst connect = builders\n .connect()\n .action(async function (_context, _chain, options) {\n if (!options?.derivationPath) {\n throw new Error('Derivation Path can not be empty.');\n }\n setDerivationPath(\n getTrezorNormalizedDerivationPath(options.derivationPath)\n );\n\n await initTrezor();\n\n const result = await getEthereumAccounts();\n\n const formatAccounts = utils.formatAccountsToCAIP(\n result.accounts,\n result.chainId\n );\n\n return {\n accounts: formatAccounts,\n network: result.chainId,\n };\n })\n .or(standardizeAndThrowError)\n .build();\n\nconst disconnect = commonBuilders.disconnect<EvmActions>().build();\n\nconst getChainId = builders\n .getChainId()\n .action(() => ETHEREUM_CHAIN_ID)\n .build();\n\n/*\n * Trezor injects no EIP-1193 provider, so these read actions talk to the shared\n * JSON-RPC provider directly rather than through the default hub3js/evm actions.\n */\nconst getAllowance = builders\n .getAllowance()\n .action(\n async (\n _context: Context<EvmActions>,\n params: AllowanceParams\n ): Promise<string> => {\n const token = new Contract(\n params.token,\n ERC20_ALLOWANCE_ABI,\n getEvmRpcProvider()\n );\n const currentAllowance: bigint = await token.allowance(\n params.owner,\n params.spender\n );\n return currentAllowance.toString();\n }\n )\n .build();\n\nconst getTransactionReceipt = builders\n .getTransactionReceipt()\n .action(\n async (\n _context: Context<EvmActions>,\n transactionHash: `0x${string}`\n ): Promise<EvmTransactionReceipt | null> => {\n const receipt = await getEvmRpcProvider().getTransactionReceipt(\n transactionHash\n );\n if (!receipt) {\n return null;\n }\n return {\n status: receipt.status === 1 ? '0x1' : '0x0',\n transactionHash: receipt.hash,\n blockNumber: toBeHex(receipt.blockNumber),\n };\n }\n )\n .build();\n\nconst evm = new NamespaceBuilder<EvmActions>('EVM', WALLET_ID)\n .action(connect)\n .action(disconnect)\n .action(getChainId)\n .action(getAllowance)\n .action(getTransactionReceipt)\n .build();\n\nexport { evm };\n", "import { getTrezorManifest } from './provider.js';\nimport { getTrezorModule } from './utils.js';\n\nlet isTrezorInitialized = false;\n\n/*\n * `TrezorConnect.init` throws if called twice, so initialization is shared across every\n * namespace (EVM, UTXO). `lazyLoad` defers iframe injection until the first method call.\n */\nexport async function initTrezor() {\n if (isTrezorInitialized) {\n return;\n }\n const TrezorConnect = await getTrezorModule();\n await TrezorConnect.init({\n lazyLoad: true,\n manifest: getTrezorManifest(),\n });\n isTrezorInitialized = true;\n}\n", "import type { UtxoActions } from '@hub3js/bip122';\n\nimport { builders, CAIP_BITCOIN_CHAIN_ID } from '@hub3js/bip122';\nimport { NamespaceBuilder } from '@hub3js/core';\nimport * as commonBuilders from '@hub3js/std/builders';\nimport { standardizeAndThrowError } from '@hub3js/std/operators';\n\nimport { utxoActions } from '../actions/utxo.js';\nimport { WALLET_ID } from '../constants.js';\n\nconst connect = builders\n .connect()\n .action(utxoActions.connect(CAIP_BITCOIN_CHAIN_ID))\n .or(standardizeAndThrowError)\n .build();\n\nconst disconnect = commonBuilders.disconnect<UtxoActions>().build();\n\nconst utxo = new NamespaceBuilder<UtxoActions>('UTXO', WALLET_ID)\n .action(connect)\n .action(disconnect)\n .build();\n\nexport { utxo };\n", "import type { Bip122ChainId, UtxoActions } from '@hub3js/bip122';\nimport type { Context, FunctionWithContext } from '@hub3js/core';\n\nimport { utils } from '@hub3js/bip122';\n\nimport { initTrezor } from '../init.js';\nimport { setBitcoinDerivationPath } from '../state.js';\nimport {\n getTrezorModule,\n getTrezorNormalizedDerivationPath,\n} from '../utils.js';\nimport { BITCOIN_COIN_NAME, resolveBitcoinScriptType } from '../utxo/config.js';\n\n/**\n * Connect the Bitcoin account for the selected derivation path: derive the receive\n * address and return it CAIP-encoded with the bip122 Bitcoin chain id. The path is kept\n * (like the EVM namespace does) because Rango's PSBT has no derivation data, so the\n * signer needs it at signing time.\n */\nexport function connect(\n network: Bip122ChainId\n): FunctionWithContext<UtxoActions['connect'], Context> {\n return async (_context, options) => {\n if (!options?.derivationPath) {\n throw new Error('Derivation Path can not be empty.');\n }\n\n await initTrezor();\n\n const path = getTrezorNormalizedDerivationPath(options.derivationPath);\n const inputScriptType = resolveBitcoinScriptType(path);\n setBitcoinDerivationPath(path);\n\n const TrezorConnect = await getTrezorModule();\n const result = await TrezorConnect.getAddress({\n path,\n coin: BITCOIN_COIN_NAME,\n scriptType: inputScriptType,\n showOnTrezor: false,\n });\n\n if (!result.success) {\n throw new Error(result.payload.error);\n }\n\n const { address } = result.payload;\n\n return utils.formatAccountsToCAIP([address], network);\n };\n}\n\nexport const utxoActions = { connect };\n"],
|
|
5
|
+
"mappings": "qHAEA,OAAS,mBAAAA,MAAuB,eCKhC,OAAS,oBAAAC,MAAwB,eACjC,OAAS,YAAAC,EAAU,SAAAC,MAAa,cAChC,UAAYC,MAAoB,uBAChC,OAAS,4BAAAC,MAAgC,wBACzC,OAAS,YAAAC,EAAU,WAAAC,MAAe,SCRlC,IAAIC,EAAsB,GAM1B,eAAsBC,GAAa,CACjC,GAAID,EACF,OAGF,MADsB,MAAME,EAAgB,GACxB,KAAK,CACvB,SAAU,GACV,SAAUC,EAAkB,CAC9B,CAAC,EACDH,EAAsB,EACxB,CAVsBI,EAAA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AAQC,CAAI,EAChB,MAAM,EAhBW",
|
|
6
|
+
"names": ["ProviderBuilder", "NamespaceBuilder", "builders", "utils", "commonBuilders", "standardizeAndThrowError", "Contract", "toBeHex", "isTrezorInitialized", "initTrezor", "getTrezorModule", "getTrezorManifest", "__name", "ERC20_ALLOWANCE_ABI", "connect", "builders", "_context", "_chain", "options", "setDerivationPath", "getTrezorNormalizedDerivationPath", "initTrezor", "result", "getEthereumAccounts", "utils", "standardizeAndThrowError", "disconnect", "getChainId", "ETHEREUM_CHAIN_ID", "getAllowance", "params", "Contract", "getEvmRpcProvider", "getTransactionReceipt", "transactionHash", "receipt", "toBeHex", "evm", "NamespaceBuilder", "WALLET_ID", "builders", "CAIP_BITCOIN_CHAIN_ID", "NamespaceBuilder", "commonBuilders", "standardizeAndThrowError", "utils", "connect", "network", "_context", "options", "initTrezor", "path", "getTrezorNormalizedDerivationPath", "inputScriptType", "resolveBitcoinScriptType", "setBitcoinDerivationPath", "result", "getTrezorModule", "BITCOIN_COIN_NAME", "address", "utils", "__name", "utxoActions", "connect", "builders", "utxoActions", "CAIP_BITCOIN_CHAIN_ID", "standardizeAndThrowError", "disconnect", "utxo", "NamespaceBuilder", "WALLET_ID", "trezorManifest", "getTrezorManifest", "__name", "buildProvider", "ProviderBuilder", "WALLET_ID", "context", "environments", "setState", "metadata", "evm", "utxo"]
|
|
7
7
|
}
|
package/dist/utils.d.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { TrezorConnect } from '@trezor/connect-web';
|
|
2
|
+
import { JsonRpcProvider } from 'ethers';
|
|
2
3
|
type DeviceAccounts = {
|
|
3
4
|
accounts: string[];
|
|
4
5
|
chainId: string;
|
|
5
6
|
derivationPath: string;
|
|
6
7
|
};
|
|
8
|
+
export declare function getEvmRpcProvider(): JsonRpcProvider;
|
|
7
9
|
export declare const trezorErrorMessages: {
|
|
8
10
|
[statusCode: string]: string;
|
|
9
11
|
};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as s,e as g,
|
|
2
|
-
//# sourceMappingURL=utxo-
|
|
1
|
+
import{a as s,e as g,h as m,k as d,l as h}from"./chunk-O4PNQGPF.js";import{isBitcoinBlockchain as B}from"@rango-dev/internal-blockchains";import{SignerError as S}from"rango-types";import*as x from"@bitcoinerlab/secp256k1";import*as n from"bitcoinjs-lib";n.initEccLib(x);var z=s(o=>Buffer.from(o).reverse().toString("hex"),"reverseTxid");function l(o,e,c=n.networks.bitcoin){let r=n.Psbt.fromBase64(o,{network:c}),u=h(e),T=r.txInputs.map((t,p)=>{let i=r.data.inputs[p];if(i.sighashType!=null&&i.sighashType!==n.Transaction.SIGHASH_ALL)throw new Error(`PSBT input #${p} uses sighash type ${i.sighashType}; only SIGHASH_ALL is supported.`);let a=i.witnessUtxo??n.Transaction.fromBuffer(i.nonWitnessUtxo).outs[t.index];return{address_n:e,prev_hash:z(t.hash),prev_index:t.index,amount:a.value.toString(),script_type:u,sequence:t.sequence}}),f=r.txOutputs.map(t=>t.address?{script_type:"PAYTOADDRESS",address:t.address,amount:t.value.toString()}:{script_type:"PAYTOOPRETURN",amount:"0",op_return_data:(n.script.decompile(t.script)?.find(Buffer.isBuffer)??Buffer.alloc(0)).toString("hex")});return{inputs:T,outputs:f,version:r.version,locktime:r.locktime}}s(l,"buildTrezorBitcoinTransaction");function w(o){return new Error(o.code?`${o.error} (${o.code})`:o.error)}s(w,"getTrezorErrorMessage");var b=class{static{s(this,"BTCSigner")}async signMessage(){throw S.UnimplementedError("signMessage")}async signAndSendTx(e){let{blockchain:c}=e.asset;if(!B(c))throw new Error(`Signing ${c} transactions is not supported by Trezor.`);let{psbt:r}=e;if(!r)throw new Error("No PSBT found to sign. Ensure a valid PSBT is provided.");let u=g();if(!u)throw new Error("No connected Bitcoin account found. Please connect the wallet first.");let T=await m(),{inputs:f,outputs:t,version:p,locktime:i}=l(r.unsignedPsbtBase64,u),a=await T.signTransaction({coin:d,inputs:f,outputs:t,version:p,locktime:i,push:!0});if(!a.success)throw w(a.payload);return{hash:await this.#r(a.payload)}}async#r(e){if(e.txid)return e.txid;if(!e.serializedTx)throw new Error("Trezor did not return a transaction id.");let r=await(await m()).pushTransaction({tx:e.serializedTx,coin:d});if(!r.success)throw w(r.payload);return r.payload.txid}};export{b as BTCSigner};
|
|
2
|
+
//# sourceMappingURL=utxo-P2GSGU6B.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rango-dev/provider-trezor",
|
|
3
|
-
"version": "0.31.2-next.
|
|
3
|
+
"version": "0.31.2-next.2",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"source": "./src/mod.ts",
|
|
@@ -23,17 +23,17 @@
|
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
25
|
"@bitcoinerlab/secp256k1": "^1.2.0",
|
|
26
|
-
"@hub3js/bip122": "^0.
|
|
27
|
-
"@hub3js/core": "^0.
|
|
28
|
-
"@hub3js/evm": "^0.
|
|
29
|
-
"@hub3js/std": "^0.
|
|
30
|
-
"@rango-dev/internal-blockchains": "^0.2.2-next.
|
|
31
|
-
"@rango-dev/signer-evm": "^0.46.2-next.
|
|
32
|
-
"@rango-dev/wallets-core": "^0.62.2-next.
|
|
26
|
+
"@hub3js/bip122": "^0.3.0",
|
|
27
|
+
"@hub3js/core": "^0.63.0",
|
|
28
|
+
"@hub3js/evm": "^0.6.0",
|
|
29
|
+
"@hub3js/std": "^0.5.0",
|
|
30
|
+
"@rango-dev/internal-blockchains": "^0.2.2-next.1",
|
|
31
|
+
"@rango-dev/signer-evm": "^0.46.2-next.1",
|
|
32
|
+
"@rango-dev/wallets-core": "^0.62.2-next.1",
|
|
33
33
|
"@trezor/connect-web": "^9.5.0",
|
|
34
34
|
"bitcoinjs-lib": "^6.1.7",
|
|
35
35
|
"ethers": "^6.13.2",
|
|
36
|
-
"rango-types": "^0.
|
|
36
|
+
"rango-types": "^0.6.0"
|
|
37
37
|
},
|
|
38
38
|
"publishConfig": {
|
|
39
39
|
"access": "public"
|
package/src/namespaces/evm.ts
CHANGED
|
@@ -1,18 +1,29 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Context } from '@hub3js/core';
|
|
2
|
+
import type {
|
|
3
|
+
AllowanceParams,
|
|
4
|
+
EvmActions,
|
|
5
|
+
EvmTransactionReceipt,
|
|
6
|
+
} from '@hub3js/evm';
|
|
2
7
|
|
|
3
8
|
import { NamespaceBuilder } from '@hub3js/core';
|
|
4
9
|
import { builders, utils } from '@hub3js/evm';
|
|
5
10
|
import * as commonBuilders from '@hub3js/std/builders';
|
|
6
11
|
import { standardizeAndThrowError } from '@hub3js/std/operators';
|
|
12
|
+
import { Contract, toBeHex } from 'ethers';
|
|
7
13
|
|
|
8
14
|
import { ETHEREUM_CHAIN_ID, WALLET_ID } from '../constants.js';
|
|
9
15
|
import { initTrezor } from '../init.js';
|
|
10
16
|
import { setDerivationPath } from '../state.js';
|
|
11
17
|
import {
|
|
12
18
|
getEthereumAccounts,
|
|
19
|
+
getEvmRpcProvider,
|
|
13
20
|
getTrezorNormalizedDerivationPath,
|
|
14
21
|
} from '../utils.js';
|
|
15
22
|
|
|
23
|
+
const ERC20_ALLOWANCE_ABI = [
|
|
24
|
+
'function allowance(address owner, address spender) view returns (uint256)',
|
|
25
|
+
];
|
|
26
|
+
|
|
16
27
|
const connect = builders
|
|
17
28
|
.connect()
|
|
18
29
|
.action(async function (_context, _chain, options) {
|
|
@@ -47,10 +58,59 @@ const getChainId = builders
|
|
|
47
58
|
.action(() => ETHEREUM_CHAIN_ID)
|
|
48
59
|
.build();
|
|
49
60
|
|
|
61
|
+
/*
|
|
62
|
+
* Trezor injects no EIP-1193 provider, so these read actions talk to the shared
|
|
63
|
+
* JSON-RPC provider directly rather than through the default hub3js/evm actions.
|
|
64
|
+
*/
|
|
65
|
+
const getAllowance = builders
|
|
66
|
+
.getAllowance()
|
|
67
|
+
.action(
|
|
68
|
+
async (
|
|
69
|
+
_context: Context<EvmActions>,
|
|
70
|
+
params: AllowanceParams
|
|
71
|
+
): Promise<string> => {
|
|
72
|
+
const token = new Contract(
|
|
73
|
+
params.token,
|
|
74
|
+
ERC20_ALLOWANCE_ABI,
|
|
75
|
+
getEvmRpcProvider()
|
|
76
|
+
);
|
|
77
|
+
const currentAllowance: bigint = await token.allowance(
|
|
78
|
+
params.owner,
|
|
79
|
+
params.spender
|
|
80
|
+
);
|
|
81
|
+
return currentAllowance.toString();
|
|
82
|
+
}
|
|
83
|
+
)
|
|
84
|
+
.build();
|
|
85
|
+
|
|
86
|
+
const getTransactionReceipt = builders
|
|
87
|
+
.getTransactionReceipt()
|
|
88
|
+
.action(
|
|
89
|
+
async (
|
|
90
|
+
_context: Context<EvmActions>,
|
|
91
|
+
transactionHash: `0x${string}`
|
|
92
|
+
): Promise<EvmTransactionReceipt | null> => {
|
|
93
|
+
const receipt = await getEvmRpcProvider().getTransactionReceipt(
|
|
94
|
+
transactionHash
|
|
95
|
+
);
|
|
96
|
+
if (!receipt) {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
status: receipt.status === 1 ? '0x1' : '0x0',
|
|
101
|
+
transactionHash: receipt.hash,
|
|
102
|
+
blockNumber: toBeHex(receipt.blockNumber),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
)
|
|
106
|
+
.build();
|
|
107
|
+
|
|
50
108
|
const evm = new NamespaceBuilder<EvmActions>('EVM', WALLET_ID)
|
|
51
109
|
.action(connect)
|
|
52
110
|
.action(disconnect)
|
|
53
111
|
.action(getChainId)
|
|
112
|
+
.action(getAllowance)
|
|
113
|
+
.action(getTransactionReceipt)
|
|
54
114
|
.build();
|
|
55
115
|
|
|
56
116
|
export { evm };
|
package/src/signers/ethereum.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { FeeData } from 'ethers';
|
|
1
2
|
import type { EvmTransaction } from 'rango-types/mainApi';
|
|
2
3
|
|
|
3
4
|
import {
|
|
@@ -11,6 +12,32 @@ import { type GenericSigner } from 'rango-types';
|
|
|
11
12
|
import { getDerivationPath } from '../state.js';
|
|
12
13
|
import { getTrezorModule, trezorErrorMessages } from '../utils.js';
|
|
13
14
|
|
|
15
|
+
/** Whether a transaction already prices itself under either scheme. */
|
|
16
|
+
function hasGasPricing(tx: EvmTransaction): boolean {
|
|
17
|
+
return !!tx.gasPrice || (!!tx.maxFeePerGas && !!tx.maxPriorityFeePerGas);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Picks one pricing scheme from what the node quotes. The two are mutually
|
|
22
|
+
* exclusive in a signed transaction, so EIP-1559 is used wherever the chain
|
|
23
|
+
* quotes it and a legacy price is the fallback.
|
|
24
|
+
*/
|
|
25
|
+
function pricingFromFeeData(fees: FeeData) {
|
|
26
|
+
if (fees.maxFeePerGas && fees.maxPriorityFeePerGas) {
|
|
27
|
+
return {
|
|
28
|
+
gasPrice: null,
|
|
29
|
+
maxFeePerGas: fees.maxFeePerGas.toString(),
|
|
30
|
+
maxPriorityFeePerGas: fees.maxPriorityFeePerGas.toString(),
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
gasPrice: fees.gasPrice?.toString() ?? null,
|
|
36
|
+
maxFeePerGas: null,
|
|
37
|
+
maxPriorityFeePerGas: null,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
14
41
|
export function getTrezorErrorMessage(error: unknown) {
|
|
15
42
|
if (
|
|
16
43
|
typeof error === 'object' &&
|
|
@@ -48,34 +75,62 @@ export class EthereumSigner implements GenericSigner<EvmTransaction> {
|
|
|
48
75
|
): Promise<{ hash: string }> {
|
|
49
76
|
try {
|
|
50
77
|
const TrezorConnect = await getTrezorModule();
|
|
51
|
-
const
|
|
52
|
-
const
|
|
78
|
+
const provider = new JsonRpcProvider(DEFAULT_ETHEREUM_RPC_URL); // Provider to broadcast transaction
|
|
79
|
+
const transactionCount = await provider.getTransactionCount(fromAddress); // Get nonce
|
|
53
80
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
81
|
+
/*
|
|
82
|
+
* Trezor signs a raw transaction on-device and does not estimate gas, so
|
|
83
|
+
* a limit has to be present. Server-built transactions arrive with one;
|
|
84
|
+
* client-built ones - approve prerequisites among them - do not, so it is
|
|
85
|
+
* estimated here. Everything else is taken as the transaction sends it.
|
|
86
|
+
*/
|
|
87
|
+
const gasLimit =
|
|
88
|
+
tx.gasLimit ??
|
|
89
|
+
(
|
|
90
|
+
await provider.estimateGas({
|
|
91
|
+
from: fromAddress,
|
|
92
|
+
to: tx.to,
|
|
93
|
+
data: tx.data ?? undefined,
|
|
94
|
+
value: tx.value ?? undefined,
|
|
95
|
+
})
|
|
96
|
+
).toString();
|
|
97
|
+
/*
|
|
98
|
+
* Whatever pricing the transaction came with wins - a server-built one
|
|
99
|
+
* always carries it, and it is signed with exactly what it was created
|
|
100
|
+
* with. Only a client-built transaction, which leaves both schemes null,
|
|
101
|
+
* is priced from the node.
|
|
102
|
+
*/
|
|
103
|
+
const pricing = hasGasPricing(tx)
|
|
104
|
+
? {
|
|
105
|
+
gasPrice: tx.gasPrice,
|
|
106
|
+
maxFeePerGas: tx.maxFeePerGas,
|
|
107
|
+
maxPriorityFeePerGas: tx.maxPriorityFeePerGas,
|
|
108
|
+
}
|
|
109
|
+
: pricingFromFeeData(await provider.getFeeData());
|
|
110
|
+
|
|
111
|
+
const isEIP1559 =
|
|
112
|
+
!!pricing.maxFeePerGas && !!pricing.maxPriorityFeePerGas;
|
|
113
|
+
|
|
114
|
+
if (!isEIP1559 && !pricing.gasPrice) {
|
|
61
115
|
throw new Error('Missing gasPrice');
|
|
62
116
|
}
|
|
63
|
-
|
|
64
|
-
const transactionCount = await provider.getTransactionCount(fromAddress); // Get nonce
|
|
117
|
+
|
|
65
118
|
const additionalFields = isEIP1559
|
|
66
119
|
? {
|
|
67
|
-
maxFeePerGas: toHexQuantity(maxFeePerGas || '0'),
|
|
68
|
-
maxPriorityFeePerGas: toHexQuantity(
|
|
120
|
+
maxFeePerGas: toHexQuantity(pricing.maxFeePerGas || '0'),
|
|
121
|
+
maxPriorityFeePerGas: toHexQuantity(
|
|
122
|
+
pricing.maxPriorityFeePerGas || '0'
|
|
123
|
+
),
|
|
69
124
|
}
|
|
70
125
|
: {
|
|
71
|
-
gasPrice: toHexQuantity(gasPrice || '0'),
|
|
126
|
+
gasPrice: toHexQuantity(pricing.gasPrice || '0'),
|
|
72
127
|
};
|
|
73
128
|
|
|
74
129
|
const transaction = {
|
|
75
130
|
to: tx.to,
|
|
76
131
|
data: tx.data || '0x',
|
|
77
132
|
value: toHexQuantity(tx.value?.toString() || '0'),
|
|
78
|
-
gasLimit: toHexQuantity(
|
|
133
|
+
gasLimit: toHexQuantity(gasLimit),
|
|
79
134
|
chainId: Number.parseInt(chainId),
|
|
80
135
|
nonce: toHexQuantity(transactionCount.toString()),
|
|
81
136
|
...additionalFields,
|
package/src/utils.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { TrezorConnect } from '@trezor/connect-web';
|
|
2
2
|
|
|
3
|
+
import { DEFAULT_ETHEREUM_RPC_URL } from '@rango-dev/signer-evm';
|
|
4
|
+
import { JsonRpcProvider } from 'ethers';
|
|
5
|
+
|
|
3
6
|
import { ETHEREUM_CHAIN_ID } from './constants.js';
|
|
4
7
|
import { getDerivationPath } from './state.js';
|
|
5
8
|
|
|
@@ -9,6 +12,22 @@ type DeviceAccounts = {
|
|
|
9
12
|
derivationPath: string;
|
|
10
13
|
};
|
|
11
14
|
|
|
15
|
+
/**
|
|
16
|
+
* Trezor EVM is Ethereum-only today and has no injected provider, so a single
|
|
17
|
+
* JSON-RPC provider over the Ethereum endpoint serves both the signer (nonce +
|
|
18
|
+
* broadcast) and the read-only namespace actions (allowance, receipt).
|
|
19
|
+
*
|
|
20
|
+
* NOTE: If Trezor EVM support ever expands beyond Ethereum, this must select
|
|
21
|
+
* the RPC per chain instead of the single Ethereum endpoint.
|
|
22
|
+
*/
|
|
23
|
+
let evmRpcProvider: JsonRpcProvider | undefined;
|
|
24
|
+
export function getEvmRpcProvider(): JsonRpcProvider {
|
|
25
|
+
if (!evmRpcProvider) {
|
|
26
|
+
evmRpcProvider = new JsonRpcProvider(DEFAULT_ETHEREUM_RPC_URL);
|
|
27
|
+
}
|
|
28
|
+
return evmRpcProvider;
|
|
29
|
+
}
|
|
30
|
+
|
|
12
31
|
export const trezorErrorMessages: { [statusCode: string]: string } = {
|
|
13
32
|
Failure_ActionCancelled: 'User rejected the transaction.',
|
|
14
33
|
};
|
package/dist/chunk-PCTGR6CA.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var m=Object.defineProperty;var t=(e,r)=>m(e,"name",{value:r,configurable:!0});var a="";function y(e){a=e}t(y,"setDerivationPath");function s(){return a}t(s,"getDerivationPath");var p="";function f(e){p=e}t(f,"setBitcoinDerivationPath");function I(){return p}t(I,"getBitcoinDerivationPath");import{CAIP_BITCOIN_CHAIN_ID as S,isChainSupported as T}from"@hub3js/bip122";import{CAIP_ETHEREUM_CHAIN_ID as u,isEvmNamespace as E}from"@hub3js/evm";import{getChainIdFromCaip2ChainId as D}from"@hub3js/std/utils";import{DefaultSignerFactory as l,TransactionType as c}from"rango-types";async function n(){let e=new l,{EthereumSigner:r}=await import("./ethereum-INXKZXQW.js"),{BTCSigner:i}=await import("./utxo-L7GRAPNY.js");return e.registerSigner(c.EVM,new r),e.registerSigner(c.TRANSFER,new i),e}t(n,"getSigners");var w="btc",o=[{id:"native-segwit",label:"Native SegWit",purpose:84,inputScriptType:"SPENDWITNESS"},{id:"nested-segwit",label:"Nested SegWit",purpose:49,inputScriptType:"SPENDP2SHWITNESS"},{id:"legacy",label:"Legacy",purpose:44,inputScriptType:"SPENDADDRESS"},{id:"taproot",label:"Taproot",purpose:86,inputScriptType:"SPENDTAPROOT"}];function _(e){let r=Number.parseInt(e.replace(/^m\//,"").split("/")[0]?.replace(/['h]$/,"")??"",10),i=o.find(d=>d.purpose===r);if(!i)throw new Error(`Unsupported Bitcoin derivation path: ${e}`);return i.inputScriptType}t(_,"resolveBitcoinScriptType");var L="trezor",h=16,g=`0x${Number(u).toString(h)}`,W={name:"Trezor",icon:"https://raw.githubusercontent.com/rango-exchange/assets/main/wallets/trezor/icon.svg",extensions:{homepage:"https://trezor.io/learn/a/download-verify-trezor-suite"},properties:[{name:"namespaces",value:{selection:"single",data:[{label:"Ethereum",value:"EVM",id:"ETH",isChainSupported:e=>E(e)&&D(e)===u},{label:"Bitcoin",value:"UTXO",id:"BTC",isChainSupported:T([S])}]}},{name:"derivationPath",value:{data:[{id:"metamask",label:"Metamask (m/44'/60'/0'/0/index)",namespace:"EVM",generateDerivationPath:e=>`44'/60'/0'/0/${e}`},{id:"ledgerLive",label:"LedgerLive (m/44'/60'/index'/0/0)",namespace:"EVM",generateDerivationPath:e=>`44'/60'/${e}'/0/0`},{id:"legacy",label:"Legacy (m/44'/60'/0'/index)",namespace:"EVM",generateDerivationPath:e=>`44'/60'/0'/${e}`},...o.map(e=>({id:`bitcoin-${e.id}`,label:`${e.label} (m/${e.purpose}'/0'/index')`,namespace:"UTXO",generateDerivationPath:r=>`${e.purpose}'/0'/${r}'/0/0`}))]}},{name:"signers",value:{getSigners:async()=>n()}}]};var k={Failure_ActionCancelled:"User rejected the transaction."};async function P(){let e=await import("@trezor/connect-web");return e.default.default?e.default.default:e.default}t(P,"getTrezorModule");async function X(){let e=await P(),r=s(),i=await e.ethereumGetAddress({path:r});if(!i.success)throw new Error(i.payload.error);return{accounts:[i.payload.address],chainId:g,derivationPath:r}}t(X,"getEthereumAccounts");var j=t(e=>e&&!e.startsWith("m/")?"m/"+e:e,"getTrezorNormalizedDerivationPath");export{t as a,y as b,s as c,f as d,I as e,k as f,P as g,X as h,j as i,w as j,_ as k,L as l,g as m,W as n};
|
|
2
|
-
//# sourceMappingURL=chunk-PCTGR6CA.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/state.ts", "../src/constants.ts", "../src/signer.ts", "../src/utxo/config.ts", "../src/utils.ts"],
|
|
4
|
-
"sourcesContent": ["// We keep derivationPath here because we need to maintain it for signing transactions after it is set in connect method\nlet derivationPath = '';\n\nexport function setDerivationPath(path: string) {\n derivationPath = path;\n}\n\nexport function getDerivationPath() {\n return derivationPath;\n}\n\n/*\n * Bitcoin's connect-time path, kept for the same reason as the EVM one: Rango's PSBT\n * carries no derivation data, so the signer must remember which path to sign with. Kept\n * separate from the EVM path so the two namespaces never collide.\n */\nlet bitcoinDerivationPath = '';\n\nexport function setBitcoinDerivationPath(path: string) {\n bitcoinDerivationPath = path;\n}\n\nexport function getBitcoinDerivationPath() {\n return bitcoinDerivationPath;\n}\n", "import type { ProviderMetadata } from '@hub3js/core';\n\nimport {\n CAIP_BITCOIN_CHAIN_ID,\n isChainSupported as isBip122ChainSupported,\n} from '@hub3js/bip122';\nimport { CAIP_ETHEREUM_CHAIN_ID, isEvmNamespace } from '@hub3js/evm';\nimport { getChainIdFromCaip2ChainId } from '@hub3js/std/utils';\n\nimport getSigners from './signer.js';\nimport { BITCOIN_ADDRESS_TYPES } from './utxo/config.js';\n\nexport const WALLET_ID = 'trezor';\n\nconst HEXADECIMAL_BASE = 16;\nexport const ETHEREUM_CHAIN_ID = `0x${Number(CAIP_ETHEREUM_CHAIN_ID).toString(\n HEXADECIMAL_BASE\n)}`;\n\nexport const metadata: ProviderMetadata = {\n name: 'Trezor',\n icon: 'https://raw.githubusercontent.com/rango-exchange/assets/main/wallets/trezor/icon.svg',\n extensions: {\n homepage: 'https://trezor.io/learn/a/download-verify-trezor-suite',\n },\n properties: [\n {\n name: 'namespaces',\n value: {\n selection: 'single',\n data: [\n {\n label: 'Ethereum',\n value: 'EVM',\n id: 'ETH',\n isChainSupported: (chainId: string) =>\n isEvmNamespace(chainId) &&\n getChainIdFromCaip2ChainId(chainId) === CAIP_ETHEREUM_CHAIN_ID,\n },\n {\n label: 'Bitcoin',\n value: 'UTXO',\n id: 'BTC',\n isChainSupported: isBip122ChainSupported([CAIP_BITCOIN_CHAIN_ID]),\n },\n ],\n },\n },\n {\n name: 'derivationPath',\n value: {\n data: [\n {\n id: 'metamask',\n label: `Metamask (m/44'/60'/0'/0/index)`,\n namespace: 'EVM',\n generateDerivationPath: (index: string) => `44'/60'/0'/0/${index}`,\n },\n {\n id: 'ledgerLive',\n label: `LedgerLive (m/44'/60'/index'/0/0)`,\n namespace: 'EVM',\n generateDerivationPath: (index: string) => `44'/60'/${index}'/0/0`,\n },\n {\n id: 'legacy',\n label: `Legacy (m/44'/60'/0'/index)`,\n namespace: 'EVM',\n generateDerivationPath: (index: string) => `44'/60'/0'/${index}`,\n },\n /*\n * Bitcoin derivation templates. The BIP-43 purpose (and thus the address\n * type) is what the user picks here; `index` selects the account.\n */\n ...BITCOIN_ADDRESS_TYPES.map((addressType) => ({\n id: `bitcoin-${addressType.id}`,\n label: `${addressType.label} (m/${addressType.purpose}'/0'/index')`,\n namespace: 'UTXO',\n generateDerivationPath: (index: string) =>\n `${addressType.purpose}'/0'/${index}'/0/0`,\n })),\n ],\n },\n },\n {\n name: 'signers',\n value: { getSigners: async () => getSigners() },\n },\n ],\n};\n", "import type { SignerFactory } from 'rango-types';\n\nimport { DefaultSignerFactory, TransactionType as TxType } from 'rango-types';\n\nexport default async function getSigners(): Promise<SignerFactory> {\n const signers = new DefaultSignerFactory();\n const { EthereumSigner } = await import('./signers/ethereum.js');\n const { BTCSigner } = await import('./signers/utxo.js');\n signers.registerSigner(TxType.EVM, new EthereumSigner());\n signers.registerSigner(TxType.TRANSFER, new BTCSigner());\n return signers;\n}\n", "/*\n * Trezor needs the input `script_type` to sign a Bitcoin input. It is determined by the\n * BIP-43 `purpose` of the derivation path the address was derived from, so we expose the\n * four common address types and let the user connect whichever one they hold funds on.\n */\nexport type TrezorInputScriptType =\n | 'SPENDADDRESS'\n | 'SPENDP2SHWITNESS'\n | 'SPENDWITNESS'\n | 'SPENDTAPROOT';\n\nexport interface BitcoinAddressType {\n /** Stable id used in the derivationPath metadata entries. */\n id: 'legacy' | 'nested-segwit' | 'native-segwit' | 'taproot';\n label: string;\n /** BIP-43 purpose: 44 legacy, 49 nested segwit, 84 native segwit, 86 taproot. */\n purpose: number;\n inputScriptType: TrezorInputScriptType;\n}\n\nexport const BITCOIN_COIN_NAME = 'btc';\n\nexport const BITCOIN_ADDRESS_TYPES: readonly BitcoinAddressType[] = [\n {\n id: 'native-segwit',\n label: 'Native SegWit',\n purpose: 84,\n inputScriptType: 'SPENDWITNESS',\n },\n {\n id: 'nested-segwit',\n label: 'Nested SegWit',\n purpose: 49,\n inputScriptType: 'SPENDP2SHWITNESS',\n },\n {\n id: 'legacy',\n label: 'Legacy',\n purpose: 44,\n inputScriptType: 'SPENDADDRESS',\n },\n {\n id: 'taproot',\n label: 'Taproot',\n purpose: 86,\n inputScriptType: 'SPENDTAPROOT',\n },\n] as const;\n\n/**\n * Resolve the Trezor input script type for a derivation path by reading its BIP-43\n * purpose (the first hardened level). The path always comes from one of our own\n * derivation templates, so an unknown purpose is a programming error.\n */\nexport function resolveBitcoinScriptType(path: string): TrezorInputScriptType {\n const purpose = Number.parseInt(\n path.replace(/^m\\//, '').split('/')[0]?.replace(/['h]$/, '') ?? '',\n 10\n );\n const addressType = BITCOIN_ADDRESS_TYPES.find(\n (type) => type.purpose === purpose\n );\n if (!addressType) {\n throw new Error(`Unsupported Bitcoin derivation path: ${path}`);\n }\n return addressType.inputScriptType;\n}\n", "import type { TrezorConnect } from '@trezor/connect-web';\n\nimport { ETHEREUM_CHAIN_ID } from './constants.js';\nimport { getDerivationPath } from './state.js';\n\ntype DeviceAccounts = {\n accounts: string[];\n chainId: string;\n derivationPath: string;\n};\n\nexport const trezorErrorMessages: { [statusCode: string]: string } = {\n Failure_ActionCancelled: 'User rejected the transaction.',\n};\n\n// `@trezor/connect-web` is commonjs, when we are importing it dynamically, it has some differences in different tooling. for example vite (you can check widget-examples), goes throw error. this is a workaround for solving this interop issue.\nexport async function getTrezorModule() {\n const mod = await import('@trezor/connect-web');\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n if (mod.default.default) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return mod.default.default as unknown as TrezorConnect;\n }\n\n return mod.default;\n}\n\nexport async function getEthereumAccounts(): Promise<DeviceAccounts> {\n const TrezorConnect = await getTrezorModule();\n const derivationPath = getDerivationPath();\n const result = await TrezorConnect.ethereumGetAddress({\n path: derivationPath,\n });\n\n if (!result.success) {\n throw new Error(result.payload.error);\n }\n\n return {\n accounts: [result.payload.address],\n chainId: ETHEREUM_CHAIN_ID,\n derivationPath,\n };\n}\n\nexport const getTrezorNormalizedDerivationPath = (\n path: string // TrezorConnect needs master node to be added to derivation path\n) => (path && !path.startsWith('m/') ? 'm/' + path : path);\n"],
|
|
5
|
-
"mappings": "+EACA,IAAIA,EAAiB,GAEd,SAASC,EAAkBC,EAAc,CAC9CF,EAAiBE,CACnB,CAFgBC,EAAAF,EAAA,qBAIT,SAASG,GAAoB,CAClC,OAAOJ,CACT,CAFgBG,EAAAC,EAAA,qBAShB,IAAIC,EAAwB,GAErB,SAASC,EAAyBJ,EAAc,CACrDG,EAAwBH,CAC1B,CAFgBC,EAAAG,EAAA,4BAIT,SAASC,GAA2B,CACzC,OAAOF,CACT,CAFgBF,EAAAI,EAAA,4BCpBhB,OACE,yBAAAC,EACA,oBAAoBC,MACf,iBACP,OAAS,0BAAAC,EAAwB,kBAAAC,MAAsB,cACvD,OAAS,8BAAAC,MAAkC,oBCL3C,OAAS,wBAAAC,EAAsB,mBAAmBC,MAAc,cAEhE,eAAOC,GAA4D,CACjE,IAAMC,EAAU,IAAIC,EACd,CAAE,eAA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erivationPath", "path", "__name", "getDerivationPath", "bitcoinDerivationPath", "setBitcoinDerivationPath", "getBitcoinDerivationPath", "CAIP_BITCOIN_CHAIN_ID", "isBip122ChainSupported", "CAIP_ETHEREUM_CHAIN_ID", "isEvmNamespace", "getChainIdFromCaip2ChainId", "DefaultSignerFactory", "TxType", "getSigners", "signers", "DefaultSignerFactory", "EthereumSigner", "BTCSigner", "TxType", "__name", "BITCOIN_COIN_NAME", "BITCOIN_ADDRESS_TYPES", "resolveBitcoinScriptType", "path", "purpose", "addressType", "type", "__name", "WALLET_ID", "HEXADECIMAL_BASE", "ETHEREUM_CHAIN_ID", "CAIP_ETHEREUM_CHAIN_ID", "metadata", "chainId", "isEvmNamespace", "getChainIdFromCaip2ChainId", "isBip122ChainSupported", "CAIP_BITCOIN_CHAIN_ID", "index", "BITCOIN_ADDRESS_TYPES", "addressType", "getSigners", "trezorErrorMessages", "getTrezorModule", "mod", "__name", "getEthereumAccounts", "TrezorConnect", "derivationPath", "getDerivationPath", "result", "ETHEREUM_CHAIN_ID", "getTrezorNormalizedDerivationPath", "path"]
|
|
7
|
-
}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{a as p,c as u,f as P,g as h}from"./chunk-PCTGR6CA.js";import{cleanEvmError as G,DEFAULT_ETHEREUM_RPC_URL as z,toHexQuantity as s}from"@rango-dev/signer-evm";import{JsonRpcProvider as S,Transaction as b}from"ethers";import"rango-types";function R(r){return typeof r=="object"&&r!==null&&"shortMessage"in r&&typeof r.shortMessage=="string"?new Error(r.shortMessage,{cause:r}):G(r)}p(R,"getTrezorErrorMessage");var E=class{static{p(this,"EthereumSigner")}async signMessage(e){let a=await h(),{success:o,payload:t}=await a.ethereumSignMessage({message:e,path:u()});if(!o)throw new Error(t.error);return t.signature}async signAndSendTx(e,a,o){try{let t=await h(),{gasPrice:w,maxFeePerGas:i,maxPriorityFeePerGas:c}=e,n=i&&c;if(n&&!i)throw new Error("Missing maxFeePerGas");if(n&&!c)throw new Error("Missing maxPriorityFeePerGas");if(!n&&!w)throw new Error("Missing gasPrice");let d=new S(z),f=await d.getTransactionCount(a),l=n?{maxFeePerGas:s(i||"0"),maxPriorityFeePerGas:s(c||"0")}:{gasPrice:s(w||"0")},g={to:e.to,data:e.data||"0x",value:s(e.value?.toString()||"0"),gasLimit:s(e.gasLimit?.toString()||"0"),chainId:Number.parseInt(o),nonce:s(f.toString()),...l},{success:y,payload:m}=await t.ethereumSignTransaction({path:u(),transaction:g});if(!y){let F=P[m?.code||""]||m.error;throw new Error(F)}let{r:T,s:M,v}=m,x=b.from({...g,nonce:Number.parseInt(g.nonce),type:n?2:0,signature:{r:T,s:M,v:parseInt(v)}}).serialized;return{hash:(await d.broadcastTransaction(x)).hash}}catch(t){throw R(t)}}};export{E as EthereumSigner,R as getTrezorErrorMessage};
|
|
2
|
-
//# sourceMappingURL=ethereum-INXKZXQW.js.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/signers/ethereum.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EvmTransaction } from 'rango-types/mainApi';\n\nimport {\n cleanEvmError,\n DEFAULT_ETHEREUM_RPC_URL,\n toHexQuantity,\n} from '@rango-dev/signer-evm';\nimport { JsonRpcProvider, Transaction } from 'ethers';\nimport { type GenericSigner } from 'rango-types';\n\nimport { getDerivationPath } from '../state.js';\nimport { getTrezorModule, trezorErrorMessages } from '../utils.js';\n\nexport function getTrezorErrorMessage(error: unknown) {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'shortMessage' in error &&\n typeof error.shortMessage === 'string'\n ) {\n /*\n * Some error signs have lengthy, challenging-to-read messages.\n * shortMessage is used because it is shorter and easier to understand.\n */\n return new Error(error.shortMessage, { cause: error });\n }\n return cleanEvmError(error);\n}\n\nexport class EthereumSigner implements GenericSigner<EvmTransaction> {\n async signMessage(msg: string): Promise<string> {\n const TrezorConnect = await getTrezorModule();\n\n const { success, payload } = await TrezorConnect.ethereumSignMessage({\n message: msg,\n path: getDerivationPath(),\n });\n if (!success) {\n throw new Error(payload.error);\n }\n return payload.signature;\n }\n\n async signAndSendTx(\n tx: EvmTransaction,\n fromAddress: string,\n chainId: string\n ): Promise<{ hash: string }> {\n try {\n const TrezorConnect = await getTrezorModule();\n const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = tx;\n const isEIP1559 = maxFeePerGas && maxPriorityFeePerGas;\n\n if (isEIP1559 && !maxFeePerGas) {\n throw new Error('Missing maxFeePerGas');\n }\n if (isEIP1559 && !maxPriorityFeePerGas) {\n throw new Error('Missing maxPriorityFeePerGas');\n }\n if (!isEIP1559 && !gasPrice) {\n throw new Error('Missing gasPrice');\n }\n const provider = new JsonRpcProvider(DEFAULT_ETHEREUM_RPC_URL); // Provider to broadcast transaction\n const transactionCount = await provider.getTransactionCount(fromAddress); // Get nonce\n const additionalFields = isEIP1559\n ? {\n maxFeePerGas: toHexQuantity(maxFeePerGas || '0'),\n maxPriorityFeePerGas: toHexQuantity(maxPriorityFeePerGas || '0'),\n }\n : {\n gasPrice: toHexQuantity(gasPrice || '0'),\n };\n\n const transaction = {\n to: tx.to,\n data: tx.data || '0x',\n value: toHexQuantity(tx.value?.toString() || '0'),\n gasLimit: toHexQuantity(tx.gasLimit?.toString() || '0'),\n chainId: Number.parseInt(chainId),\n nonce: toHexQuantity(transactionCount.toString()),\n ...additionalFields,\n };\n\n const { success, payload } = await TrezorConnect.ethereumSignTransaction({\n path: getDerivationPath(),\n transaction,\n });\n\n if (!success) {\n const errorMessage =\n trezorErrorMessages[payload?.code || ''] || payload.error;\n throw new Error(errorMessage);\n }\n const { r, s, v } = payload;\n\n const serializedTx = Transaction.from({\n ...transaction,\n nonce: Number.parseInt(transaction.nonce),\n /*\n * Type 0: This refers to the legacy transaction type that has been used since Ethereum's inception.\n * Type 2: This refers to the new transaction type introduced with the EIP-1559 (Ethereum Improvement Proposal 1559) update,\n * which was part of the London hard fork.\n */\n type: isEIP1559 ? 2 : 0,\n signature: { r, s, v: parseInt(v) },\n }).serialized;\n const broadcastResult = await provider.broadcastTransaction(serializedTx);\n\n return { hash: broadcastResult.hash };\n } catch (error) {\n throw getTrezorErrorMessage(error);\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "6DAEA,OACE,iBAAAA,EACA,4BAAAC,EACA,iBAAAC,MACK,wBACP,OAAS,mBAAAC,EAAiB,eAAAC,MAAmB,SAC7C,MAAmC,cAK5B,SAASC,EAAsBC,EAAgB,CACpD,OACE,OAAOA,GAAU,UACjBA,IAAU,MACV,iBAAkBA,GAClB,OAAOA,EAAM,cAAiB,SAMvB,IAAI,MAAMA,EAAM,aAAc,CAAE,MAAOA,CAAM,CAAC,EAEhDC,EAAcD,CAAK,CAC5B,CAdgBE,EAAAH,EAAA,yBAgBT,IAAMI,EAAN,KAA8D,CA7BrE,MA6BqE,CAAAD,EAAA,uBACnE,MAAM,YAAYE,EAA8B,CAC9C,IAAMC,EAAgB,MAAMC,EAAgB,EAEtC,CAAE,QAAAC,EAAS,QAAAC,CAAQ,EAAI,MAAMH,EAAc,oBAAoB,CACnE,QAASD,EACT,KAAMK,EAAkB,CAC1B,CAAC,EACD,GAAI,CAACF,EACH,MAAM,IAAI,MAAMC,EAAQ,KAAK,EAE/B,OAAOA,EAAQ,SACjB,CAEA,MAAM,cACJE,EACAC,EACAC,EAC2B,CAC3B,GAAI,CACF,IAAMP,EAAgB,MAAMC,EAAgB,EACtC,CAAE,SAAAO,EAAU,aAAAC,EAAc,qBAAAC,CAAqB,EAAIL,EACnDM,EAAYF,GAAgBC,EAElC,GAAIC,GAAa,CAACF,EAChB,MAAM,IAAI,MAAM,sBAAsB,EAExC,GAAIE,GAAa,CAACD,EAChB,MAAM,IAAI,MAAM,8BAA8B,EAEhD,GAAI,CAACC,GAAa,CAACH,EACjB,MAAM,IAAI,MAAM,kBAAkB,EAEpC,IAAMI,EAAW,IAAIC,EAAgBC,CAAwB,EACvDC,EAAmB,MAAMH,EAAS,oBAAoBN,CAAW,EACjEU,EAAmBL,EACrB,CACE,aAAcM,EAAcR,GAAgB,GAAG,EAC/C,qBAAsBQ,EAAcP,GAAwB,GAAG,CACjE,EACA,CACE,SAAUO,EAAcT,GAAY,GAAG,CACzC,EAEEU,EAAc,CAClB,GAAIb,EAAG,GACP,KAAMA,EAAG,MAAQ,KACjB,MAAOY,EAAcZ,EAAG,OAAO,SAAS,GAAK,GAAG,EAChD,SAAUY,EAAcZ,EAAG,UAAU,SAAS,GAAK,GAAG,EACtD,QAAS,OAAO,SAASE,CAAO,EAChC,MAAOU,EAAcF,EAAiB,SAAS,CAAC,EAChD,GAAGC,CACL,EAEM,CAAE,QAAAd,EAAS,QAAAC,CAAQ,EAAI,MAAMH,EAAc,wBAAwB,CACvE,KAAMI,EAAkB,EACxB,YAAAc,CACF,CAAC,EAED,GAAI,CAAChB,EAAS,CACZ,IAAMiB,EACJC,EAAoBjB,GAAS,MAAQ,EAAE,GAAKA,EAAQ,MACtD,MAAM,IAAI,MAAMgB,CAAY,CAC9B,CACA,GAAM,CAAE,EAAAE,EAAG,EAAAC,EAAG,CAAE,EAAInB,EAEdoB,EAAeC,EAAY,KAAK,CACpC,GAAGN,EACH,MAAO,OAAO,SAASA,EAAY,KAAK,EAMxC,KAAMP,EAAY,EAAI,EACtB,UAAW,CAAE,EAAAU,EAAG,EAAAC,EAAG,EAAG,SAAS,CAAC,CAAE,CACpC,CAAC,EAAE,WAGH,MAAO,CAAE,MAFe,MAAMV,EAAS,qBAAqBW,CAAY,GAEzC,IAAK,CACtC,OAAS5B,EAAO,CACd,MAAMD,EAAsBC,CAAK,CACnC,CACF,CACF",
|
|
6
|
-
"names": ["cleanEvmError", "DEFAULT_ETHEREUM_RPC_URL", "toHexQuantity", "JsonRpcProvider", "Transaction", "getTrezorErrorMessage", "error", "cleanEvmError", "__name", "EthereumSigner", "msg", "TrezorConnect", "getTrezorModule", "success", "payload", "getDerivationPath", "tx", "fromAddress", "chainId", "gasPrice", "maxFeePerGas", "maxPriorityFeePerGas", "isEIP1559", "provider", "JsonRpcProvider", "DEFAULT_ETHEREUM_RPC_URL", "transactionCount", "additionalFields", "toHexQuantity", "transaction", "errorMessage", "trezorErrorMessages", "r", "s", "serializedTx", "Transaction"]
|
|
7
|
-
}
|
|
File without changes
|