diff --git a/blockchains/internal-blockchains/package.json b/blockchains/internal-blockchains/package.json index bb3cec877f..826263bdc7 100644 --- a/blockchains/internal-blockchains/package.json +++ b/blockchains/internal-blockchains/package.json @@ -29,7 +29,7 @@ }, "dependencies": { "@hub3js/bip122": "^0.4.0", - "@hub3js/evm": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", "@hub3js/solana": "^0.7.0", "@hub3js/starknet": "^0.6.0", "@hub3js/stellar": "^0.6.0", diff --git a/patches/@reown+appkit-controllers+1.8.20.patch b/patches/@reown+appkit-controllers+1.8.20.patch deleted file mode 100644 index dc6e261e90..0000000000 --- a/patches/@reown+appkit-controllers+1.8.20.patch +++ /dev/null @@ -1,20 +0,0 @@ -diff --git a/node_modules/@reown/appkit-controllers/dist/types/src/utils/ViemUtil.d.ts b/node_modules/@reown/appkit-controllers/dist/types/src/utils/ViemUtil.d.ts -index 7fd38b994b976acf71b6e782cd888305d78fbf65..27a040e6aeecfbb8d2a7a9e9f4d53a963f5a6f9f 100644 ---- a/node_modules/@reown/appkit-controllers/dist/types/src/utils/ViemUtil.d.ts -+++ b/node_modules/@reown/appkit-controllers/dist/types/src/utils/ViemUtil.d.ts -@@ -4479,6 +4479,7 @@ export declare const ViemUtil: { - authorizationList: import("viem").TransactionSerializableEIP7702["authorizationList"]; - } ? "eip7702" : never) | (request["type"] extends string | undefined ? Extract : never)>) ? T_25 extends "eip7702" ? import("viem").TransactionRequestEIP7702 : never : never : never)>> & { - chainId?: number | undefined; -+// @ts-ignore -- generated against an older viem; generics mismatch viem@2.52.x (TS2344/TS2536). Only these 2 sites; rest of file stays checked. - }, (request["parameters"] extends readonly import("viem").PrepareTransactionRequestParameterType[] ? request["parameters"][number] : "fees" | "chainId" | "type" | "gas" | "nonce" | "blobVersionedHashes") extends infer T_26 ? T_26 extends (request["parameters"] extends readonly import("viem").PrepareTransactionRequestParameterType[] ? request["parameters"][number] : "fees" | "chainId" | "type" | "gas" | "nonce" | "blobVersionedHashes") ? T_26 extends "fees" ? "gasPrice" | "maxFeePerGas" | "maxPriorityFeePerGas" : T_26 : never : never> & (unknown extends request["kzg"] ? {} : Pick) extends infer T ? { [K in keyof T]: (import("viem").UnionRequiredBy : never)>) ? T_12 extends "eip7702" ? import("viem").TransactionRequestEIP7702 : never : never : never)>> & { - chainId?: number | undefined; -+// @ts-ignore -- generated against an older viem; generics mismatch viem@2.52.x (TS2344/TS2536). Only these 2 sites; rest of file stays checked. - }, (request["parameters"] extends readonly import("viem").PrepareTransactionRequestParameterType[] ? request["parameters"][number] : "fees" | "chainId" | "type" | "gas" | "nonce" | "blobVersionedHashes") extends infer T_13 ? T_13 extends (request["parameters"] extends readonly import("viem").PrepareTransactionRequestParameterType[] ? request["parameters"][number] : "fees" | "chainId" | "type" | "gas" | "nonce" | "blobVersionedHashes") ? T_13 extends "fees" ? "gasPrice" | "maxFeePerGas" | "maxPriorityFeePerGas" : T_13 : never : never> & (unknown extends request["kzg"] ? {} : Pick))[K]; } : never>; - readContract: , const args extends import("viem").ContractFunctionArgs>(args: import("viem").ReadContractParameters) => Promise>; - sendRawTransaction: (args: import("viem").SendRawTransactionParameters) => Promise; diff --git a/patches/viem++ox+0.14.29.patch b/patches/viem++ox+0.14.63.patch similarity index 100% rename from patches/viem++ox+0.14.29.patch rename to patches/viem++ox+0.14.63.patch diff --git a/patches/viem+2.52.2.patch b/patches/viem+2.52.2.patch deleted file mode 100644 index 1e31bbcedc..0000000000 --- a/patches/viem+2.52.2.patch +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/node_modules/viem/_types/package.json b/node_modules/viem/_types/package.json -new file mode 100644 -index 0000000000000000000000000000000000000000..089153bcb5adf57dc25f206a9dad3114c9cff80d ---- /dev/null -+++ b/node_modules/viem/_types/package.json -@@ -0,0 +1 @@ -+{"type":"module"} diff --git a/queue-manager/queue-manager-demo/src/components/Wallets/index.tsx b/queue-manager/queue-manager-demo/src/components/Wallets/index.tsx index 1feb9bad34..9637b4b195 100644 --- a/queue-manager/queue-manager-demo/src/components/Wallets/index.tsx +++ b/queue-manager/queue-manager-demo/src/components/Wallets/index.tsx @@ -1,8 +1,12 @@ -import { allProviders } from '@rango-dev/provider-all'; +import { allProviders, toNamespacesRPCUrls } from '@rango-dev/provider-all'; import { useWallets } from '@rango-dev/wallets-react'; import React from 'react'; -export const providers = allProviders().map((build) => build()); +import { RPC_URLS } from '../../configs'; + +export const providers = allProviders().map((build) => + build(toNamespacesRPCUrls(RPC_URLS)) +); export const wallets = providers.map((provider) => provider.id); diff --git a/queue-manager/queue-manager-demo/src/configs.ts b/queue-manager/queue-manager-demo/src/configs.ts index f6d8f26f39..d4342fa835 100644 --- a/queue-manager/queue-manager-demo/src/configs.ts +++ b/queue-manager/queue-manager-demo/src/configs.ts @@ -22,7 +22,7 @@ export function getConfig(name: keyof Configs) { return configs[name]; } -export function setConfig(name: keyof Configs, value: any) { +export function setConfig(name: K, value: Configs[K]) { configs[name] = value; return value; @@ -32,3 +32,11 @@ export function initConfig(nextConfigs: Configs) { configs = structuredClone(nextConfigs); return configs; } + +/** + * RPC urls for wallets that can't read the chain through themselves, such as + * Ledger and Trezor. Only Ethereum is configured here, on a public node. + */ +export const RPC_URLS = { + evm: { 1: ['https://ethereum-rpc.publicnode.com'] }, +}; diff --git a/queue-manager/queue-manager-demo/src/index.tsx b/queue-manager/queue-manager-demo/src/index.tsx index 1622c114ed..603c7cff8c 100644 --- a/queue-manager/queue-manager-demo/src/index.tsx +++ b/queue-manager/queue-manager-demo/src/index.tsx @@ -1,7 +1,11 @@ import type { WalletType } from '@hub3js/core'; import type { BlockchainMeta } from 'rango-types'; -import { allProviders, WalletTypes } from '@rango-dev/provider-all'; +import { + allProviders, + toNamespacesRPCUrls, + WalletTypes, +} from '@rango-dev/provider-all'; import { Events, Provider } from '@rango-dev/wallets-react'; import { RangoClient } from 'rango-sdk'; import React, { useEffect, useState } from 'react'; @@ -9,12 +13,15 @@ import { createRoot } from 'react-dom/client'; import { App } from './App'; import { + RPC_URLS, TON_CONNECT_MANIFEST_URL, TREZOR_MANIFEST, WC_PROJECT_ID, } from './configs'; -const providers = allProviders().map((build) => build()); +const providers = allProviders().map((build) => + build(toNamespacesRPCUrls(RPC_URLS)) +); function AppContainer() { const [connectedWallets, setConnectedWallets] = useState([]); diff --git a/queue-manager/rango-preset/package.json b/queue-manager/rango-preset/package.json index 36de0bc06c..7ee324aa56 100644 --- a/queue-manager/rango-preset/package.json +++ b/queue-manager/rango-preset/package.json @@ -36,7 +36,8 @@ }, "dependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/stellar": "^0.6.0", "@hub3js/xrpl": "^0.6.0", "@rango-dev/internal-blockchains": "^0.3.1-next.1", diff --git a/queue-manager/rango-preset/src/actions/checkApprove/adapters/evm.ts b/queue-manager/rango-preset/src/actions/checkApprove/adapters/evm.ts index ca49897c16..5727d663be 100644 --- a/queue-manager/rango-preset/src/actions/checkApprove/adapters/evm.ts +++ b/queue-manager/rango-preset/src/actions/checkApprove/adapters/evm.ts @@ -14,13 +14,28 @@ import { } from 'rango-types'; import { Ok } from 'ts-results'; -/** A receipt reporting a transaction that did not revert. */ -const RECEIPT_STATUS_SUCCESS = 1; +import { sendEvmTransaction } from '../../executeEvmTransaction'; + +/** + * viem throws this while the transaction is pending. It is matched by name so + * queue-manager doesn't depend on viem. + */ +const RECEIPT_NOT_FOUND_ERROR_NAME = 'TransactionReceiptNotFoundError'; + +function isReceiptNotFoundError(error: unknown): boolean { + let current: unknown = error; + while (current instanceof Error) { + if (current.name === RECEIPT_NOT_FOUND_ERROR_NAME) { + return true; + } + current = current.cause; + } + return false; +} export const evmApproveAdapter: ApproveAdapter<'evm', EvmTransaction> = { prerequisiteType: EVM_APPROVE_TYPE, namespaceKey: 'evm', - signerTxType: TransactionType.EVM, isApprovePrerequisite: isEvmApprovePrerequisite, @@ -49,23 +64,22 @@ export const evmApproveAdapter: ApproveAdapter<'evm', EvmTransaction> = { }) ), + send: { through: 'namespace', sendTransaction: sendEvmTransaction }, + getTransactionStatus: async ( namespace, executedTransactionHash ): Promise => { - const receipt = await namespace.getTransactionReceipt( - executedTransactionHash as `0x${string}` - ); - if (!receipt) { - return 'pending'; + try { + const receipt = await namespace.getTransactionReceipt({ + hash: executedTransactionHash as `0x${string}`, + }); + return receipt.status === 'success' ? 'success' : 'failed'; + } catch (error) { + if (isReceiptNotFoundError(error)) { + return 'pending'; + } + throw error; } - /* - * The receipt status is a quantity, and wallets are not consistent about - * how they hand it over - `0x1`, `0x01` and `1` all occur - so it is - * compared as a number rather than as the exact string the spec suggests. - */ - return Number(receipt.status) === RECEIPT_STATUS_SUCCESS - ? 'success' - : 'failed'; }, }; diff --git a/queue-manager/rango-preset/src/actions/checkApprove/adapters/tron.ts b/queue-manager/rango-preset/src/actions/checkApprove/adapters/tron.ts index 537cdc5f87..e838f10e35 100644 --- a/queue-manager/rango-preset/src/actions/checkApprove/adapters/tron.ts +++ b/queue-manager/rango-preset/src/actions/checkApprove/adapters/tron.ts @@ -19,7 +19,8 @@ import { Err, Ok } from 'ts-results'; export const tronApproveAdapter: ApproveAdapter<'tron', TronTransaction> = { prerequisiteType: TRON_APPROVE_TYPE, namespaceKey: 'tron', - signerTxType: TransactionType.TRON, + // The Tron namespace has no signing actions yet. + send: { through: 'signer', txType: TransactionType.TRON }, isApprovePrerequisite: isTronApprovePrerequisite, diff --git a/queue-manager/rango-preset/src/actions/checkApprove/checkApprove.ts b/queue-manager/rango-preset/src/actions/checkApprove/checkApprove.ts index 8cc07e0888..441507811b 100644 --- a/queue-manager/rango-preset/src/actions/checkApprove/checkApprove.ts +++ b/queue-manager/rango-preset/src/actions/checkApprove/checkApprove.ts @@ -2,6 +2,8 @@ import type { ApproveAdapter, ApproveCapableNamespaceId, ApprovePrerequisite, + NamespaceApproveSender, + SignerApproveSender, } from './types'; import type { SwapQueueContext, SwapStorage } from '../../types'; import type { NextTransactionStateError } from '../common/produceNextStateForTransaction'; @@ -29,6 +31,7 @@ import { import { checkEnvironmentBeforeExecuteTransaction } from '../common/checkEnvironmentBeforeExecuteTransaction'; import { onNextStateError } from '../common/produceNextStateForTransaction'; import { requestBlockQueue } from '../common/utils'; +import { checkEnvironmentBeforeExecuteEvmTransaction } from '../executeEvmTransaction'; import { isAllowanceSufficient } from './utils'; @@ -137,7 +140,10 @@ export async function checkApprove< * 3. Ensure wallet is connected and is on the correct network. * */ - const checkResult = await checkEnvironmentBeforeExecuteTransaction(actions); + const checkResult = + approveAdapter.namespaceKey === 'evm' + ? await checkEnvironmentBeforeExecuteEvmTransaction(actions) + : checkEnvironmentBeforeExecuteTransaction(actions); if (checkResult.err) { requestBlockQueue(actions, checkResult.val); return; @@ -203,9 +209,23 @@ export async function checkApprove< const chainId = meta.blockchains[unmetApproveMeta.prerequisite.blockChain]?.chainId; const walletAddress = getCurrentAddressOf(swap, currentStep); - const walletSigners = await getSigners(sourceWallet.walletType); - const signer: GenericSigner = - walletSigners.getSigner(approveAdapter.signerTxType); + const sender: + | NamespaceApproveSender + | SignerApproveSender = approveAdapter.send; + const sendApproveTransaction = async (transaction: TTransaction) => { + if (sender.through === 'namespace') { + return sender.sendTransaction( + namespace, + transaction, + walletAddress, + chainId ?? null + ); + } + const walletSigners = await getSigners(sourceWallet.walletType); + const signer: GenericSigner = + walletSigners.getSigner(sender.txType); + return signer.signAndSendTx(transaction, walletAddress, chainId); + }; /* * Approving takes two waits, and telling them apart matters to the user: a @@ -235,10 +255,8 @@ export async function checkApprove< isApproval: true, }); - const transactionResult = await signer.signAndSendTx( - approveTransactionResult.val, - walletAddress, - chainId + const transactionResult = await sendApproveTransaction( + approveTransactionResult.val ); updateStorageWithPrerequisiteResult(actions, { diff --git a/queue-manager/rango-preset/src/actions/checkApprove/types.ts b/queue-manager/rango-preset/src/actions/checkApprove/types.ts index 065e18599f..955693683d 100644 --- a/queue-manager/rango-preset/src/actions/checkApprove/types.ts +++ b/queue-manager/rango-preset/src/actions/checkApprove/types.ts @@ -52,6 +52,40 @@ export type ExecutedApproveResult = Extract< { data: { executedTransactionHash: string } } >; +/** Sends the approve transaction through the wallet's namespace. */ +export type NamespaceApproveSender< + K extends ApproveCapableNamespaceId, + TTransaction extends Transaction +> = { + through: 'namespace'; + sendTransaction: ( + namespace: ApproveCapableNamespace, + transaction: TTransaction, + walletAddress: string, + chainId: string | null + ) => Promise<{ hash: string }>; +}; + +/** + * Sends the approve transaction through the wallet's signer for `txType`, for + * chains whose namespace can't sign yet. + */ +export type SignerApproveSender = { + through: 'signer'; + txType: TransactionType; +}; + +/** + * EVM approvals always go through the namespace; only other chains may still + * fall back to a signer. + */ +export type ApproveSender< + K extends ApproveCapableNamespaceId, + TTransaction extends Transaction +> = [K] extends ['evm'] + ? NamespaceApproveSender + : NamespaceApproveSender | SignerApproveSender; + /** * Per-chain strategy for the generic approve-prerequisite actions. Everything * that differs between EVM and Tron is captured here; the actions themselves are @@ -65,8 +99,6 @@ export interface ApproveAdapter< prerequisiteType: TransactionPrerequisiteType; /** The hub namespace key backing this chain, e.g. `'evm'` | `'tron'`. */ namespaceKey: K; - /** The signer transaction type used to sign the approve tx. */ - signerTxType: TransactionType; /** Type guard for this chain's approve prerequisite. */ isApprovePrerequisite: ( prerequisite: TransactionPrerequisite @@ -80,6 +112,8 @@ export interface ApproveAdapter< prerequisite: ApprovePrerequisite, namespace: ApproveCapableNamespace ) => Promise>; + /** How the signed approve transaction is sent. */ + send: ApproveSender; /** Reads the on-chain status of a submitted approve transaction. */ getTransactionStatus: ( namespace: ApproveCapableNamespace, diff --git a/queue-manager/rango-preset/src/actions/checkPrerequisites/checkPrerequisites.ts b/queue-manager/rango-preset/src/actions/checkPrerequisites/checkPrerequisites.ts index 3ccf10e040..73ad8785d9 100644 --- a/queue-manager/rango-preset/src/actions/checkPrerequisites/checkPrerequisites.ts +++ b/queue-manager/rango-preset/src/actions/checkPrerequisites/checkPrerequisites.ts @@ -7,6 +7,7 @@ import { Networks } from '@rango-dev/internal-blockchains'; import { EVM_APPROVE_TYPE, STELLAR_CHANGE_TRUSTLINE_TYPE, + TransactionType, TRON_APPROVE_TYPE, XRPL_CHANGE_TRUSTLINE_TYPE, } from 'rango-types'; @@ -121,6 +122,8 @@ export async function checkPrerequisites( result = new Ok(SwapActionTypes.EXECUTE_XRPL_TRANSACTION); } else if (currentStep.fromBlockchain === Networks.HYPERLIQUID) { result = new Ok(SwapActionTypes.EXECUTE_HYPERLIQUID_TRANSACTION); + } else if (getCurrentStepTx(currentStep)?.type === TransactionType.EVM) { + result = new Ok(SwapActionTypes.EXECUTE_EVM_TRANSACTION); } else { result = new Ok(SwapActionTypes.EXECUTE_TRANSACTION); } diff --git a/queue-manager/rango-preset/src/actions/checkStatus.ts b/queue-manager/rango-preset/src/actions/checkStatus.ts index 7ac9154dba..db563e6706 100644 --- a/queue-manager/rango-preset/src/actions/checkStatus.ts +++ b/queue-manager/rango-preset/src/actions/checkStatus.ts @@ -2,19 +2,17 @@ import type { SwapQueueContext, SwapStorage } from '../types'; import type { ExecuterActions } from '@rango-dev/queue-manager-core'; import type { CheckTxStatusRequest, - Transaction, TransactionStatusResponse, } from 'rango-sdk'; import { warn } from '@rango-dev/logging-core'; -import { type GenericSigner, SignerError } from 'rango-types'; +import { SignerError } from 'rango-types'; import { createStepFailedEvent, delay, getCurrentStep, getCurrentStepTx, - getCurrentStepTxType, getLastFinishedStepInput, getLastFinishedStepInputUsd, getLastSuccessfulStepOutputUsd, @@ -28,15 +26,18 @@ import { notifier } from '../services/eventEmitter'; import { getCurrentNamespaceOf, getNextStep, - getRelatedWallet, getScannerUrl, MessageSeverity, } from '../shared'; import { prettifyErrorMessage } from '../shared-errors'; import { StepEventType, SwapActionTypes } from '../types'; +import { + getEvmNamespaceOfStep, + waitForEvmTransaction, +} from './executeEvmTransaction'; + const INTERVAL_FOR_CHECK_STATUS = 5_000; -const INTERVAL_FOR_CHECK_APPROVAL = 5_000; /** * Subscribe to status of swap transaction by checking from server periodically. @@ -68,36 +69,25 @@ async function checkTransactionStatus({ let txId = currentStep.executedTransactionId; let getTxReceiptFailed = false; let status: TransactionStatusResponse | null = null; - let signer: GenericSigner | null = null; const { getTransactionDataByHash, setTransactionDataByHash } = inMemoryTransactionsData(); + /* + * Only EVM transactions are waited for through the wallet, which also tells + * when one was replaced. Null when the wallet isn't connected yet. + */ + const evmNamespace = getEvmNamespaceOfStep(context, swap, currentStep); try { - const txType = getCurrentStepTxType(currentStep); - const sourceWallet = getRelatedWallet(swap, currentStep); - if (txType && sourceWallet) { - signer = (await context.getSigners(sourceWallet.walletType)).getSigner( - txType - ); - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - } catch (error) { - /* - * wallet is not connected yet - * no need to do anything - */ - } - - try { - // if wallet is connected, try to get transaction reciept - const { response: txResponse, receiptReceived } = - getTransactionDataByHash(txId); - if (signer?.wait && !receiptReceived) { + const { receiptReceived } = getTransactionDataByHash(txId); + if (evmNamespace && !receiptReceived) { const chainId = (tx?.blockChain && meta.blockchains?.[tx?.blockChain]?.chainId) || undefined; - const { hash: updatedTxHash, response: updatedTxResponse } = - await signer.wait(txId, chainId, txResponse); + const { hash: updatedTxHash } = await waitForEvmTransaction( + evmNamespace, + txId, + chainId + ); if (updatedTxHash !== txId) { currentStep.executedTransactionId = updatedTxHash || currentStep.executedTransactionId; @@ -120,11 +110,6 @@ async function checkTransactionStatus({ } } txId = currentStep.executedTransactionId; - if (updatedTxHash && updatedTxResponse) { - setTransactionDataByHash(updatedTxHash, { - response: updatedTxResponse, - }); - } } else { setTransactionDataByHash(updatedTxHash, { receiptReceived: true, @@ -289,256 +274,35 @@ async function checkTransactionStatus({ } /** - * Subscribe to status of approval transaction by checking from server periodically. - * After getting the status, notify the user and schedule `SCHEDULE_NEXT_STEP`. + * Approvals now run as transaction prerequisites, which track their own status, + * so a step only waits for an approval here when it was saved by an older + * version that sent the server-built approve transaction. Its approve + * transaction is dropped and the step starts over: the prerequisite flow reads + * the allowance on-chain, so a mined approval isn't asked for again. */ -async function checkApprovalStatus({ +function restartLegacyApproval({ getStorage, setStorage, - next, schedule, - retry, - failed, - context, -}: ExecuterActions< - SwapStorage, - SwapActionTypes, - SwapQueueContext ->): Promise { + next, +}: ExecuterActions): void { const swap = getStorage().swapDetails; - const { meta } = context; - const { getTransactionDataByHash, setTransactionDataByHash } = - inMemoryTransactionsData(); - const checkApprovalStatusError = new Error('check approval status error'); - - const currentStep = getCurrentStep(swap); - if (!currentStep) { - console.log('ignore check status, current step is null'); - return; - } - const tx = getCurrentStepTx(currentStep); - - if (!currentStep?.executedTransactionId) { - return; - } - let txId = currentStep.executedTransactionId; - - let signer: GenericSigner | null = null; - try { - const txType = getCurrentStepTxType(currentStep); - const sourceWallet = getRelatedWallet(swap, currentStep); - if (txType && sourceWallet) { - const walletSigners = await context.getSigners(sourceWallet.walletType); - signer = walletSigners.getSigner(txType); - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - } catch (error) { - /* - * wallet is not connected yet - * no need to do anything - */ - } - - try { - const { response: txResponse, receiptReceived } = - getTransactionDataByHash(txId); - // if wallet is connected, try to get transaction reciept - if (signer?.wait && !receiptReceived) { - const chainId = - (tx?.blockChain && meta.blockchains?.[tx?.blockChain]?.chainId) || - undefined; - const { hash: updatedTxHash, response: updatedTxResponse } = - await signer.wait(txId, chainId, txResponse); - if (updatedTxHash !== txId) { - currentStep.executedTransactionId = - updatedTxHash || currentStep.executedTransactionId; - const currentStepNamespace = getCurrentNamespaceOf(swap, currentStep); - let explorerUrl: string | undefined; - const blockchainsMetaNotEmpty = !!Object.keys(meta.blockchains).length; - if (blockchainsMetaNotEmpty) { - explorerUrl = getScannerUrl( - currentStep.executedTransactionId, - currentStepNamespace.network, - meta.blockchains - ); - } - if (explorerUrl) { - if (currentStep.explorerUrl && currentStep.explorerUrl?.length >= 1) { - currentStep.explorerUrl[currentStep.explorerUrl.length - 1] = { - url: explorerUrl, - description: 'Replaced Approve', - }; - } - } - txId = currentStep.executedTransactionId; - if (updatedTxHash && updatedTxResponse) { - setTransactionDataByHash(updatedTxHash, { - response: updatedTxResponse, - }); - } - } else { - setTransactionDataByHash(updatedTxHash, { - receiptReceived: true, - }); - } - } - } catch (error) { - const { extraMessage, extraMessageDetail, extraMessageErrorCode } = - prettifyErrorMessage(error); - const updateResult = updateSwapStatus({ - getStorage, - setStorage, - nextStatus: 'failed', - nextStepStatus: 'failed', - message: extraMessage, - details: extraMessageDetail, - errorCode: extraMessageErrorCode, - }); - - const event = createStepFailedEvent( - swap, - extraMessage, - updateResult.failureType - ); - - notifier({ - event, - ...updateResult, - }); - warn(checkApprovalStatusError, { - tags: { - type: 'singer-error', - reason: event.reason, - reasonCode: event.reasonCode, - message: extraMessage, - messageDetail: extraMessageDetail, - pendingSwap: swap, - }, - context: SignerError.isSignerError(error) ? error.getErrorContext() : {}, - }); - return failed(); - } - - let isApproved = false; - const request: { requestId: string; txId?: string } = { - requestId: swap.requestId, - txId: currentStep.executedTransactionId, - }; - - try { - const response = await httpService().checkApproval( - request.requestId, - request.txId - ); - // If user cancel swap during check status api call, we should ignore check approval response - if (currentStep?.status === 'failed') { - return; - } - - isApproved = response.isApproved; - if ( - !isApproved && - (response.txStatus === 'failed' || response.txStatus === 'success') - ) { - let message, details; - if (response.txStatus === 'failed') { - message = 'Approve transaction failed'; - details = 'Smart contract approval tx failed in blockchain.'; - } else { - message = 'Not enough approval'; - if (response.requiredApprovedAmount && response.currentApprovedAmount) { - details = `Required approval: ${response.requiredApprovedAmount}, current approval: ${response.currentApprovedAmount}`; - } else { - details = `You still don't have enough approval for this swap.`; - } - } - /* - * approve transaction failed on - * we should fail the whole swap - */ - const updateResult = updateSwapStatus({ - getStorage, - setStorage, - nextStatus: 'failed', - nextStepStatus: 'failed', - errorCode: 'INSUFFICIENT_APPROVE', - message: message, - details: details, - }); - - const event = createStepFailedEvent( - swap, - message, - updateResult.failureType - ); - - notifier({ - event, - ...updateResult, - }); - - warn(checkApprovalStatusError, { - tags: { - type: 'approval-failed', - message: swap.extraMessage, - messageDetails: swap.extraMessageDetail, - pendingSwap: swap, - }, - }); - - failed(); - } else if (!isApproved) { - // it is needed to set notification after reloading the page - notifier({ - event: { type: StepEventType.CHECK_STATUS }, - swap, - step: currentStep, - }); - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - } catch (e) { - isApproved = false; - warn(checkApprovalStatusError, { - tags: { type: 'request-error', requestBody: request, pendingSwap: swap }, - }); - } - if (isApproved) { - currentStep.status = 'approved'; - swap.extraMessage = `Spending ${currentStep.fromSymbol} approved successfully.`; - swap.extraMessageDetail = null; - swap.extraMessageSeverity = MessageSeverity.success; - currentStep.evmApprovalTransaction = null; - currentStep.executedTransactionId = null; - currentStep.executedTransactionTime = null; - currentStep.starknetApprovalTransaction = null; - currentStep.tronApprovalTransaction = null; - - setStorage({ - ...getStorage(), - swapDetails: swap, - }); + const currentStep = getCurrentStep(swap)!; - notifier({ - event: { type: StepEventType.APPROVAL_TX_SUCCEEDED }, - swap: swap, - step: currentStep, - }); + currentStep.status = 'created'; + currentStep.evmApprovalTransaction = null; + currentStep.starknetApprovalTransaction = null; + currentStep.tronApprovalTransaction = null; + currentStep.executedTransactionId = null; + currentStep.executedTransactionTime = null; - schedule(SwapActionTypes.SCHEDULE_NEXT_STEP); - next(); - } else { - await delay(INTERVAL_FOR_CHECK_APPROVAL); - retry(); - } + setStorage({ ...getStorage(), swapDetails: swap }); + schedule(SwapActionTypes.SCHEDULE_NEXT_STEP); + next(); } /** - * - * For doing a swap the user needs to accept a `contract` so it can use the user balance. - * There is two types of check status: - * 1. Checking approval transaction (Give permission to a contract) - * 2. Checking swap transaction. - * + * Checks the status of the current step's swap transaction. */ export async function checkStatus( actions: ExecuterActions @@ -559,6 +323,6 @@ export async function checkStatus( if (currentStep.status === 'running') { await checkTransactionStatus(actions); } else if (currentStep.status === 'waitingForApproval') { - await checkApprovalStatus(actions); + restartLegacyApproval(actions); } } diff --git a/queue-manager/rango-preset/src/actions/common/checkEnvironmentBeforeExecuteTransaction.ts b/queue-manager/rango-preset/src/actions/common/checkEnvironmentBeforeExecuteTransaction.ts index 0222c88539..45928656b2 100644 --- a/queue-manager/rango-preset/src/actions/common/checkEnvironmentBeforeExecuteTransaction.ts +++ b/queue-manager/rango-preset/src/actions/common/checkEnvironmentBeforeExecuteTransaction.ts @@ -8,80 +8,28 @@ import type { ExecuterActions, } from '@rango-dev/queue-manager-core'; -import { PendingSwapNetworkStatus } from 'rango-types'; import { Err, Ok, type Result } from 'ts-results'; import { - ERROR_MESSAGE_DEPENDS_ON_OTHER_QUEUES, - ERROR_MESSAGE_WAIT_FOR_CHANGE_NETWORK, ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION, ERROR_MESSAGE_WAIT_FOR_WALLET_DESCRIPTION_WRONG_WALLET, } from '../../constants'; import { - claimQueue, - getCurrentStep, - getRequiredSignNetwork, getRequiredWallet, - isNeedBlockQueueForParallel, - isNetworkMatchedForTransaction, isRequiredWalletConnected, isWalletNull, - updateNetworkStatus, } from '../../helpers'; -import { getCurrentNamespaceOf } from '../../shared'; import { BlockReason } from '../../types'; -import { isClaimedByCurrentQueue } from './utils'; - /** - * Check for network & address be matched and queue to not be blocked and update the swap accordingly. + * Makes sure the wallet the transaction needs is connected, and the connected + * wallet's address matches the transaction's. EVM transactions run more checks + * on top, see `checkEnvironmentBeforeExecuteEvmTransaction`. */ -export async function checkEnvironmentBeforeExecuteTransaction( +export function checkEnvironmentBeforeExecuteTransaction( actions: ExecuterActions -): Promise> { - const { getStorage, context } = actions; - - const swap = getStorage().swapDetails; - - const currentStep = getCurrentStep(swap)!; - - /* Make sure wallet is connected and also the connected wallet is matched with tx by checking address. */ - const addressCheckResult = ensureRequiredWalletIsConnected(actions); - if (addressCheckResult.err) { - return addressCheckResult; - } - - /* Wallet should be on correct network */ - const networkResult = await ensureWalletIsOnCorrectNetwork(actions); - if (networkResult.err) { - return networkResult; - } - - if (currentStep.networkStatus === PendingSwapNetworkStatus.NetworkChanged) { - // Considering that network is matched now, if currently network status of the current step is equal to `NetworkChanged`, we need to update the network status to mark it as network changed successfully. - updateNetworkStatus(actions, { - message: '', - details: 'The network has been successfully changed.', - status: PendingSwapNetworkStatus.NetworkChanged, - }); - } - - /* - *For avoiding conflict by making too many requests to wallet, we need to make sure - *We only run one request at a time (In parallel mode). - */ - const needsToBlockQueue = isNeedBlockQueueForParallel(currentStep); - const isClaimed = isClaimedByCurrentQueue(context); - if (needsToBlockQueue && !isClaimed) { - const blockedFor = { - reason: BlockReason.DEPENDS_ON_OTHER_QUEUES, - description: ERROR_MESSAGE_DEPENDS_ON_OTHER_QUEUES, - details: {}, - }; - return new Err(blockedFor); - } - - return new Ok(true); +): Result { + return ensureRequiredWalletIsConnected(actions); } function ensureRequiredWalletIsConnected( @@ -111,47 +59,3 @@ function ensureRequiredWalletIsConnected( return new Ok(true); } - -async function ensureWalletIsOnCorrectNetwork( - actions: ExecuterActions -): Promise> { - const { getStorage, context } = actions; - const { meta, wallets, hubProvider } = context; - const swap = getStorage().swapDetails; - const currentStep = getCurrentStep(swap)!; - - const networkMatched = await isNetworkMatchedForTransaction( - swap, - currentStep, - wallets, - meta, - hubProvider - ); - - const { claimedBy } = claimQueue(); - const claimerId = claimedBy(); - const isClaimedByAnyQueue = !!claimerId && !isClaimedByCurrentQueue(context); - - if (isClaimedByAnyQueue && !networkMatched) { - const details = ERROR_MESSAGE_DEPENDS_ON_OTHER_QUEUES; - - const blockedFor = { - reason: BlockReason.DEPENDS_ON_OTHER_QUEUES, - details: details, - }; - return new Err(blockedFor); - } else if (!networkMatched) { - const fromNamespace = getCurrentNamespaceOf(swap, currentStep); - const details = ERROR_MESSAGE_WAIT_FOR_CHANGE_NETWORK( - getRequiredSignNetwork(currentStep, fromNamespace.network) - ); - - const blockedFor = { - reason: BlockReason.WAIT_FOR_NETWORK_CHANGE, - details: details, - }; - return new Err(blockedFor); - } - - return new Ok(true); -} diff --git a/queue-manager/rango-preset/src/actions/executeEvmTransaction/checkEnvironmentBeforeExecuteEvmTransaction.ts b/queue-manager/rango-preset/src/actions/executeEvmTransaction/checkEnvironmentBeforeExecuteEvmTransaction.ts new file mode 100644 index 0000000000..946c82448e --- /dev/null +++ b/queue-manager/rango-preset/src/actions/executeEvmTransaction/checkEnvironmentBeforeExecuteEvmTransaction.ts @@ -0,0 +1,126 @@ +import type { + SwapActionTypes, + SwapQueueContext, + SwapStorage, +} from '../../types'; +import type { + BlockedReason, + ExecuterActions, +} from '@rango-dev/queue-manager-core'; + +import { PendingSwapNetworkStatus } from 'rango-types'; +import { Err, Ok, type Result } from 'ts-results'; + +import { + ERROR_MESSAGE_DEPENDS_ON_OTHER_QUEUES, + ERROR_MESSAGE_WAIT_FOR_CHANGE_NETWORK, +} from '../../constants'; +import { + claimQueue, + getCurrentStep, + getRequiredSignNetwork, + isNeedBlockQueueForParallel, + isNetworkMatchedForTransaction, + updateNetworkStatus, +} from '../../helpers'; +import { getCurrentNamespaceOf } from '../../shared'; +import { BlockReason } from '../../types'; +import { checkEnvironmentBeforeExecuteTransaction } from '../common/checkEnvironmentBeforeExecuteTransaction'; +import { isClaimedByCurrentQueue } from '../common/utils'; + +/** + * The checks an EVM transaction needs before it's sent to the wallet: the + * wallet is connected with the right address, it's on the transaction's + * network, and no other queue is using the wallet (in parallel mode). + */ +export async function checkEnvironmentBeforeExecuteEvmTransaction( + actions: ExecuterActions +): Promise> { + const { getStorage, context } = actions; + + const swap = getStorage().swapDetails; + + const currentStep = getCurrentStep(swap)!; + + /* Make sure wallet is connected and also the connected wallet is matched with tx by checking address. */ + const addressCheckResult = checkEnvironmentBeforeExecuteTransaction(actions); + if (addressCheckResult.err) { + return addressCheckResult; + } + + /* Wallet should be on correct network */ + const networkResult = await ensureWalletIsOnCorrectNetwork(actions); + if (networkResult.err) { + return networkResult; + } + + if (currentStep.networkStatus === PendingSwapNetworkStatus.NetworkChanged) { + // Considering that network is matched now, if currently network status of the current step is equal to `NetworkChanged`, we need to update the network status to mark it as network changed successfully. + updateNetworkStatus(actions, { + message: '', + details: 'The network has been successfully changed.', + status: PendingSwapNetworkStatus.NetworkChanged, + }); + } + + /* + *For avoiding conflict by making too many requests to wallet, we need to make sure + *We only run one request at a time (In parallel mode). + */ + const needsToBlockQueue = isNeedBlockQueueForParallel(currentStep); + const isClaimed = isClaimedByCurrentQueue(context); + if (needsToBlockQueue && !isClaimed) { + const blockedFor = { + reason: BlockReason.DEPENDS_ON_OTHER_QUEUES, + description: ERROR_MESSAGE_DEPENDS_ON_OTHER_QUEUES, + details: {}, + }; + return new Err(blockedFor); + } + + return new Ok(true); +} + +async function ensureWalletIsOnCorrectNetwork( + actions: ExecuterActions +): Promise> { + const { getStorage, context } = actions; + const { meta, wallets, hubProvider } = context; + const swap = getStorage().swapDetails; + const currentStep = getCurrentStep(swap)!; + + const networkMatched = await isNetworkMatchedForTransaction( + swap, + currentStep, + wallets, + meta, + hubProvider + ); + + const { claimedBy } = claimQueue(); + const claimerId = claimedBy(); + const isClaimedByAnyQueue = !!claimerId && !isClaimedByCurrentQueue(context); + + if (isClaimedByAnyQueue && !networkMatched) { + const details = ERROR_MESSAGE_DEPENDS_ON_OTHER_QUEUES; + + const blockedFor = { + reason: BlockReason.DEPENDS_ON_OTHER_QUEUES, + details: details, + }; + return new Err(blockedFor); + } else if (!networkMatched) { + const fromNamespace = getCurrentNamespaceOf(swap, currentStep); + const details = ERROR_MESSAGE_WAIT_FOR_CHANGE_NETWORK( + getRequiredSignNetwork(currentStep, fromNamespace.network) + ); + + const blockedFor = { + reason: BlockReason.WAIT_FOR_NETWORK_CHANGE, + details: details, + }; + return new Err(blockedFor); + } + + return new Ok(true); +} diff --git a/queue-manager/rango-preset/src/actions/executeEvmTransaction/executeEvmTransaction.ts b/queue-manager/rango-preset/src/actions/executeEvmTransaction/executeEvmTransaction.ts new file mode 100644 index 0000000000..4d6be7a59f --- /dev/null +++ b/queue-manager/rango-preset/src/actions/executeEvmTransaction/executeEvmTransaction.ts @@ -0,0 +1,90 @@ +import type { + SwapActionTypes, + SwapQueueContext, + SwapStorage, +} from '../../types'; +import type { ExecuterActions } from '@rango-dev/queue-manager-core'; +import type { EvmTransaction } from 'rango-sdk'; + +import { + getCurrentStep, + getCurrentStepTx, + handleRejectedSign, + handleSuccessfulSign, + isApprovalCurrentStepTx, + resetNetworkStatus, +} from '../../helpers'; +import { getCurrentAddressOf } from '../../shared'; +import { + onNextStateError, + onNextStateOk, + produceNextStateForTransaction, +} from '../common/produceNextStateForTransaction'; +import { requestBlockQueue } from '../common/utils'; + +import { checkEnvironmentBeforeExecuteEvmTransaction } from './checkEnvironmentBeforeExecuteEvmTransaction'; +import { getEvmNamespaceOfStep, sendEvmTransaction } from './utils'; + +/** + * Sends the current step's EVM transaction through the wallet's EVM namespace. + * + * Parallel swaps that share a wallet go through a `claim` mechanism, so only + * one of them talks to the wallet at a time. The claim is released once the + * wallet returns, and the transaction is then followed by the status check. + */ +export async function executeEvmTransaction( + actions: ExecuterActions +): Promise { + const checkResult = await checkEnvironmentBeforeExecuteEvmTransaction( + actions + ); + if (checkResult.err) { + requestBlockQueue(actions, checkResult.val); + return; + } + + resetNetworkStatus(actions); + + const { failed, getStorage, context } = actions; + const { meta } = context; + + const swap = getStorage().swapDetails; + const currentStep = getCurrentStep(swap)!; + const isApproval = isApprovalCurrentStepTx(currentStep); + + const onFinish = () => { + if (actions.context.resetClaimedBy) { + actions.context.resetClaimedBy(); + } + }; + + const nextStateResult = produceNextStateForTransaction(actions); + if (nextStateResult.err) { + onNextStateError(actions, nextStateResult.val); + failed(); + onFinish(); + return; + } + onNextStateOk(actions, nextStateResult.val); + + // `produceNextStateForTransaction` has checked the tx isn't null. + const tx = getCurrentStepTx(currentStep) as EvmTransaction; + const walletAddress = getCurrentAddressOf(swap, currentStep); + const chainId = meta.blockchains?.[tx.blockChain]?.chainId ?? null; + + const namespace = getEvmNamespaceOfStep(context, swap, currentStep); + if (!namespace) { + handleRejectedSign(actions)( + new Error('The EVM namespace is not available on your wallet.') + ); + onFinish(); + return; + } + + await sendEvmTransaction(namespace, tx, walletAddress, chainId) + .then( + handleSuccessfulSign(actions, { isApproval }), + handleRejectedSign(actions) + ) + .finally(onFinish); +} diff --git a/queue-manager/rango-preset/src/actions/executeEvmTransaction/index.ts b/queue-manager/rango-preset/src/actions/executeEvmTransaction/index.ts new file mode 100644 index 0000000000..b16b05c519 --- /dev/null +++ b/queue-manager/rango-preset/src/actions/executeEvmTransaction/index.ts @@ -0,0 +1,9 @@ +export { executeEvmTransaction } from './executeEvmTransaction.js'; +export { checkEnvironmentBeforeExecuteEvmTransaction } from './checkEnvironmentBeforeExecuteEvmTransaction.js'; +export { + getEvmNamespaceOfStep, + sendEvmTransaction, + signEvmTypedData, + waitForEvmTransaction, +} from './utils.js'; +export type { EvmNamespace } from './utils.js'; diff --git a/queue-manager/rango-preset/src/actions/executeEvmTransaction/utils.test.ts b/queue-manager/rango-preset/src/actions/executeEvmTransaction/utils.test.ts new file mode 100644 index 0000000000..41bb86a9f4 --- /dev/null +++ b/queue-manager/rango-preset/src/actions/executeEvmTransaction/utils.test.ts @@ -0,0 +1,275 @@ +import type { EvmActions, ProviderAPI } from '@hub3js/evm'; +import type { EvmTransaction } from 'rango-sdk'; + +import { createStore, NamespaceBuilder, ProviderBuilder } from '@hub3js/core'; +import { viemWalletAdapter } from '@hub3js/evm'; +import { + RPCErrorCode, + SignerError, + SignerErrorCode, + TransactionType, +} from 'rango-types'; +import { describe, expect, test, vi } from 'vitest'; + +import { sendEvmTransaction } from './utils'; + +const ADDRESS = '0x1111111111111111111111111111111111111111'; +const TO = '0x2222222222222222222222222222222222222222'; +const HASH_BYTES = 32; +const TEST_WALLET_METADATA = { + name: 'Test Wallet', + icon: 'https://example.com/icon.svg', + extensions: { homepage: 'https://example.com' }, +}; +const HASH = `0x${'ab'.repeat(HASH_BYTES)}`; + +function createEvmTransaction( + overrides: Partial = {} +): EvmTransaction { + return { + type: TransactionType.EVM, + blockChain: 'ETH', + isApprovalTx: false, + from: ADDRESS, + to: TO, + data: '0xabcdef', + value: null, + nonce: null, + gasLimit: '21000', + gasPrice: null, + maxFeePerGas: '30000000000', + maxPriorityFeePerGas: '1000000000', + prerequisites: [], + ...overrides, + }; +} + +/** + * A namespace with viem's wallet actions over a fake EIP-1193 provider, so the + * exact `eth_sendTransaction` params can be asserted. + */ +function createNamespace( + sendTransaction: (params: unknown) => unknown = () => HASH +) { + const request = vi.fn( + async ({ method, params }: { method: string; params?: unknown[] }) => { + if (method === 'eth_sendTransaction') { + return sendTransaction(params?.[0]); + } + if (method === 'eth_chainId') { + return '0x1'; + } + throw new Error(`Unexpected method: ${method}`); + } + ); + const instance = { request } as unknown as ProviderAPI; + + const evm = new NamespaceBuilder('EVM', 'test-wallet') + .action('getChainId', async () => '0x1') + .action(viemWalletAdapter(() => instance)) + .build(); + const provider = new ProviderBuilder('test-wallet', { + store: createStore(), + }) + .config('metadata', TEST_WALLET_METADATA) + .add('evm', evm) + .build(); + provider.init(); + + const [, setState] = evm.state(); + setState('connected', true); + setState('accounts', [`eip155:1:${ADDRESS}`]); + setState('network', '0x1'); + + return { namespace: evm, request }; +} + +function sentParams(request: ReturnType) { + return request.mock.calls + .map(([args]) => args) + .filter(({ method }) => method === 'eth_sendTransaction') + .map(({ params }) => params[0]); +} + +describe('sendEvmTransaction', () => { + test('sends hex quantities, gas and an explicit zero value', async () => { + const { namespace, request } = createNamespace(); + + const result = await sendEvmTransaction( + namespace, + createEvmTransaction(), + ADDRESS, + '1' + ); + + expect(result).toEqual({ hash: HASH }); + expect(sentParams(request)).toEqual([ + { + from: ADDRESS, + to: TO, + data: '0xabcdef', + value: '0x0', + gas: '0x5208', + maxFeePerGas: '0x6fc23ac00', + maxPriorityFeePerGas: '0x3b9aca00', + }, + ]); + }); + + test('sends a legacy gas price and a nonce when given', async () => { + const { namespace, request } = createNamespace(); + + await sendEvmTransaction( + namespace, + createEvmTransaction({ + value: '1000', + nonce: '7', + gasPrice: '20000000000', + maxFeePerGas: null, + maxPriorityFeePerGas: null, + }), + ADDRESS, + '1' + ); + + expect(sentParams(request)[0]).toMatchObject({ + value: '0x3e8', + nonce: '0x7', + gasPrice: '0x4a817c800', + }); + }); + + test('retries without EIP-1559 fees when the wallet rejects them', async () => { + let attempts = 0; + const { namespace, request } = createNamespace(() => { + attempts++; + if (attempts === 1) { + throw new Error('EIP-1559 is not supported'); + } + return HASH; + }); + + await sendEvmTransaction( + namespace, + createEvmTransaction({ gasPrice: '20000000000' }), + ADDRESS, + '1' + ); + + const [first, retry] = sentParams(request); + expect(first).toHaveProperty('maxFeePerGas'); + expect(retry).not.toHaveProperty('maxFeePerGas'); + expect(retry).toMatchObject({ gasPrice: '0x4a817c800' }); + }); + + test('reports a user rejection as a rejection', async () => { + const { namespace } = createNamespace(() => { + throw Object.assign(new Error('User rejected the request.'), { + code: 4001, + }); + }); + + const error = await sendEvmTransaction( + namespace, + createEvmTransaction(), + ADDRESS, + '1' + ).catch((error: unknown) => error); + + expect(SignerError.isSignerError(error)).toBe(true); + expect((error as SignerError).rpcCode).toBe(RPCErrorCode.REJECTION); + }); + + test("fails when the wallet resolves with 'null' instead of a hash", async () => { + const { namespace } = createNamespace(() => 'null'); + + const error = await sendEvmTransaction( + namespace, + createEvmTransaction(), + ADDRESS, + '1' + ).catch((error: unknown) => error); + + expect((error as SignerError).code).toBe(SignerErrorCode.SEND_TX_ERROR); + expect((error as SignerError).getErrorDetail().detail).toMatch( + /invalid hash.*hash=null/ + ); + }); + + test("fails when the legacy gas retry resolves with 'null'", async () => { + let attempts = 0; + const { namespace, request } = createNamespace(() => { + attempts++; + if (attempts === 1) { + throw new Error('EIP-1559 is not supported'); + } + return 'null'; + }); + + const error = await sendEvmTransaction( + namespace, + createEvmTransaction({ gasPrice: '20000000000' }), + ADDRESS, + '1' + ).catch((error: unknown) => error); + + expect(sentParams(request)).toHaveLength(2); + expect((error as SignerError).getErrorDetail().detail).toMatch( + /invalid hash.*hash=null/ + ); + }); + + test('keeps the context the wallet attached to its error', async () => { + const context = { peering: { name: 'Rainbow' }, code: 5000 }; + const { namespace } = createNamespace(() => { + throw Object.assign(new Error('Relay request failed'), { context }); + }); + + const error = await sendEvmTransaction( + namespace, + createEvmTransaction(), + ADDRESS, + '1' + ).catch((error: unknown) => error); + + expect((error as SignerError).getErrorContext()).toMatchObject(context); + }); + + test("refuses to send when the wallet's chain doesn't match", async () => { + const { namespace, request } = createNamespace(); + + const error = await sendEvmTransaction( + namespace, + createEvmTransaction(), + ADDRESS, + '137' + ).catch((error: unknown) => error); + + expect((error as SignerError).code).toBe( + SignerErrorCode.UNEXPECTED_BEHAVIOUR + ); + expect((error as SignerError).getErrorDetail().detail).toMatch( + /doesn't match with required chainId/ + ); + expect(sentParams(request)).toHaveLength(0); + }); + + test("refuses to send when the wallet's address doesn't match", async () => { + const { namespace, request } = createNamespace(); + + const error = await sendEvmTransaction( + namespace, + createEvmTransaction(), + '0x3333333333333333333333333333333333333333', + '1' + ).catch((error: unknown) => error); + + expect((error as SignerError).code).toBe( + SignerErrorCode.UNEXPECTED_BEHAVIOUR + ); + expect((error as SignerError).getErrorDetail().detail).toMatch( + /doesn't match with required address/ + ); + expect(sentParams(request)).toHaveLength(0); + }); +}); diff --git a/queue-manager/rango-preset/src/actions/executeEvmTransaction/utils.ts b/queue-manager/rango-preset/src/actions/executeEvmTransaction/utils.ts new file mode 100644 index 0000000000..3c34907b1d --- /dev/null +++ b/queue-manager/rango-preset/src/actions/executeEvmTransaction/utils.ts @@ -0,0 +1,395 @@ +import type { SwapQueueContext } from '../../types'; +import type { FindProxiedNamespace } from '@hub3js/core'; +import type { EvmActions, TypedDataDefinition } from '@hub3js/evm'; +import type { DefaultNamespaces } from '@hub3js/namespaces'; +import type { EvmTransaction } from 'rango-sdk'; +import type { PendingSwap, PendingSwapStep } from 'rango-types'; + +import { + RPCErrorCode, + SignerError, + SignerErrorCode, + TransactionType, +} from 'rango-types'; + +import { getCurrentStepTxType } from '../../helpers'; +import { getRelatedWalletOrNull } from '../../shared'; + +export type EvmNamespace = FindProxiedNamespace<'evm', DefaultNamespaces>; + +type SendTransactionParameters = NonNullable< + Parameters[0] +>; + +/** + * A namespace action some wallets add when the hash `sendTransaction` returns + * is not the on-chain one, e.g. Safe returns a safeTxHash. It resolves the + * on-chain hash, and is skipped for wallets that don't register it. + */ +const RESOLVE_TRANSACTION_HASH_ACTION = 'resolveTransactionHash'; +type ResolveTransactionHash = (hash: string) => Promise; + +/** EIP-1193 code for a request the user rejected. */ +const USER_REJECTED_REQUEST_CODE = 4001; + +function* errorChain(error: unknown) { + let current: unknown = error; + while (current) { + yield current as { name?: string; code?: unknown; message?: string }; + current = current instanceof Error ? current.cause : undefined; + } +} + +function errorChainIncludes(error: unknown, text: string): boolean { + for (const item of errorChain(error)) { + if (typeof item.message === 'string' && item.message.includes(text)) { + return true; + } + } + return false; +} + +/** + * Turns what a wallet or viem throws into a `SignerError`. viem wraps the + * wallet's error, so a rejection is looked for along the `cause` chain. + */ +export function toEvmSignerError( + error: unknown, + code: SignerErrorCode = SignerErrorCode.SEND_TX_ERROR +): SignerError { + if (SignerError.isSignerError(error)) { + return error; + } + if (!error) { + return new SignerError(code); + } + + let isRejected = false; + let context: Record | undefined; + for (const item of errorChain(error)) { + /* + * A wallet can attach context for the logs to the error it throws, e.g. + * WalletConnect adds the session's peer. viem wraps it, so it's looked for + * along the chain. + */ + const itemContext = (item as { context?: unknown }).context; + if (!context && itemContext && typeof itemContext === 'object') { + context = itemContext as Record; + } + if ( + item.code === USER_REJECTED_REQUEST_CODE || + item.name === 'UserRejectedRequestError' + ) { + isRejected = true; + break; + } + } + + const message = + error instanceof Error + ? (error as Error & { shortMessage?: string }).shortMessage || + error.message + : error; + + return new SignerError( + code, + undefined, + message, + isRejected ? RPCErrorCode.REJECTION : RPCErrorCode.UNKNOWN_ERROR, + error, + context + ); +} + +/** + * Converts a transaction from Rango's API into the request viem's + * `sendTransaction` takes. `legacyGas` drops the EIP-1559 fees in favour of + * `gasPrice`, for wallets that reject them. + * + * The request holds bigints, so it is built right before sending and never + * stored with the swap. + */ +export function toEvmTransactionRequest( + tx: EvmTransaction, + account: string, + options: { legacyGas?: boolean } = {} +): SendTransactionParameters { + const request: Record = { + account, + // The network is checked before sending, so viem doesn't assert it again. + chain: null, + to: tx.to, + /* + * `0x` rather than undefined, otherwise some wallets could face issue + * https://github.com/WalletConnect/web3modal/issues/1082#issuecomment-1637793242 + */ + data: tx.data || '0x', + // Some wallets reject a missing value, so a zero value is sent explicitly. + value: BigInt(tx.value || 0), + }; + + if (tx.nonce) { + request.nonce = Number(BigInt(tx.nonce)); + } + if (tx.gasLimit) { + request.gas = BigInt(tx.gasLimit); + } + if (!options.legacyGas && tx.maxFeePerGas && tx.maxPriorityFeePerGas) { + request.maxFeePerGas = BigInt(tx.maxFeePerGas); + request.maxPriorityFeePerGas = BigInt(tx.maxPriorityFeePerGas); + } else if (tx.gasPrice) { + request.gasPrice = BigInt(tx.gasPrice); + } + + // Built loosely because viem types each fee scheme as its own variant. + return request as SendTransactionParameters; +} + +/** + * The EVM namespace of the wallet that sends the step's transaction. Null when + * the transaction isn't EVM, or the wallet has no EVM namespace or isn't + * connected yet. + */ +export function getEvmNamespaceOfStep( + context: SwapQueueContext, + swap: PendingSwap, + step: PendingSwapStep +): EvmNamespace | null { + if (getCurrentStepTxType(step) !== TransactionType.EVM) { + return null; + } + const sourceWallet = getRelatedWalletOrNull(swap, step); + if (!sourceWallet) { + return null; + } + try { + return context.hubProvider(sourceWallet.walletType).get('evm') ?? null; + } catch { + return null; + } +} + +function getActiveAddress(namespace: EvmNamespace): string | undefined { + const [getState] = namespace.state(); + const accounts = getState('accounts') as string[] | null | undefined; + // Accounts are CAIP-10 (`eip155:1:0xabc`), the address is the last part. + return accounts?.[0]?.split(':').pop(); +} + +async function assertWalletMatches( + namespace: EvmNamespace, + address: string, + chainId: string | null +) { + if (chainId) { + const walletChainId = await namespace.getChainId(); + if (walletChainId && Number(walletChainId) !== Number(chainId)) { + throw new SignerError( + SignerErrorCode.UNEXPECTED_BEHAVIOUR, + undefined, + `Wallet chainId: '${Number( + walletChainId + )}' doesn't match with required chainId: '${Number(chainId)}' for tx.` + ); + } + } + + const walletAddress = getActiveAddress(namespace); + if ( + walletAddress && + address && + walletAddress.toLowerCase() !== address.toLowerCase() + ) { + throw new SignerError( + SignerErrorCode.UNEXPECTED_BEHAVIOUR, + undefined, + `Wallet address: '${walletAddress.toLowerCase()}' doesn't match with required address: '${address.toLowerCase()}' for tx.` + ); + } +} + +/** + * Some wallets (e.g. Rainbow over WalletConnect) resolve `eth_sendTransaction` + * with `'null'` instead of throwing when the user rejects it. Neither viem nor + * the namespace checks the result, so it's checked here, before it can be + * stored and polled as the transaction's hash. + */ +function assertTransactionHash(hash: unknown): `0x${string}` { + if (typeof hash !== 'string' || !hash.startsWith('0x')) { + throw new Error( + `Received an invalid hash on signing the transaction. (hash=${String( + hash + )})` + ); + } + return hash as `0x${string}`; +} + +/** + * Sends a transaction from Rango's API through the wallet's EVM namespace. + */ +export async function sendEvmTransaction( + namespace: EvmNamespace, + tx: EvmTransaction, + address: string, + chainId: string | null +): Promise<{ hash: string }> { + if (!('sendTransaction' in namespace)) { + throw SignerError.UnsupportedError('executeEvmTransaction'); + } + + try { + await assertWalletMatches(namespace, address, chainId); + + try { + const hash = await namespace.sendTransaction( + toEvmTransactionRequest(tx, address) + ); + return { hash: assertTransactionHash(hash) }; + } catch (error) { + // Some wallets reject EIP-1559 fees, retry with a legacy gas price. + if (errorChainIncludes(error, 'EIP-1559')) { + console.log('retrying EIP-1559 error without v2 fields ...'); + const hash = await namespace.sendTransaction( + toEvmTransactionRequest(tx, address, { legacyGas: true }) + ); + return { hash: assertTransactionHash(hash) }; + } + throw error; + } + } catch (error) { + throw toEvmSignerError(error); + } +} + +/** + * Signs EIP-712 typed data through the wallet's EVM namespace. + */ +export async function signEvmTypedData( + namespace: EvmNamespace, + typedData: TypedDataDefinition, + address: string +): Promise<`0x${string}`> { + try { + return await namespace.signTypedData({ + ...typedData, + account: address as `0x${string}`, + }); + } catch (error) { + throw toEvmSignerError(error, SignerErrorCode.SIGN_TX_ERROR); + } +} + +interface TenderlyResponse { + error_message: string; +} + +async function getTenderlyError( + chainId: string | undefined, + txHash: string +): Promise { + if (!chainId || !txHash) { + return; + } + try { + const url = `https://api.tenderly.co/api/v1/public-contract/${parseInt( + chainId + )}/tx/${txHash}`; + const response = await fetch(url, { method: 'GET' }); + if (!response.ok) { + return; + } + const data: TenderlyResponse = await response.json(); + return data?.error_message; + } catch { + return; + } +} + +function hasResolveTransactionHash(namespace: EvmNamespace): boolean { + return RESOLVE_TRANSACTION_HASH_ACTION in namespace; +} + +/** + * Waits for a sent EVM transaction to be mined, following it if it gets + * replaced. Returns the hash to track it by, which differs from `hash` when the + * wallet returned another kind of hash or the transaction was replaced. + * + * Only a cancelled transaction, or one that reverted for a reason Tenderly can + * give, throws. Anything else is left to the backend's status check. + */ +export async function waitForEvmTransaction( + namespace: EvmNamespace, + hash: string, + chainId: string | undefined +): Promise<{ hash: string }> { + let txHash = hash; + + try { + if (hasResolveTransactionHash(namespace)) { + const resolveTransactionHash = ( + namespace as unknown as Record + )[RESOLVE_TRANSACTION_HASH_ACTION]; + txHash = await resolveTransactionHash(hash); + } + + /* + * The receipt is read through the wallet, which only sees the chain it's on. + * If the user has switched networks in the meantime, leave it to the + * backend's status check. + */ + const [getState] = namespace.state(); + if (!getState('connected') || !chainId) { + return { hash: txHash }; + } + const walletChainId = await namespace.getChainId(); + if ( + Number(walletChainId) !== Number(chainId) || + !('waitForTransactionReceipt' in namespace) + ) { + return { hash: txHash }; + } + + let replacementReason: string | undefined; + const receipt = await namespace.waitForTransactionReceipt({ + hash: txHash as `0x${string}`, + onReplaced: (replacement) => { + replacementReason = replacement.reason; + }, + }); + + if (replacementReason === 'cancelled') { + throw new SignerError( + SignerErrorCode.SEND_TX_ERROR, + undefined, + 'Transaction replaced and canceled by user' + ); + } + + if (receipt.status === 'reverted') { + const tenderlyError = await getTenderlyError( + chainId, + receipt.transactionHash + ); + if (tenderlyError) { + throw new SignerError( + SignerErrorCode.TX_FAILED_IN_BLOCKCHAIN, + 'Transaction failed in blockchain', + tenderlyError, + RPCErrorCode.CALL_EXCEPTION + ); + } + } + + return { hash: receipt.transactionHash }; + } catch (error) { + if (SignerError.isSignerError(error)) { + throw error; + } + /* + * RPCs sometimes fail even when the transaction succeeded, so other errors + * are ignored and the status check carries on. + */ + return { hash: txHash }; + } +} diff --git a/queue-manager/rango-preset/src/actions/executeHyperliquidTransaction/executeHyperliquidTransaction.ts b/queue-manager/rango-preset/src/actions/executeHyperliquidTransaction/executeHyperliquidTransaction.ts index c0200d7439..4a02c82cae 100644 --- a/queue-manager/rango-preset/src/actions/executeHyperliquidTransaction/executeHyperliquidTransaction.ts +++ b/queue-manager/rango-preset/src/actions/executeHyperliquidTransaction/executeHyperliquidTransaction.ts @@ -1,9 +1,7 @@ import type { SwapQueueContext, SwapStorage } from '../../types'; import type { NextTransactionStateError } from '../common/produceNextStateForTransaction'; import type { ExecuterActions } from '@rango-dev/queue-manager-core'; -import type { EvmTransaction } from 'rango-sdk'; -import { type GenericSigner, TransactionType } from 'rango-types'; import { Err } from 'ts-results'; import { @@ -13,17 +11,20 @@ import { } from '../../helpers'; import { getCurrentAddressOf, getRelatedWallet } from '../../shared'; import { SwapActionTypes } from '../../types'; -import { checkEnvironmentBeforeExecuteTransaction } from '../common/checkEnvironmentBeforeExecuteTransaction'; import { onNextStateError, onNextStateOk, produceNextStateForTransaction, } from '../common/produceNextStateForTransaction'; import { requestBlockQueue } from '../common/utils'; +import { + checkEnvironmentBeforeExecuteEvmTransaction, + signEvmTypedData, +} from '../executeEvmTransaction'; import { ensureHyperliquidTransactionIsValid, - getEthersV6CompatibleTypedDataFromMessage, + getTypedDataFromMessage, initiateWithdrawalRequest, splitSignature, } from './utils'; @@ -31,14 +32,15 @@ import { export async function executeHyperliquidTransaction( actions: ExecuterActions ): Promise { - const checkResult = await checkEnvironmentBeforeExecuteTransaction(actions); + const checkResult = await checkEnvironmentBeforeExecuteEvmTransaction( + actions + ); if (checkResult.err) { requestBlockQueue(actions, checkResult.val); return; } const { failed, getStorage, context, schedule, next } = actions; - const { getSigners } = context; const swap = getStorage().swapDetails; const currentStep = getCurrentStep(swap)!; @@ -89,22 +91,29 @@ export async function executeHyperliquidTransaction( const sourceWallet = getRelatedWallet(swap, currentStep); const walletAddress = getCurrentAddressOf(swap, currentStep); - let signer: GenericSigner; - try { - const walletSigners = await getSigners(sourceWallet.walletType); - signer = walletSigners.getSigner(TransactionType.EVM); // We need EVM signer for Hyperliquid transactions - } catch (error) { - handleRejectedSign(actions)(error); - onFinish(); + // Hyperliquid transactions are EIP-712 messages signed by the EVM wallet. + const namespace = context.hubProvider(sourceWallet.walletType).get('evm'); + if (!namespace) { + handleErr( + new Err({ + nextStatus: 'failed', + nextStepStatus: 'failed', + message: + 'Unexpected Error: The EVM namespace is not available on your wallet.', + details: undefined, + errorCode: 'CLIENT_UNEXPECTED_BEHAVIOUR', + }) + ); return; } - if (!signer?.signTypedData) { + if (!('signTypedData' in namespace)) { handleErr( new Err({ nextStatus: 'failed', nextStepStatus: 'failed', - message: 'Unexpected Error: Signer does not support signTypedData.', + message: + 'Unexpected Error: Your wallet does not support signTypedData.', details: undefined, errorCode: 'CLIENT_UNEXPECTED_BEHAVIOUR', }) @@ -112,9 +121,7 @@ export async function executeHyperliquidTransaction( return; } - const typedData = getEthersV6CompatibleTypedDataFromMessage( - hyperliquidTransaction.message - ); + const typedData = getTypedDataFromMessage(hyperliquidTransaction.message); if (typedData.err) { handleErr(typedData); return; @@ -122,11 +129,7 @@ export async function executeHyperliquidTransaction( let signature: `0x${string}`; try { - signature = (await signer.signTypedData( - typedData.val, - walletAddress, - hyperliquidTransaction.action.signatureChainId - )) as `0x${string}`; + signature = await signEvmTypedData(namespace, typedData.val, walletAddress); } catch (error) { handleRejectedSign(actions)(error); onFinish(); diff --git a/queue-manager/rango-preset/src/actions/executeHyperliquidTransaction/types.ts b/queue-manager/rango-preset/src/actions/executeHyperliquidTransaction/types.ts deleted file mode 100644 index 5189fa67bb..0000000000 --- a/queue-manager/rango-preset/src/actions/executeHyperliquidTransaction/types.ts +++ /dev/null @@ -1,5 +0,0 @@ -export type EthersV6CompatibleTypedData = { - domain: unknown; - types: Record; - value: Record; -}; diff --git a/queue-manager/rango-preset/src/actions/executeHyperliquidTransaction/utils.ts b/queue-manager/rango-preset/src/actions/executeHyperliquidTransaction/utils.ts index 4207058482..f537793557 100644 --- a/queue-manager/rango-preset/src/actions/executeHyperliquidTransaction/utils.ts +++ b/queue-manager/rango-preset/src/actions/executeHyperliquidTransaction/utils.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/no-magic-numbers */ -import type { EthersV6CompatibleTypedData } from './types'; import type { NextTransactionStateError } from '../common/produceNextStateForTransaction'; +import type { TypedDataDefinition } from '@hub3js/evm'; import type { HyperliquidTransaction, Transaction } from 'rango-sdk'; import type { Result } from 'ts-results'; @@ -56,19 +56,20 @@ export function ensureHyperliquidTransactionIsValid( return Ok(tx); } -export function getEthersV6CompatibleTypedDataFromMessage( +export function getTypedDataFromMessage( message: string -): Result { +): Result { try { const typedData = JSON.parse(message); - const ethersV6CompatibleTypedData = { + // `types` holds only the primary type: `EIP712Domain` is derived from `domain`. + return Ok({ domain: typedData.domain, types: { [typedData.primaryType]: typedData.types[typedData.primaryType], }, - value: typedData.message, - }; - return Ok(ethersV6CompatibleTypedData); + primaryType: typedData.primaryType, + message: typedData.message, + }); } catch { return new Err({ nextStatus: 'failed', diff --git a/queue-manager/rango-preset/src/actions/executeTransaction/executeTransaction.ts b/queue-manager/rango-preset/src/actions/executeTransaction/executeTransaction.ts index 37a0d96e54..cb5e18a17a 100644 --- a/queue-manager/rango-preset/src/actions/executeTransaction/executeTransaction.ts +++ b/queue-manager/rango-preset/src/actions/executeTransaction/executeTransaction.ts @@ -6,6 +6,8 @@ import type { import type { ExecuterActions } from '@rango-dev/queue-manager-core'; import type { SignerFactory } from 'rango-types'; +import { TransactionType } from 'rango-types'; + import { getCurrentStep, getCurrentStepTx, @@ -22,21 +24,28 @@ import { produceNextStateForTransaction, } from '../common/produceNextStateForTransaction'; import { requestBlockQueue } from '../common/utils'; +import { executeEvmTransaction } from '../executeEvmTransaction'; /** - * - * Excecute a created transaction. - * - * This function implemented the parallel mode by `claim` mechanism which means - * All the queues the meet certain situation (like multiple evm transaction) will go through - * a `claim` mechanims that decides which queue should be run and it blocks other ones. - * - * A queue will be go to sign process, if the wallet and network is matched. + * Executes a created transaction through the wallet's signer, for the chains + * that don't have their own execute action. A queue goes to signing once the + * required wallet is connected. */ export async function executeTransaction( actions: ExecuterActions ): Promise { - const checkResult = await checkEnvironmentBeforeExecuteTransaction(actions); + const currentStepTx = getCurrentStepTx( + getCurrentStep(actions.getStorage().swapDetails)! + ); + /* + * EVM transactions have their own action. A swap stored by an older version + * can still resume here with one, so it's handed over. + */ + if (currentStepTx?.type === TransactionType.EVM) { + return executeEvmTransaction(actions); + } + + const checkResult = checkEnvironmentBeforeExecuteTransaction(actions); if (checkResult.err) { requestBlockQueue(actions, checkResult.val); return; diff --git a/queue-manager/rango-preset/src/queueDef.ts b/queue-manager/rango-preset/src/queueDef.ts index 77a4126f66..bc9cc01926 100644 --- a/queue-manager/rango-preset/src/queueDef.ts +++ b/queue-manager/rango-preset/src/queueDef.ts @@ -13,6 +13,7 @@ import { checkStellarTrustline } from './actions/checkStellarTrustline'; import { checkXrplTrustline } from './actions/checkXrplTrustline'; import { checkXrplTrustLineTransactionStatus } from './actions/checkXrplTrustlineTransactionStatus'; import { createTransaction } from './actions/createTransaction'; +import { executeEvmTransaction } from './actions/executeEvmTransaction'; import { executeHyperliquidTransaction } from './actions/executeHyperliquidTransaction'; import { executeStellarTransaction } from './actions/executeStellarTransaction'; import { executeTransaction } from './actions/executeTransaction'; @@ -53,6 +54,7 @@ export const swapQueueDef: SwapQueueDef = { [SwapActionTypes.CHECK_TRON_APPROVE_TRANSACTION_STATUS]: async (actions) => checkApproveTransactionStatus(actions, tronApproveAdapter), [SwapActionTypes.EXECUTE_TRANSACTION]: executeTransaction, + [SwapActionTypes.EXECUTE_EVM_TRANSACTION]: executeEvmTransaction, [SwapActionTypes.EXECUTE_XRPL_TRANSACTION]: executeXrplTransaction, [SwapActionTypes.EXECUTE_STELLAR_TRANSACTION]: executeStellarTransaction, [SwapActionTypes.EXECUTE_HYPERLIQUID_TRANSACTION]: diff --git a/queue-manager/rango-preset/src/types.ts b/queue-manager/rango-preset/src/types.ts index dcbb1799cf..fc147b79e9 100644 --- a/queue-manager/rango-preset/src/types.ts +++ b/queue-manager/rango-preset/src/types.ts @@ -61,6 +61,7 @@ export enum SwapActionTypes { CHECK_TRON_APPROVE_TRANSACTION_STATUS = 'CHECK_TRON_APPROVE_TRANSACTION_STATUS', EXECUTE_TRANSACTION = 'EXECUTE_TRANSACTION', + EXECUTE_EVM_TRANSACTION = 'EXECUTE_EVM_TRANSACTION', EXECUTE_XRPL_TRANSACTION = 'EXECUTE_XRPL_TRANSACTION', EXECUTE_STELLAR_TRANSACTION = 'EXECUTE_STELLAR_TRANSACTION', EXECUTE_HYPERLIQUID_TRANSACTION = 'EXECUTE_HYPERLIQUID_TRANSACTION', diff --git a/wallets/provider-all/package.json b/wallets/provider-all/package.json index 321840a14d..c34b2f86c7 100644 --- a/wallets/provider-all/package.json +++ b/wallets/provider-all/package.json @@ -61,8 +61,8 @@ "devDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/starknet": "^0.6.0", "@hub3js/std": "^0.6.0", @@ -75,8 +75,8 @@ "peerDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/starknet": "^0.6.0", "@hub3js/std": "^0.6.0", diff --git a/wallets/provider-all/src/index.ts b/wallets/provider-all/src/index.ts index 2310793ce3..ce28d3d8d9 100644 --- a/wallets/provider-all/src/index.ts +++ b/wallets/provider-all/src/index.ts @@ -1,4 +1,5 @@ import type { Provider } from '@hub3js/core'; +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; import { buildProvider as binance } from '@rango-dev/provider-binance'; import { buildProvider as bitget } from '@rango-dev/provider-bitget'; @@ -37,10 +38,14 @@ import { buildProvider as walletconnect2 } from '@rango-dev/provider-walletconne import { buildProvider as xverse } from '@rango-dev/provider-xverse'; export { WalletTypes } from './walletTypes.js'; +export { toNamespacesRPCUrls } from './rpcUrls.js'; +export type { RpcUrlsConfig } from './rpcUrls.js'; // Providers register different namespaces, so the list is typed loosely instead of `Provider`. // eslint-disable-next-line @typescript-eslint/no-explicit-any -export const allProviders = (): (() => Provider)[] => { +type BuildProvider = (rpcURLs?: NamespacesRPCUrls) => Provider; + +export const allProviders = (): BuildProvider[] => { return [ safe, defaultInjected, diff --git a/wallets/provider-all/src/rpcUrls.test.ts b/wallets/provider-all/src/rpcUrls.test.ts new file mode 100644 index 0000000000..f41faa4c61 --- /dev/null +++ b/wallets/provider-all/src/rpcUrls.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, test } from 'vitest'; + +import { toNamespacesRPCUrls } from './rpcUrls.js'; + +const BSC_CHAIN_ID = 56; +const POLYGON_CHAIN_ID = 137; + +describe('toNamespacesRPCUrls', () => { + test('gives every EVM chain its own urls and viem chain', () => { + const { evm } = toNamespacesRPCUrls({ + evm: { + 1: ['https://eth.example'], + [BSC_CHAIN_ID]: ['https://a.bsc', 'https://b.bsc'], + }, + }); + + expect(evm).toHaveLength(2); + expect(evm?.map(({ chain, rpcUrls }) => [chain.id, rpcUrls])).toEqual([ + [1, ['https://eth.example']], + [BSC_CHAIN_ID, ['https://a.bsc', 'https://b.bsc']], + ]); + expect(evm?.[1]?.chain.rpcUrls.default.http).toEqual([ + 'https://a.bsc', + 'https://b.bsc', + ]); + }); + + test('leaves out chains without urls and invalid chain ids', () => { + const { evm } = toNamespacesRPCUrls({ + evm: { 1: [], 10: [''], [POLYGON_CHAIN_ID]: ['https://polygon.example'] }, + }); + + expect(evm?.map(({ chain }) => chain.id)).toEqual([POLYGON_CHAIN_ID]); + expect( + toNamespacesRPCUrls({ + evm: { 0: ['https://x'] }, + }) + ).toEqual({}); + }); + + test('has no urls of its own', () => { + expect(toNamespacesRPCUrls()).toEqual({}); + expect(toNamespacesRPCUrls({})).toEqual({}); + }); +}); diff --git a/wallets/provider-all/src/rpcUrls.ts b/wallets/provider-all/src/rpcUrls.ts new file mode 100644 index 0000000000..3e976bd71d --- /dev/null +++ b/wallets/provider-all/src/rpcUrls.ts @@ -0,0 +1,41 @@ +import type { EvmRpcUrls } from '@hub3js/evm'; +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + +/** + * RPC urls as an app configures them. An EVM url serves one chain, so EVM urls + * are keyed by chain id, e.g. `{ evm: { 1: ['https://…'], 56: ['https://…'] } }`. + */ +export type RpcUrlsConfig = { + evm?: Record; +}; + +/** + * Turns configured RPC urls into the shape providers are built with. Each EVM + * chain gets a minimal viem chain: its id and urls are what reads need. Chains + * without urls are left out, so reads on them reject instead of going to a url + * we don't control. + */ +export function toNamespacesRPCUrls(config?: RpcUrlsConfig): NamespacesRPCUrls { + const evm: EvmRpcUrls = []; + + for (const [key, urls] of Object.entries(config?.evm ?? {})) { + const id = Number(key); + const rpcUrls = urls.filter(Boolean); + + if (!Number.isInteger(id) || id <= 0 || rpcUrls.length === 0) { + continue; + } + + evm.push({ + chain: { + id, + name: `EVM chain ${id}`, + nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, + rpcUrls: { default: { http: rpcUrls } }, + }, + rpcUrls, + }); + } + + return evm.length ? { evm } : {}; +} diff --git a/wallets/provider-binance/package.json b/wallets/provider-binance/package.json index ae449e4363..a6f4ecaa50 100644 --- a/wallets/provider-binance/package.json +++ b/wallets/provider-binance/package.json @@ -22,19 +22,18 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "rango-types": "^0.6.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-binance/src/constants.ts b/wallets/provider-binance/src/constants.ts index 3c840564f6..dbba3ad3cb 100644 --- a/wallets/provider-binance/src/constants.ts +++ b/wallets/provider-binance/src/constants.ts @@ -21,9 +21,6 @@ import { } from '@hub3js/evm'; import { getChainIdFromCaip2ChainId } from '@hub3js/std/utils'; -import getSigners from './signer.js'; -import { getInstanceOrThrow } from './utils.js'; - export const WALLET_ID = 'binance'; export const EVM_SUPPORTED_CHAINS = [ CAIP_ETHEREUM_CHAIN_ID, @@ -73,9 +70,5 @@ export const metadata: ProviderMetadata = { ], }, }, - { - name: 'signers', - value: { getSigners: async () => getSigners(getInstanceOrThrow()) }, - }, ], }; diff --git a/wallets/provider-binance/src/namespaces/evm.ts b/wallets/provider-binance/src/namespaces/evm.ts index 474c87e9d2..1ada9c56b0 100644 --- a/wallets/provider-binance/src/namespaces/evm.ts +++ b/wallets/provider-binance/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, utils } from '@hub3js/evm'; +import { actions, builders, utils, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -52,18 +52,13 @@ const getAllowance = builders .action(actions.getAllowance(evmBinance)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmBinance)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmBinance)) .action(connect) .action(disconnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-binance/src/provider.ts b/wallets/provider-binance/src/provider.ts index 37ff60ac28..d6d8861c6a 100644 --- a/wallets/provider-binance/src/provider.ts +++ b/wallets/provider-binance/src/provider.ts @@ -1,11 +1,14 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; import { evm } from './namespaces/evm.js'; import { binance as binanceInstance } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); if (binanceInstance()) { @@ -16,5 +19,6 @@ const buildProvider = () => .config('metadata', metadata) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-binance/src/signer.ts b/wallets/provider-binance/src/signer.ts deleted file mode 100644 index 6f05aa1495..0000000000 --- a/wallets/provider-binance/src/signer.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { Provider } from './types.js'; -import type { SignerFactory } from 'rango-types'; - -import { EVM_NAMESPACE } from '@hub3js/namespaces'; -import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; - -export default async function getSigners( - provider: Provider -): Promise { - const evmProvider = provider.get(EVM_NAMESPACE); - const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); - if (!!evmProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(evmProvider)); - } - return signers; -} diff --git a/wallets/provider-binance/src/utils.ts b/wallets/provider-binance/src/utils.ts index 42354495c9..c6a05ff78b 100644 --- a/wallets/provider-binance/src/utils.ts +++ b/wallets/provider-binance/src/utils.ts @@ -22,18 +22,6 @@ export function binance(): Provider | null { return instances; } -export function getInstanceOrThrow(): Provider { - const instances = binance(); - - if (!instances) { - throw new Error( - 'Binance Wallet is not injected. Please check your wallet.' - ); - } - - return instances; -} - export function evmBinance(): EvmProviderApi { const instances = binance(); diff --git a/wallets/provider-bitget/package.json b/wallets/provider-bitget/package.json index d9d77d7dd7..a4d45d8deb 100644 --- a/wallets/provider-bitget/package.json +++ b/wallets/provider-bitget/package.json @@ -23,7 +23,6 @@ }, "dependencies": { "@rango-dev/internal-blockchains": "^0.3.1-next.1", - "@rango-dev/signer-evm": "^0.47.0", "@rango-dev/signer-tron": "^0.44.1-next.0", "bitcoinjs-lib": "^6.1.7", "rango-types": "^0.6.0" @@ -31,16 +30,16 @@ "devDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0", "@hub3js/tron": "^0.3.0" }, "peerDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0", "@hub3js/tron": "^0.3.0" }, diff --git a/wallets/provider-bitget/src/namespaces/evm.ts b/wallets/provider-bitget/src/namespaces/evm.ts index f490add445..a57ea065fe 100644 --- a/wallets/provider-bitget/src/namespaces/evm.ts +++ b/wallets/provider-bitget/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, hooks } from '@hub3js/evm'; +import { actions, builders, hooks, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -43,19 +43,14 @@ const getAllowance = builders .action(actions.getAllowance(evmBitget)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmBitget)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmBitget)) .action(connect) .action(disconnect) .action(getChainId) .action(canEagerConnect) .action(canSwitchNetwork) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-bitget/src/provider.ts b/wallets/provider-bitget/src/provider.ts index 453cc14347..03d33ee6ce 100644 --- a/wallets/provider-bitget/src/provider.ts +++ b/wallets/provider-bitget/src/provider.ts @@ -1,3 +1,5 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; @@ -6,8 +8,9 @@ import { tron } from './namespaces/tron.js'; import { utxo } from './namespaces/utxo.js'; import { bitget } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -21,5 +24,6 @@ const buildProvider = () => .add('evm', evm) .add('utxo', utxo) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-bitget/src/signer.ts b/wallets/provider-bitget/src/signer.ts index 6a32e27393..a727f350e6 100644 --- a/wallets/provider-bitget/src/signer.ts +++ b/wallets/provider-bitget/src/signer.ts @@ -1,11 +1,7 @@ import type { Provider } from './types.js'; import type { SignerFactory } from 'rango-types'; -import { - EVM_NAMESPACE, - TRON_NAMESPACE, - UTXO_NAMESPACE, -} from '@hub3js/namespaces'; +import { TRON_NAMESPACE, UTXO_NAMESPACE } from '@hub3js/namespaces'; import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; import { BitgetUTXOSigner } from './signers/utxo.js'; @@ -13,16 +9,11 @@ import { BitgetUTXOSigner } from './signers/utxo.js'; export default async function getSigners( provider: Provider ): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); const tronProvider = provider.get(TRON_NAMESPACE); const utxoProvider = provider.get(UTXO_NAMESPACE); const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); const { DefaultTronSigner } = await import('@rango-dev/signer-tron'); - if (!!ethProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(ethProvider)); - } if (!!tronProvider) { signers.registerSigner(TxType.TRON, new DefaultTronSigner(tronProvider)); } diff --git a/wallets/provider-braavos/package.json b/wallets/provider-braavos/package.json index e3164b4802..5d3afffeb3 100644 --- a/wallets/provider-braavos/package.json +++ b/wallets/provider-braavos/package.json @@ -27,13 +27,13 @@ }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/starknet": "^0.6.0", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/starknet": "^0.6.0", "@hub3js/std": "^0.6.0" }, diff --git a/wallets/provider-braavos/src/provider.ts b/wallets/provider-braavos/src/provider.ts index cfc9e6b98c..5da24257da 100644 --- a/wallets/provider-braavos/src/provider.ts +++ b/wallets/provider-braavos/src/provider.ts @@ -1,10 +1,13 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; import { starknet } from './namespaces/starknet.js'; import { braavos } from './utils.js'; -const buildProvider = () => +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); diff --git a/wallets/provider-brave/package.json b/wallets/provider-brave/package.json index 7b7466a2b6..a076213130 100644 --- a/wallets/provider-brave/package.json +++ b/wallets/provider-brave/package.json @@ -22,21 +22,20 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "@rango-dev/signer-solana": "^0.51.1-next.0", "rango-types": "^0.6.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, diff --git a/wallets/provider-brave/src/namespaces/evm.ts b/wallets/provider-brave/src/namespaces/evm.ts index ce4df376fc..78c0d9baae 100644 --- a/wallets/provider-brave/src/namespaces/evm.ts +++ b/wallets/provider-brave/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, hooks } from '@hub3js/evm'; +import { actions, builders, hooks, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -43,19 +43,14 @@ const getAllowance = builders .action(actions.getAllowance(evmBrave)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmBrave)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmBrave)) .action(connect) .action(disconnect) .action(canEagerConnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-brave/src/provider.ts b/wallets/provider-brave/src/provider.ts index 8af23ea3cf..426bead7e8 100644 --- a/wallets/provider-brave/src/provider.ts +++ b/wallets/provider-brave/src/provider.ts @@ -1,3 +1,5 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; @@ -5,8 +7,9 @@ import { evm } from './namespaces/evm.js'; import { solana } from './namespaces/solana.js'; import { brave } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -19,5 +22,6 @@ const buildProvider = () => .add('solana', solana) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-brave/src/signer.ts b/wallets/provider-brave/src/signer.ts index a28099e14e..de16a31a7a 100644 --- a/wallets/provider-brave/src/signer.ts +++ b/wallets/provider-brave/src/signer.ts @@ -1,7 +1,7 @@ import type { Provider } from './types.js'; import type { SignerFactory } from 'rango-types'; -import { EVM_NAMESPACE, SOLANA_NAMESPACE } from '@hub3js/namespaces'; +import { SOLANA_NAMESPACE } from '@hub3js/namespaces'; import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; import { BraveSolanaSigner } from './signers/solana.js'; @@ -9,13 +9,8 @@ import { BraveSolanaSigner } from './signers/solana.js'; export default async function getSigners( provider: Provider ): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); const solProvider = provider.get(SOLANA_NAMESPACE); const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); - if (!!ethProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(ethProvider)); - } if (!!solProvider) { signers.registerSigner(TxType.SOLANA, new BraveSolanaSigner(solProvider)); } diff --git a/wallets/provider-coin98/package.json b/wallets/provider-coin98/package.json index 2a890a1101..0f99f6ce3f 100644 --- a/wallets/provider-coin98/package.json +++ b/wallets/provider-coin98/package.json @@ -22,7 +22,6 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "@rango-dev/signer-solana": "^0.51.1-next.0", "@solana/web3.js": "^1.91.4", "bs58": "^5.0.0", @@ -30,15 +29,15 @@ }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, diff --git a/wallets/provider-coin98/src/namespaces/evm.ts b/wallets/provider-coin98/src/namespaces/evm.ts index 018135af40..2c2dfd66e8 100644 --- a/wallets/provider-coin98/src/namespaces/evm.ts +++ b/wallets/provider-coin98/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders } from '@hub3js/evm'; +import { actions, builders, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -40,18 +40,13 @@ const getAllowance = builders .action(actions.getAllowance(evmCoin98)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmCoin98)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmCoin98)) .action(connect) .action(disconnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-coin98/src/provider.ts b/wallets/provider-coin98/src/provider.ts index 5038f3c2d8..24c8faf777 100644 --- a/wallets/provider-coin98/src/provider.ts +++ b/wallets/provider-coin98/src/provider.ts @@ -1,3 +1,5 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { COIN98_INJECTION_DELAY, metadata, WALLET_ID } from './constants.js'; @@ -5,8 +7,9 @@ import { evm } from './namespaces/evm.js'; import { solana } from './namespaces/solana.js'; import { coin98 } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -21,5 +24,6 @@ const buildProvider = () => .add('evm', evm) .add('solana', solana) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-coin98/src/signer.ts b/wallets/provider-coin98/src/signer.ts index 6747998b4e..48e938533e 100644 --- a/wallets/provider-coin98/src/signer.ts +++ b/wallets/provider-coin98/src/signer.ts @@ -1,7 +1,7 @@ import type { Provider } from './types.js'; import type { SignerFactory } from 'rango-types'; -import { EVM_NAMESPACE, SOLANA_NAMESPACE } from '@hub3js/namespaces'; +import { SOLANA_NAMESPACE } from '@hub3js/namespaces'; import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; import { Coin98SolanaSigner } from './signers/solana.js'; @@ -9,13 +9,8 @@ import { Coin98SolanaSigner } from './signers/solana.js'; export default async function getSigners( provider: Provider ): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); const solProvider = provider.get(SOLANA_NAMESPACE); const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); - if (!!ethProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(ethProvider)); - } if (!!solProvider) { signers.registerSigner(TxType.SOLANA, new Coin98SolanaSigner(solProvider)); } diff --git a/wallets/provider-coinbase/package.json b/wallets/provider-coinbase/package.json index d0352d4aa9..dbda686d9e 100644 --- a/wallets/provider-coinbase/package.json +++ b/wallets/provider-coinbase/package.json @@ -22,22 +22,21 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "@rango-dev/signer-solana": "^0.51.1-next.0", "bs58": "^5.0.0", "rango-types": "^0.6.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, diff --git a/wallets/provider-coinbase/src/namespaces/evm.ts b/wallets/provider-coinbase/src/namespaces/evm.ts index d8938b1a2b..b0b50d0d00 100644 --- a/wallets/provider-coinbase/src/namespaces/evm.ts +++ b/wallets/provider-coinbase/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { ActionBuilder, NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, utils } from '@hub3js/evm'; +import { actions, builders, utils, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { connectAndUpdateStateForMultiNetworks, @@ -78,19 +78,14 @@ const getAllowance = builders .action(actions.getAllowance(evmCoinbase)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmCoinbase)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmCoinbase)) .action(connect) .action(disconnect) .action(canEagerConnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-coinbase/src/provider.ts b/wallets/provider-coinbase/src/provider.ts index b3de61c4c7..5237a56cc2 100644 --- a/wallets/provider-coinbase/src/provider.ts +++ b/wallets/provider-coinbase/src/provider.ts @@ -1,3 +1,5 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; @@ -5,8 +7,9 @@ import { evm } from './namespaces/evm.js'; import { solana } from './namespaces/solana.js'; import { coinbase as coinbaseInstance } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -19,5 +22,6 @@ const buildProvider = () => .add('solana', solana) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-coinbase/src/signer.ts b/wallets/provider-coinbase/src/signer.ts index bbbe35c54c..d73522e975 100644 --- a/wallets/provider-coinbase/src/signer.ts +++ b/wallets/provider-coinbase/src/signer.ts @@ -1,7 +1,7 @@ import type { Provider } from './utils.js'; import type { SignerFactory } from 'rango-types'; -import { EVM_NAMESPACE, SOLANA_NAMESPACE } from '@hub3js/namespaces'; +import { SOLANA_NAMESPACE } from '@hub3js/namespaces'; import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; import { CustomSolanaSigner } from './signers/solana-signer.js'; @@ -9,13 +9,8 @@ import { CustomSolanaSigner } from './signers/solana-signer.js'; export default async function getSigners( provider: Provider ): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); const solProvider = provider.get(SOLANA_NAMESPACE); const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); - if (!!ethProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(ethProvider)); - } if (!!solProvider) { signers.registerSigner(TxType.SOLANA, new CustomSolanaSigner(solProvider)); } diff --git a/wallets/provider-default/package.json b/wallets/provider-default/package.json index d99290faa5..4f95d769ec 100644 --- a/wallets/provider-default/package.json +++ b/wallets/provider-default/package.json @@ -22,19 +22,18 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "rango-types": "^0.6.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-default/src/constants.ts b/wallets/provider-default/src/constants.ts index e9dc0d8cc2..f0a5e4a55a 100644 --- a/wallets/provider-default/src/constants.ts +++ b/wallets/provider-default/src/constants.ts @@ -2,9 +2,6 @@ import type { ProviderMetadata } from '@hub3js/core'; import { isEvmNamespace } from '@hub3js/evm'; -import getSigners from './signer.js'; -import { getInstanceOrThrow } from './utils.js'; - export const WALLET_ID = 'default'; export const INJECTION_DELAY = 1000; @@ -33,9 +30,5 @@ export const metadata: ProviderMetadata = { ], }, }, - { - name: 'signers', - value: { getSigners: async () => getSigners(getInstanceOrThrow()) }, - }, ], }; diff --git a/wallets/provider-default/src/namespaces/evm.ts b/wallets/provider-default/src/namespaces/evm.ts index b40907b3ea..81219a81f1 100644 --- a/wallets/provider-default/src/namespaces/evm.ts +++ b/wallets/provider-default/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, hooks } from '@hub3js/evm'; +import { actions, builders, hooks, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -44,19 +44,14 @@ const getAllowance = builders .action(actions.getAllowance(evmDefault)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmDefault)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmDefault)) .action(connect) .action(disconnect) .action(canEagerConnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-default/src/provider.ts b/wallets/provider-default/src/provider.ts index 949b51114a..9345f2d41a 100644 --- a/wallets/provider-default/src/provider.ts +++ b/wallets/provider-default/src/provider.ts @@ -1,11 +1,14 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { INJECTION_DELAY, metadata, WALLET_ID } from './constants.js'; import { evm } from './namespaces/evm.js'; import { defaultInjected } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -19,5 +22,6 @@ const buildProvider = () => .config('metadata', metadata) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-default/src/signer.ts b/wallets/provider-default/src/signer.ts deleted file mode 100644 index 6f05aa1495..0000000000 --- a/wallets/provider-default/src/signer.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { Provider } from './types.js'; -import type { SignerFactory } from 'rango-types'; - -import { EVM_NAMESPACE } from '@hub3js/namespaces'; -import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; - -export default async function getSigners( - provider: Provider -): Promise { - const evmProvider = provider.get(EVM_NAMESPACE); - const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); - if (!!evmProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(evmProvider)); - } - return signers; -} diff --git a/wallets/provider-default/src/utils.ts b/wallets/provider-default/src/utils.ts index 5f136ca444..59012f3b92 100644 --- a/wallets/provider-default/src/utils.ts +++ b/wallets/provider-default/src/utils.ts @@ -21,16 +21,6 @@ export function defaultInjected(): Provider | null { return instances; } -export function getInstanceOrThrow(): Provider { - const instances = defaultInjected(); - - if (!instances) { - throw new Error('ethereum is not injected. Please check your wallet.'); - } - - return instances; -} - export function evmDefault(): EvmProviderApi { const instances = defaultInjected(); diff --git a/wallets/provider-enkrypt/package.json b/wallets/provider-enkrypt/package.json index d1d878b70b..2651fc11af 100644 --- a/wallets/provider-enkrypt/package.json +++ b/wallets/provider-enkrypt/package.json @@ -22,19 +22,18 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "rango-types": "^0.6.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-enkrypt/src/constants.ts b/wallets/provider-enkrypt/src/constants.ts index fd0059d02c..77f913e04c 100644 --- a/wallets/provider-enkrypt/src/constants.ts +++ b/wallets/provider-enkrypt/src/constants.ts @@ -2,9 +2,6 @@ import type { ProviderMetadata } from '@hub3js/core'; import { isEvmNamespace } from '@hub3js/evm'; -import getSigners from './signer.js'; -import { getInstanceOrThrow } from './utils.js'; - export const WALLET_ID = 'enkrypt'; // Enkrypt rejects with a bare string, not an error object. export const ENKRYPT_REJECTION = @@ -37,9 +34,5 @@ export const metadata: ProviderMetadata = { ], }, }, - { - name: 'signers', - value: { getSigners: async () => getSigners(getInstanceOrThrow()) }, - }, ], }; diff --git a/wallets/provider-enkrypt/src/namespaces/evm.ts b/wallets/provider-enkrypt/src/namespaces/evm.ts index ab1fb4a929..648a73b560 100644 --- a/wallets/provider-enkrypt/src/namespaces/evm.ts +++ b/wallets/provider-enkrypt/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, hooks } from '@hub3js/evm'; +import { actions, builders, hooks, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -45,19 +45,14 @@ const getAllowance = builders .action(actions.getAllowance(evmEnkrypt)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmEnkrypt)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmEnkrypt)) .action(connect) .action(disconnect) .action(canEagerConnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-enkrypt/src/provider.ts b/wallets/provider-enkrypt/src/provider.ts index 7ff1b0b9c3..02a91d1fc7 100644 --- a/wallets/provider-enkrypt/src/provider.ts +++ b/wallets/provider-enkrypt/src/provider.ts @@ -1,11 +1,14 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; import { evm } from './namespaces/evm.js'; import { enkrypt } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -17,5 +20,6 @@ const buildProvider = () => .config('metadata', metadata) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-enkrypt/src/signer.ts b/wallets/provider-enkrypt/src/signer.ts deleted file mode 100644 index 767e5ff5f0..0000000000 --- a/wallets/provider-enkrypt/src/signer.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { Provider } from './types.js'; -import type { SignerFactory } from 'rango-types'; - -import { EVM_NAMESPACE } from '@hub3js/namespaces'; -import { DefaultSignerFactory, TransactionType } from 'rango-types'; - -export default async function getSigners( - provider: Provider -): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); - const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); - if (!!ethProvider) { - signers.registerSigner( - TransactionType.EVM, - new DefaultEvmSigner(ethProvider) - ); - } - return signers; -} diff --git a/wallets/provider-enkrypt/src/utils.ts b/wallets/provider-enkrypt/src/utils.ts index d7903addb7..3e3e877556 100644 --- a/wallets/provider-enkrypt/src/utils.ts +++ b/wallets/provider-enkrypt/src/utils.ts @@ -14,18 +14,6 @@ export function enkrypt(): Provider | null { return instances; } -export function getInstanceOrThrow(): Provider { - const instances = enkrypt(); - - if (!instances) { - throw new Error( - 'Enkrypt Wallet is not injected. Please check your wallet.' - ); - } - - return instances; -} - export function evmEnkrypt(): EnkryptEvmProvider { const instances = enkrypt(); diff --git a/wallets/provider-exodus/package.json b/wallets/provider-exodus/package.json index b819c0c86d..020bb64dbf 100644 --- a/wallets/provider-exodus/package.json +++ b/wallets/provider-exodus/package.json @@ -22,22 +22,21 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "@rango-dev/signer-solana": "^0.51.1-next.0", "bs58": "^5.0.0", "rango-types": "^0.6.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, diff --git a/wallets/provider-exodus/src/namespaces/evm.ts b/wallets/provider-exodus/src/namespaces/evm.ts index 7261f579c9..f59e382b7b 100644 --- a/wallets/provider-exodus/src/namespaces/evm.ts +++ b/wallets/provider-exodus/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders } from '@hub3js/evm'; +import { actions, builders, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -36,19 +36,14 @@ const getAllowance = builders .action(actions.getAllowance(evmExodus)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmExodus)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmExodus)) .action(connect) .action(disconnect) .action(canEagerConnect) .action(getChainId) .action(canSwitchNetwork) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-exodus/src/provider.ts b/wallets/provider-exodus/src/provider.ts index 63e433704f..bfd4219b1b 100644 --- a/wallets/provider-exodus/src/provider.ts +++ b/wallets/provider-exodus/src/provider.ts @@ -1,3 +1,5 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; @@ -6,8 +8,9 @@ import { solana } from './namespaces/solana.js'; import { exodus as exodusInstance } from './utils.js'; const WALLET_INJECTION_DELAY_MS = 1000; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init((context) => setTimeout(function () { const [, setState] = context.state(); @@ -22,5 +25,6 @@ const buildProvider = () => .add('solana', solana) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-exodus/src/signer.ts b/wallets/provider-exodus/src/signer.ts index ec19abe758..1bd591f171 100644 --- a/wallets/provider-exodus/src/signer.ts +++ b/wallets/provider-exodus/src/signer.ts @@ -1,7 +1,7 @@ import type { Provider } from './types.js'; import type { SignerFactory } from 'rango-types'; -import { EVM_NAMESPACE, SOLANA_NAMESPACE } from '@hub3js/namespaces'; +import { SOLANA_NAMESPACE } from '@hub3js/namespaces'; import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; import { ExodusSolanaSigner } from './signers/solana.js'; @@ -9,13 +9,8 @@ import { ExodusSolanaSigner } from './signers/solana.js'; export default async function getSigners( provider: Provider ): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); const solProvider = provider.get(SOLANA_NAMESPACE); const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); - if (!!ethProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(ethProvider)); - } if (!!solProvider) { signers.registerSigner(TxType.SOLANA, new ExodusSolanaSigner(solProvider)); } diff --git a/wallets/provider-freighter/package.json b/wallets/provider-freighter/package.json index d17a207139..9e77e99d83 100644 --- a/wallets/provider-freighter/package.json +++ b/wallets/provider-freighter/package.json @@ -28,11 +28,13 @@ }, "devDependencies": { "@hub3js/core": "^0.64.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0", "@hub3js/stellar": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0", "@hub3js/stellar": "^0.6.0" }, diff --git a/wallets/provider-freighter/src/provider.ts b/wallets/provider-freighter/src/provider.ts index b03fb34f97..d646481ff3 100644 --- a/wallets/provider-freighter/src/provider.ts +++ b/wallets/provider-freighter/src/provider.ts @@ -1,10 +1,13 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; import { namespace as stellar } from './namespaces/stellar/namespace.js'; import { checkInstallation } from './utils.js'; -const buildProvider = () => +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); diff --git a/wallets/provider-gemwallet/package.json b/wallets/provider-gemwallet/package.json index 711f90bbeb..4db0c18926 100644 --- a/wallets/provider-gemwallet/package.json +++ b/wallets/provider-gemwallet/package.json @@ -28,11 +28,13 @@ }, "devDependencies": { "@hub3js/core": "^0.64.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0", "@hub3js/xrpl": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0", "@hub3js/xrpl": "^0.6.0" }, diff --git a/wallets/provider-gemwallet/src/provider.ts b/wallets/provider-gemwallet/src/provider.ts index d615d2b743..65c94bac0d 100644 --- a/wallets/provider-gemwallet/src/provider.ts +++ b/wallets/provider-gemwallet/src/provider.ts @@ -1,10 +1,13 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { info, WALLET_ID } from './constants.js'; import { namespace as xrpl } from './namespaces/xrpl/mod.js'; import { checkInstallationOnLoad } from './utils.js'; -const buildProvider = () => +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); diff --git a/wallets/provider-ledger-wallet/package.json b/wallets/provider-ledger-wallet/package.json index dd0e8b4424..a79ce20143 100644 --- a/wallets/provider-ledger-wallet/package.json +++ b/wallets/provider-ledger-wallet/package.json @@ -22,18 +22,18 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@ledgerhq/ledger-wallet-provider": "^1.4.2", - "@rango-dev/signer-evm": "^0.47.1", - "rango-types": "^0.6.0" + "@ledgerhq/ledger-wallet-provider": "^1.4.2" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-ledger-wallet/src/constants.ts b/wallets/provider-ledger-wallet/src/constants.ts index 1e7ab9575e..6452034fd5 100644 --- a/wallets/provider-ledger-wallet/src/constants.ts +++ b/wallets/provider-ledger-wallet/src/constants.ts @@ -15,8 +15,6 @@ import { } from '@hub3js/evm'; import { getChainIdFromCaip2ChainId } from '@hub3js/std/utils'; -import getSigners from './signer.js'; - export const WALLET_ID = 'ledger-wallet'; /* @@ -64,10 +62,6 @@ export const metadata: ProviderMetadata = { ], }, }, - { - name: 'signers', - value: { getSigners: async () => getSigners() }, - }, { name: 'details', value: { diff --git a/wallets/provider-ledger-wallet/src/namespaces/evm.ts b/wallets/provider-ledger-wallet/src/namespaces/evm.ts index 9f9f40c3b9..1c9ebb673b 100644 --- a/wallets/provider-ledger-wallet/src/namespaces/evm.ts +++ b/wallets/provider-ledger-wallet/src/namespaces/evm.ts @@ -1,8 +1,14 @@ import type { Context } from '@hub3js/core'; -import type { Chain, ChainId, EvmActions } from '@hub3js/evm'; +import type { Chain, ChainId, EvmActions, EvmRpcUrls } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, utils } from '@hub3js/evm'; +import { + actions, + builders, + utils, + viemPublicAdapter, + viemWalletAdapter, +} from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -101,19 +107,56 @@ const getAllowance = builders .action(actions.getAllowance(getProvider)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(getProvider)) - .build(); - -const evm = new NamespaceBuilder('EVM', WALLET_ID) - .action(connect) - .action(disconnect) - .action(canEagerConnect) - .action(canSwitchNetwork) - .action(getChainId) - .action(getAllowance) - .action(getTransactionReceipt) - .build(); - -export { evm }; +/* + * viem's public actions that only use the reads the Ledger provider forwards + * to its node: `eth_blockNumber`, `eth_getBalance`, `eth_getCode`, + * `eth_estimateGas` and `eth_call`. It rejects every other read, e.g. + * `eth_getTransactionReceipt`, with 4200 (unsupported method). + * + * Ledger's list (`BROADCASTED_TO_NODE_RPC_METHODS`), as of the latest release + * (`@ledgerhq/ledger-wallet-provider` 2.0.2): + * https://github.com/LedgerHQ/ledger-button-public/blob/cc33f953aa/packages/ledger-wallet-provider-evm/src/utils/supportedRpcMethods.ts + * `eth_getTransactionReceipt` is added on their develop branch, so the receipt + * actions can move here once it's released. + */ +const LEDGER_PUBLIC_ACTIONS: ReadonlyArray = [ + 'getBalance', + 'getBlockNumber', + 'getCode', + 'getBytecode', + 'estimateGas', + 'estimateContractGas', + 'call', + 'readContract', + 'simulateContract', +]; + +const buildEvm = (rpcUrls?: EvmRpcUrls) => { + const publicActions = viemPublicAdapter(rpcUrls); + const publicActionNames = new Set(publicActions.map(([name]) => name)); + + return ( + new NamespaceBuilder('EVM', WALLET_ID) + // Every public action from our RPC, for the reads Ledger doesn't serve. + .action(publicActions) + /* + * Wallet actions, and the reads Ledger serves, come from the wallet (on + * the chain it's on). Its other reads are left to the actions above. + */ + .action( + viemWalletAdapter(getProvider).filter( + ([name]) => + !publicActionNames.has(name) || LEDGER_PUBLIC_ACTIONS.includes(name) + ) + ) + .action(connect) + .action(disconnect) + .action(canEagerConnect) + .action(canSwitchNetwork) + .action(getChainId) + .action(getAllowance) + .build() + ); +}; + +export { buildEvm }; diff --git a/wallets/provider-ledger-wallet/src/provider.ts b/wallets/provider-ledger-wallet/src/provider.ts index 6a1bc95534..5b68f1ffb8 100644 --- a/wallets/provider-ledger-wallet/src/provider.ts +++ b/wallets/provider-ledger-wallet/src/provider.ts @@ -1,17 +1,18 @@ import type { Environments } from './types.js'; import type { ProviderAPI } from '@hub3js/evm'; +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; import type { EIP6963ProviderDetail } from '@ledgerhq/ledger-wallet-provider'; import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; import { setProvider } from './ledgerProvider.js'; -import { evm } from './namespaces/evm.js'; +import { buildEvm } from './namespaces/evm.js'; const LEDGER_PROVIDER_NAME = 'Ledger Wallet'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +const buildProvider = (rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context, environments: Environments) { const [, setState] = context.state(); @@ -92,7 +93,8 @@ const buildProvider = () => }; }) .config('metadata', metadata) - .add('evm', evm) + .add('evm', buildEvm(rpcURLs?.evm)) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-ledger-wallet/src/signer.ts b/wallets/provider-ledger-wallet/src/signer.ts deleted file mode 100644 index 6192079114..0000000000 --- a/wallets/provider-ledger-wallet/src/signer.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { SignerFactory } from 'rango-types'; - -import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; - -export default async function getSigners(): Promise { - const signers = new DefaultSignerFactory(); - const { CustomEvmSigner } = await import('./signers/evm.js'); - signers.registerSigner(TxType.EVM, new CustomEvmSigner()); - - return signers; -} diff --git a/wallets/provider-ledger-wallet/src/signers/evm.ts b/wallets/provider-ledger-wallet/src/signers/evm.ts deleted file mode 100644 index f9790dc4a8..0000000000 --- a/wallets/provider-ledger-wallet/src/signers/evm.ts +++ /dev/null @@ -1,143 +0,0 @@ -import type { TypedData } from '@rango-dev/signer-evm'; -import type { GenericSigner } from 'rango-types'; -import type { EvmTransaction } from 'rango-types/mainApi'; - -import { cleanEvmError, DefaultEvmSigner } from '@rango-dev/signer-evm'; - -import { getProvider } from '../ledgerProvider.js'; - -const HEXADECIMAL_BASE = 16; - -/* - * Ledger's eth_sendTransaction params (see EthSendTransactionParams): - * - use `gas`, not ethers' `gasLimit`. TransactionHelper only reads - * `transaction.gas` → ethers gasLimit; a `gasLimit` key is ignored. - * - quantities should be hex. Ledger parses nonce with parseInt(nonce, 16), - * so a decimal nonce would be wrong. Hex also keeps fees in JSON-RPC form. - * - * If gas + maxFeePerGas + maxPriorityFeePerGas are not all set, Ledger - * re-estimates and overwrites those three fields (EIP-1559). So for swaps we - * must pass the full triad when Rango provides EIP-1559 fees; otherwise Rango's - * gas limit is dropped. - * https://developers.ledger.com/docs/ledger-wallet-provider/api-reference - */ -type LedgerTransactionParams = { - data: string; - from?: string; - to?: string; - value?: string; - nonce?: string; - gas?: string; - gasPrice?: string; - maxFeePerGas?: string; - maxPriorityFeePerGas?: string; -}; - -/** Hex-encode a Rango quantity (`0x…` or decimal string). BigInt accepts both. */ -const toHexQuantity = (value: string): string => - '0x' + BigInt(value).toString(HEXADECIMAL_BASE); - -/* - * Map Rango's EvmTransaction to Ledger's JSON-RPC shape: gasLimit → gas, - * quantities hex-encoded, EIP-1559 preferred over legacy gasPrice. - */ -const buildLedgerTx = (tx: EvmTransaction): LedgerTransactionParams => { - /* - * Always send data and value: - * - data: `0x` instead of undefined (same as DefaultEvmSigner.buildTx). - * - value: Ledger's internal Transaction type requires value; omit it on - * zero-value txs (approvals) and fee estimation / serialization can - * break. Default to 0x0. - */ - const params: LedgerTransactionParams = { - data: tx.data || '0x', - value: tx.value ? toHexQuantity(tx.value) : '0x0', - }; - if (tx.from) { - params.from = tx.from; - } - if (tx.to) { - params.to = tx.to; - } - if (tx.nonce) { - params.nonce = toHexQuantity(tx.nonce); - } - if (tx.gasLimit) { - params.gas = toHexQuantity(tx.gasLimit); - } - if (tx.maxFeePerGas && tx.maxPriorityFeePerGas) { - params.maxFeePerGas = toHexQuantity(tx.maxFeePerGas); - params.maxPriorityFeePerGas = toHexQuantity(tx.maxPriorityFeePerGas); - } else if (tx.gasPrice) { - /* - * Legacy path: Ledger still requires maxFee* to skip re-estimation, so it - * will overwrite gas/fees with its own EIP-1559 estimate. We only forward - * gasPrice for wallets that honor it; do not expect Rango's gasLimit to - * stick on this path. - */ - params.gasPrice = toHexQuantity(tx.gasPrice); - } - return params; -}; - -/* - * Implement GenericSigner so signAndSendTx can return only `{ hash }` — - * Ledger's eth_sendTransaction never yields an ethers TransactionResponse. - * Delegate personal_sign / eth_signTypedData_v4 to DefaultEvmSigner (supported - * by Ledger). Do not use its signAndSendTx: ethers then polls - * eth_getTransactionByHash, which Ledger does not support. - */ -export class CustomEvmSigner implements GenericSigner { - private defaultEvmSigner: DefaultEvmSigner; - - constructor() { - /* - * Provider comes from the EIP-6963 announce stashed in ledgerProvider - * (getSigners runs after connect, so it should already be set). - */ - this.defaultEvmSigner = new DefaultEvmSigner(getProvider()); - } - - async signMessage(msg: string): Promise { - return await this.defaultEvmSigner.signMessage(msg); - } - - async signTypedData(typedData: TypedData): Promise { - return await this.defaultEvmSigner.signTypedData(typedData); - } - - async signAndSendTx( - tx: EvmTransaction, - /* - * Unused on purpose: - * - Ledger eth_sendTransaction does not validate tx.from against the - * selected account (unlike eth_signTypedData*), so an address check - * here cannot stop a wrong-account sign. - * - Network is enforced upstream by - * checkEnvironmentBeforeExecuteTransaction. - */ - _address: string, - _chainId: string | null - ): Promise<{ hash: string }> { - try { - const provider = getProvider(); - - const hash = await provider.request({ - method: 'eth_sendTransaction', - params: [buildLedgerTx(tx)], - }); - - return { hash }; - } catch (error) { - throw cleanEvmError(error); - } - } - - /* - * Tx is already broadcast; Ledger cannot serve getTransaction/receipts. - * Return the hash so checkStatus can continue via the API watcher. - */ - async wait(txHash: string): Promise<{ hash: string }> { - return { hash: txHash }; - } -} diff --git a/wallets/provider-ledger/package.json b/wallets/provider-ledger/package.json index e79446f1a0..abcf82d985 100644 --- a/wallets/provider-ledger/package.json +++ b/wallets/provider-ledger/package.json @@ -28,7 +28,6 @@ "@ledgerhq/hw-transport-webhid": "^6.28.6", "@ledgerhq/types-cryptoassets": "^7.11.0", "@ledgerhq/types-devices": "^6.24.0", - "@rango-dev/signer-evm": "^0.47.1", "@rango-dev/signer-solana": "^0.51.1-next.0", "@solana/web3.js": "^1.91.4", "@types/w3c-web-hid": "^1.0.2", @@ -39,15 +38,15 @@ }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, diff --git a/wallets/provider-ledger/src/namespaces/evm.ts b/wallets/provider-ledger/src/namespaces/evm.ts index 91f57f90c1..cdaf5e711c 100644 --- a/wallets/provider-ledger/src/namespaces/evm.ts +++ b/wallets/provider-ledger/src/namespaces/evm.ts @@ -1,25 +1,30 @@ import type { Context } from '@hub3js/core'; -import type { - AllowanceParams, - EvmActions, - EvmTransactionReceipt, -} from '@hub3js/evm'; +import type { AllowanceParams, EvmActions, EvmRpcUrls } from '@hub3js/evm'; import type { CaipAccount } from '@hub3js/std/types'; import { Hub3Error, NamespaceBuilder } from '@hub3js/core'; -import { builders, CAIP_NAMESPACE } from '@hub3js/evm'; +import { builders, CAIP_NAMESPACE, viemPublicAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; import { AccountId } from 'caip'; -import { Contract, toBeHex } from 'ethers'; import { ETHEREUM_CHAIN_ID, WALLET_ID } from '../constants.js'; +import { sendTransaction, signMessage } from '../signers/ethereum.js'; import { setDerivationPath } from '../state.js'; -import { getEthereumAccounts, getEvmRpcProvider } from '../utils.js'; +import { getEthereumAccounts } from '../utils.js'; const ERC20_ALLOWANCE_ABI = [ - 'function allowance(address owner, address spender) view returns (uint256)', -]; + { + type: 'function', + name: 'allowance', + stateMutability: 'view', + inputs: [ + { name: 'owner', type: 'address' }, + { name: 'spender', type: 'address' }, + ], + outputs: [{ name: '', type: 'uint256' }], + }, +] as const; const connect = builders .connect() @@ -62,58 +67,38 @@ const getChainId = builders .build(); /* - * Ledger injects no EIP-1193 provider, so these read actions talk to the shared - * JSON-RPC provider directly rather than through the default hub3js/evm actions. + * Ledger injects no EIP-1193 provider, so the allowance is read with the public + * client's `readContract`, which `buildEvm` registers. */ const getAllowance = builders .getAllowance() .action( async ( - _context: Context, + context: Context, params: AllowanceParams ): Promise => { - const token = new Contract( - params.token, - ERC20_ALLOWANCE_ABI, - getEvmRpcProvider() - ); - const currentAllowance: bigint = await token.allowance( - params.owner, - params.spender - ); - return currentAllowance.toString(); - } - ) - .build(); - -const getTransactionReceipt = builders - .getTransactionReceipt() - .action( - async ( - _context: Context, - transactionHash: `0x${string}` - ): Promise => { - const receipt = await getEvmRpcProvider().getTransactionReceipt( - transactionHash - ); - if (!receipt) { - return null; - } - return { - status: receipt.status === 1 ? '0x1' : '0x0', - transactionHash: receipt.hash, - blockNumber: toBeHex(receipt.blockNumber), - }; + const allowance = (await context.action('readContract', { + address: params.token, + abi: ERC20_ALLOWANCE_ABI, + functionName: 'allowance', + args: [params.owner, params.spender], + })) as bigint; + return allowance.toString(); } ) .build(); -const evm = new NamespaceBuilder('EVM', WALLET_ID) - .action(connect) - .action(disconnect) - .action(getChainId) - .action(getAllowance) - .action(getTransactionReceipt) - .build(); +const buildEvm = (rpcUrls?: EvmRpcUrls) => + new NamespaceBuilder('EVM', WALLET_ID) + // No wallet RPC, so viem's public actions go to our RPC endpoints. + .action(viemPublicAdapter(rpcUrls)) + .action(connect) + .action(disconnect) + .action(getChainId) + .action(getAllowance) + // Signed on the device, see `signers/ethereum.ts`. + .action('sendTransaction', sendTransaction) + .action('signMessage', signMessage) + .build(); -export { evm }; +export { buildEvm }; diff --git a/wallets/provider-ledger/src/provider.ts b/wallets/provider-ledger/src/provider.ts index 1351fa110a..9c0cbdfa07 100644 --- a/wallets/provider-ledger/src/provider.ts +++ b/wallets/provider-ledger/src/provider.ts @@ -1,12 +1,14 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; -import { evm } from './namespaces/evm.js'; +import { buildEvm } from './namespaces/evm.js'; import { solana } from './namespaces/solana.js'; import { ledger as ledgerInstance } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +const buildProvider = (rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -16,7 +18,8 @@ const buildProvider = () => }) .config('metadata', metadata) .add('solana', solana) - .add('evm', evm) + .add('evm', buildEvm(rpcURLs?.evm)) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-ledger/src/signer.ts b/wallets/provider-ledger/src/signer.ts index 201a9fe140..4aa676e619 100644 --- a/wallets/provider-ledger/src/signer.ts +++ b/wallets/provider-ledger/src/signer.ts @@ -2,12 +2,10 @@ import type { SignerFactory } from 'rango-types'; import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; -import { EthereumSigner } from './signers/ethereum'; import { SolanaSigner } from './signers/solana'; export default async function getSigners(): Promise { const signers = new DefaultSignerFactory(); - signers.registerSigner(TxType.EVM, new EthereumSigner()); signers.registerSigner(TxType.SOLANA, new SolanaSigner()); return signers; } diff --git a/wallets/provider-ledger/src/signers/ethereum.ts b/wallets/provider-ledger/src/signers/ethereum.ts index a2deef4e21..0a9e2834e6 100644 --- a/wallets/provider-ledger/src/signers/ethereum.ts +++ b/wallets/provider-ledger/src/signers/ethereum.ts @@ -1,11 +1,11 @@ -import type { FeeData, TransactionLike } from 'ethers'; -import type { GenericSigner } from 'rango-types'; -import type { EvmTransaction } from 'rango-types/mainApi'; +import type { Context, FunctionWithContext } from '@hub3js/core'; +import type { EvmActions } from '@hub3js/evm'; +import type { TransactionLike } from 'ethers'; -import { getEthereumRpcUrl } from '@rango-dev/signer-evm'; -import { JsonRpcProvider, Transaction } from 'ethers'; +import { Transaction } from 'ethers'; import { SignerError, SignerErrorCode } from 'rango-types'; +import { ETHEREUM_CHAIN_ID } from '../constants.js'; import { getDerivationPath } from '../state.js'; import { getLedgerError, @@ -13,9 +13,19 @@ import { transportDisconnect, } from '../utils.js'; -/** Whether a transaction already prices itself under either scheme. */ -function hasGasPricing(tx: EvmTransaction): boolean { - return !!tx.gasPrice || (!!tx.maxFeePerGas && !!tx.maxPriorityFeePerGas); +type Pricing = { + gasPrice: bigint | null; + maxFeePerGas: bigint | null; + maxPriorityFeePerGas: bigint | null; +}; + +const ZERO = BigInt(0); + +function getAddress(account: unknown): `0x${string}` { + if (typeof account === 'string') { + return account as `0x${string}`; + } + return (account as { address: `0x${string}` }).address; } /** @@ -23,133 +33,161 @@ function hasGasPricing(tx: EvmTransaction): boolean { * exclusive in a signed transaction, so EIP-1559 is used wherever the chain * quotes it and a legacy price is the fallback. */ -function pricingFromFeeData(fees: FeeData) { - if (fees.maxFeePerGas && fees.maxPriorityFeePerGas) { +async function getPricingFromNode( + context: Context +): Promise { + try { + const fees = (await context.action('estimateFeesPerGas')) as { + maxFeePerGas: bigint; + maxPriorityFeePerGas: bigint; + }; return { gasPrice: null, - maxFeePerGas: fees.maxFeePerGas.toString(), - maxPriorityFeePerGas: fees.maxPriorityFeePerGas.toString(), + maxFeePerGas: fees.maxFeePerGas, + maxPriorityFeePerGas: fees.maxPriorityFeePerGas, + }; + } catch { + return { + gasPrice: (await context.action('getGasPrice')) as bigint, + maxFeePerGas: null, + maxPriorityFeePerGas: null, }; } - - return { - gasPrice: fees.gasPrice?.toString() ?? null, - maxFeePerGas: null, - maxPriorityFeePerGas: null, - }; } -export class EthereumSigner implements GenericSigner { - async signMessage(msg: string): Promise { - try { - const transport = await transportConnect(); - const LedgerAppEth = (await import('@ledgerhq/hw-app-eth')).default; - const eth = new LedgerAppEth(transport); - - const result = await eth.signPersonalMessage( - getDerivationPath(), - Buffer.from(msg).toString('hex') - ); - // eslint-disable-next-line @typescript-eslint/no-magic-numbers - let v = (result['v'] - 27).toString(16); - if (v.length < 2) { - v = '0' + v; - } - return '0x' + result['r'] + result['s'] + v; - } catch (error) { - throw new SignerError(SignerErrorCode.SIGN_TX_ERROR, undefined, error); - } +export const signMessage: FunctionWithContext< + EvmActions['signMessage'], + Context +> = async (_context, params) => { + const message = params?.message; + if (typeof message !== 'string') { + throw new SignerError( + SignerErrorCode.SIGN_TX_ERROR, + undefined, + 'Ledger can only sign text messages.' + ); } - async signAndSendTx( - tx: EvmTransaction, - fromAddress: string, - chainId: string | null - ): Promise<{ hash: string }> { - try { - const provider = new JsonRpcProvider(getEthereumRpcUrl()); // Provider to broadcast transaction - - const transactionCount = await provider.getTransactionCount(fromAddress); // Get nonce - - /* - * Ledger signs a raw transaction on-device and does not estimate gas, so - * a limit has to be present. Server-built transactions arrive with one; - * client-built ones - approve prerequisites among them - do not, so it is - * estimated here. Everything else is taken as the transaction sends it. - */ - const gasLimit = - tx.gasLimit ?? - ( - await provider.estimateGas({ - from: fromAddress, - to: tx.to, - data: tx.data ?? undefined, - value: tx.value ?? undefined, - }) - ).toString(); - - /* - * Whatever pricing the transaction came with wins - a server-built one - * always carries it, and it is signed with exactly what it was created - * with. Only a client-built transaction, which leaves both schemes null, - * is priced from the node. - */ - const pricing = hasGasPricing(tx) - ? { - gasPrice: tx.gasPrice, - maxFeePerGas: tx.maxFeePerGas, - maxPriorityFeePerGas: tx.maxPriorityFeePerGas, - } - : pricingFromFeeData(await provider.getFeeData()); - - const transaction: TransactionLike = { - to: tx.to, - gasPrice: pricing.gasPrice, - gasLimit, - nonce: transactionCount, - chainId: chainId, - data: tx.data, - value: tx.value, - maxPriorityFeePerGas: pricing.maxPriorityFeePerGas, - maxFeePerGas: pricing.maxFeePerGas, - }; - - const unsignedTx = - Transaction.from(transaction).unsignedSerialized.substring(2); // Create unsigned transaction - - const transport = await transportConnect(); - const LedgerHqAppEth = await import('@ledgerhq/hw-app-eth'); - - const LedgerAppEth = LedgerHqAppEth.default; - const eth = new LedgerAppEth(transport); - - const resolution = await LedgerHqAppEth.ledgerService.resolveTransaction( - unsignedTx, - {}, - {} - ); // metadata necessary to allow the device to clear sign information - const signature = await eth.signTransaction( - getDerivationPath(), - unsignedTx, - resolution - ); - - const signedTx = Transaction.from({ - ...transaction, - signature: { - r: '0x' + signature.r, - s: '0x' + signature.s, - v: parseInt(signature.v), - }, - }).serialized; - - const broadcastResult = await provider.broadcastTransaction(signedTx); - - return { hash: broadcastResult.hash }; - } catch (error) { - throw getLedgerError(error); - } finally { - await transportDisconnect(); + try { + const transport = await transportConnect(); + const LedgerAppEth = (await import('@ledgerhq/hw-app-eth')).default; + const eth = new LedgerAppEth(transport); + + const result = await eth.signPersonalMessage( + getDerivationPath(), + Buffer.from(message).toString('hex') + ); + // eslint-disable-next-line @typescript-eslint/no-magic-numbers + let v = (result['v'] - 27).toString(16); + if (v.length < 2) { + v = '0' + v; } + return `0x${result['r']}${result['s']}${v}`; + } catch (error) { + throw new SignerError(SignerErrorCode.SIGN_TX_ERROR, undefined, error); } -} +}; + +/** + * Ledger has no injected provider: the transaction is completed through the + * namespace's public client, signed on the device, then broadcast. + */ +export const sendTransaction: FunctionWithContext< + EvmActions['sendTransaction'], + Context +> = async (context, request) => { + if (!request) { + throw new Error('A transaction is required.'); + } + const from = getAddress(request.account); + const { to, data, value } = request; + + try { + const nonce = + request.nonce ?? + ((await context.action('getTransactionCount', { + address: from, + })) as number); + + /* + * Ledger signs a raw transaction on-device and does not estimate gas, so + * a limit has to be present. Server-built transactions arrive with one; + * client-built ones - approve prerequisites among them - do not, so it is + * estimated here. Everything else is taken as the transaction sends it. + */ + const gasLimit = + request.gas ?? + ((await context.action('estimateGas', { + account: from, + to, + data, + value, + })) as bigint); + + /* + * Whatever pricing the transaction came with wins - a server-built one + * always carries it, and it is signed with exactly what it was created + * with. Only a client-built transaction, which leaves both schemes null, + * is priced from the node. + */ + const hasPricing = + !!request.gasPrice || + (!!request.maxFeePerGas && !!request.maxPriorityFeePerGas); + const pricing: Pricing = hasPricing + ? { + gasPrice: request.gasPrice ?? null, + maxFeePerGas: request.maxFeePerGas ?? null, + maxPriorityFeePerGas: request.maxPriorityFeePerGas ?? null, + } + : await getPricingFromNode(context); + + const transaction: TransactionLike = { + to: to ?? null, + gasPrice: pricing.gasPrice, + gasLimit, + nonce, + chainId: ETHEREUM_CHAIN_ID, + data: data ?? '0x', + value: value ?? ZERO, + maxPriorityFeePerGas: pricing.maxPriorityFeePerGas, + maxFeePerGas: pricing.maxFeePerGas, + }; + + const unsignedTx = + Transaction.from(transaction).unsignedSerialized.substring(2); // Create unsigned transaction + + const transport = await transportConnect(); + const LedgerHqAppEth = await import('@ledgerhq/hw-app-eth'); + + const LedgerAppEth = LedgerHqAppEth.default; + const eth = new LedgerAppEth(transport); + + const resolution = await LedgerHqAppEth.ledgerService.resolveTransaction( + unsignedTx, + {}, + {} + ); // metadata necessary to allow the device to clear sign information + const signature = await eth.signTransaction( + getDerivationPath(), + unsignedTx, + resolution + ); + + const signedTx = Transaction.from({ + ...transaction, + signature: { + r: '0x' + signature.r, + s: '0x' + signature.s, + v: parseInt(signature.v), + }, + }).serialized as `0x${string}`; + + return (await context.action('sendRawTransaction', { + serializedTransaction: signedTx, + })) as `0x${string}`; + } catch (error) { + throw getLedgerError(error); + } finally { + await transportDisconnect(); + } +}; diff --git a/wallets/provider-ledger/src/utils.ts b/wallets/provider-ledger/src/utils.ts index bc152adbca..9982c31414 100644 --- a/wallets/provider-ledger/src/utils.ts +++ b/wallets/provider-ledger/src/utils.ts @@ -4,9 +4,7 @@ import { getErrorMessage, Hub3Error } from '@hub3js/core'; import { EVM_NAMESPACE, SOLANA_NAMESPACE } from '@hub3js/namespaces'; import { CAIP_SOLANA_CHAIN_ID } from '@hub3js/solana'; import { getAltStatusMessage } from '@ledgerhq/errors'; -import { getEthereumRpcUrl } from '@rango-dev/signer-evm'; import bs58 from 'bs58'; -import { JsonRpcProvider } from 'ethers'; import { ETHEREUM_CHAIN_ID, @@ -17,23 +15,6 @@ import { getDerivationPath } from './state.js'; export type Provider = Map; -/** - * Ledger EVM is Ethereum-only today and has no injected provider, so a single - * JSON-RPC provider over the Ethereum endpoint serves both the signer (nonce + - * broadcast) and the read-only namespace actions (allowance, receipt). - * - * NOTE: If Ledger EVM support ever expands beyond Ethereum, this must select - * the RPC per chain instead of the single Ethereum endpoint. - */ -let evmRpcProvider: { url: string; provider: JsonRpcProvider } | undefined; -export function getEvmRpcProvider(): JsonRpcProvider { - const url = getEthereumRpcUrl(); - if (evmRpcProvider?.url !== url) { - evmRpcProvider = { url, provider: new JsonRpcProvider(url) }; - } - return evmRpcProvider.provider; -} - type DeviceAccounts = { accounts: string[]; chainId: string; diff --git a/wallets/provider-math-wallet/package.json b/wallets/provider-math-wallet/package.json index f58a624f94..319d96046f 100644 --- a/wallets/provider-math-wallet/package.json +++ b/wallets/provider-math-wallet/package.json @@ -22,21 +22,20 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "@rango-dev/signer-solana": "^0.51.1-next.0", "rango-types": "^0.6.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, diff --git a/wallets/provider-math-wallet/src/namespaces/evm.ts b/wallets/provider-math-wallet/src/namespaces/evm.ts index 284128a7fe..43701acdc0 100644 --- a/wallets/provider-math-wallet/src/namespaces/evm.ts +++ b/wallets/provider-math-wallet/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders } from '@hub3js/evm'; +import { actions, builders, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -37,19 +37,14 @@ const getAllowance = builders .action(actions.getAllowance(evmMathWallet)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmMathWallet)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmMathWallet)) .action(connect) .action(disconnect) .action(canSwitchNetwork) .action(canEagerConnect) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-math-wallet/src/provider.ts b/wallets/provider-math-wallet/src/provider.ts index 23def3e94b..e91fdeca2c 100644 --- a/wallets/provider-math-wallet/src/provider.ts +++ b/wallets/provider-math-wallet/src/provider.ts @@ -1,3 +1,5 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { @@ -9,8 +11,9 @@ import { evm } from './namespaces/evm.js'; import { solana } from './namespaces/solana.js'; import { mathWallet } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -25,5 +28,6 @@ const buildProvider = () => .add('solana', solana) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-math-wallet/src/signer.ts b/wallets/provider-math-wallet/src/signer.ts index 96bc2f2064..d47dbaf392 100644 --- a/wallets/provider-math-wallet/src/signer.ts +++ b/wallets/provider-math-wallet/src/signer.ts @@ -1,22 +1,17 @@ import type { Provider } from './types.js'; import type { SignerFactory } from 'rango-types'; -import { EVM_NAMESPACE, SOLANA_NAMESPACE } from '@hub3js/namespaces'; +import { SOLANA_NAMESPACE } from '@hub3js/namespaces'; import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; export default async function getSigners( provider: Provider ): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); const solProvider = provider.get(SOLANA_NAMESPACE); const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); const { DefaultSolanaSigner } = await import('@rango-dev/signer-solana'); - if (!!ethProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(ethProvider)); - } if (!!solProvider) { signers.registerSigner(TxType.SOLANA, new DefaultSolanaSigner(solProvider)); } diff --git a/wallets/provider-metamask/package.json b/wallets/provider-metamask/package.json index 70fea34656..15db47644b 100644 --- a/wallets/provider-metamask/package.json +++ b/wallets/provider-metamask/package.json @@ -22,7 +22,6 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "@rango-dev/signer-solana": "^0.51.1-next.0", "@wallet-standard/app": "^1.1.0", "bs58": "^5.0.0", @@ -30,8 +29,8 @@ }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0", "@solana/wallet-standard-features": "^1.3.0", @@ -40,8 +39,8 @@ }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, diff --git a/wallets/provider-metamask/src/namespaces/evm.ts b/wallets/provider-metamask/src/namespaces/evm.ts index ae95ac3a2f..f447ff5a98 100644 --- a/wallets/provider-metamask/src/namespaces/evm.ts +++ b/wallets/provider-metamask/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { ActionBuilder, NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, utils } from '@hub3js/evm'; +import { actions, builders, utils, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { connectAndUpdateStateForMultiNetworks, @@ -71,19 +71,14 @@ const getAllowance = builders .action(actions.getAllowance(evmMetamask)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmMetamask)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmMetamask)) .action(connect) .action(disconnect) .action(canSwitchNetwork) .action(canEagerConnect) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-metamask/src/provider.ts b/wallets/provider-metamask/src/provider.ts index 00ce5736d6..5c079cd439 100644 --- a/wallets/provider-metamask/src/provider.ts +++ b/wallets/provider-metamask/src/provider.ts @@ -1,3 +1,5 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; @@ -5,8 +7,9 @@ import { evm } from './namespaces/evm.js'; import { solana } from './namespaces/solana.js'; import { metamask as metamask } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -19,5 +22,6 @@ const buildProvider = () => .add('evm', evm) .add('solana', solana) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-metamask/src/signer.ts b/wallets/provider-metamask/src/signer.ts index 800dcfd61b..2d3c639ec7 100644 --- a/wallets/provider-metamask/src/signer.ts +++ b/wallets/provider-metamask/src/signer.ts @@ -1,7 +1,7 @@ import type { Provider } from './types.js'; import type { SignerFactory } from 'rango-types'; -import { EVM_NAMESPACE, SOLANA_NAMESPACE } from '@hub3js/namespaces'; +import { SOLANA_NAMESPACE } from '@hub3js/namespaces'; import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; import { MetamaskSolanaSigner } from './signers/solana.js'; @@ -9,14 +9,9 @@ import { MetamaskSolanaSigner } from './signers/solana.js'; export default async function getSigners( provider: Provider ): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); const solanaProvider = provider.get(SOLANA_NAMESPACE); const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); - if (!!ethProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(ethProvider)); - } if (!!solanaProvider) { signers.registerSigner( TxType.SOLANA, diff --git a/wallets/provider-noir-wallet/package.json b/wallets/provider-noir-wallet/package.json index 132e9865e2..032e6e5886 100644 --- a/wallets/provider-noir-wallet/package.json +++ b/wallets/provider-noir-wallet/package.json @@ -30,11 +30,13 @@ "devDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-noir-wallet/src/provider.ts b/wallets/provider-noir-wallet/src/provider.ts index 7d53f63cb9..18fe7b71a9 100644 --- a/wallets/provider-noir-wallet/src/provider.ts +++ b/wallets/provider-noir-wallet/src/provider.ts @@ -1,10 +1,13 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { isNoirWalletInstalled } from '@noir-wallet/sdk'; import { info, WALLET_ID } from './constants.js'; import { namespace as utxo } from './namespaces/utxo.js'; -const buildProvider = () => +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); diff --git a/wallets/provider-okx/package.json b/wallets/provider-okx/package.json index 73e6322c0a..c788f25ae5 100644 --- a/wallets/provider-okx/package.json +++ b/wallets/provider-okx/package.json @@ -23,7 +23,6 @@ }, "dependencies": { "@rango-dev/internal-blockchains": "^0.3.1-next.1", - "@rango-dev/signer-evm": "^0.47.0", "@rango-dev/signer-solana": "^0.51.1-next.0", "@rango-dev/signer-sui": "^0.13.1-next.0", "@rango-dev/signer-ton": "^0.31.1-next.0", @@ -34,8 +33,8 @@ "devDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0", "@hub3js/sui": "^0.6.0", @@ -45,8 +44,8 @@ "peerDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0", "@hub3js/sui": "^0.6.0", diff --git a/wallets/provider-okx/src/namespaces/evm.ts b/wallets/provider-okx/src/namespaces/evm.ts index ea97e0cd7b..5ce3d56824 100644 --- a/wallets/provider-okx/src/namespaces/evm.ts +++ b/wallets/provider-okx/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, utils } from '@hub3js/evm'; +import { actions, builders, utils, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -61,19 +61,14 @@ const getAllowance = builders .action(actions.getAllowance(evmOKX)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmOKX)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmOKX)) .action(connect) .action(disconnect) .action(canEagerConnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-okx/src/provider.ts b/wallets/provider-okx/src/provider.ts index 47ad312f9e..6c450a907a 100644 --- a/wallets/provider-okx/src/provider.ts +++ b/wallets/provider-okx/src/provider.ts @@ -1,4 +1,5 @@ import type { Environments } from './namespaces/ton/types.js'; +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; import { ProviderBuilder } from '@hub3js/core'; @@ -12,8 +13,9 @@ import { tron } from './namespaces/tron.js'; import { utxo } from './namespaces/utxo.js'; import { okx as okxInstance } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context, environments?: Environments) { setEnvironments(environments); const [, setState] = context.state(); @@ -32,5 +34,6 @@ const buildProvider = () => .add('sui', sui) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-okx/src/signer.ts b/wallets/provider-okx/src/signer.ts index fee0de50cf..e8a793dd0f 100644 --- a/wallets/provider-okx/src/signer.ts +++ b/wallets/provider-okx/src/signer.ts @@ -2,7 +2,6 @@ import type { Provider } from './types.js'; import type { SignerFactory } from 'rango-types'; import { - EVM_NAMESPACE, SOLANA_NAMESPACE, TON_NAMESPACE, TRON_NAMESPACE, @@ -18,18 +17,13 @@ import { suiWalletInstance } from './utils.js'; export default async function getSigners( provider: Provider ): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); const solProvider = provider.get(SOLANA_NAMESPACE); const utxoProvider = provider.get(UTXO_NAMESPACE); const tonProvider = provider.get(TON_NAMESPACE); const tronProvider = provider.get(TRON_NAMESPACE); const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); const { DefaultTronSigner } = await import('@rango-dev/signer-tron'); - if (!!ethProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(ethProvider)); - } if (!!solProvider) { signers.registerSigner(TxType.SOLANA, new OKXSolanaSigner(solProvider)); } diff --git a/wallets/provider-phantom/package.json b/wallets/provider-phantom/package.json index ba9bd7e855..ebbd0a76c0 100644 --- a/wallets/provider-phantom/package.json +++ b/wallets/provider-phantom/package.json @@ -33,16 +33,16 @@ "devDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, diff --git a/wallets/provider-phantom/src/namespaces/evm.ts b/wallets/provider-phantom/src/namespaces/evm.ts index 5c65f2ef9d..ff60114310 100644 --- a/wallets/provider-phantom/src/namespaces/evm.ts +++ b/wallets/provider-phantom/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, hooks } from '@hub3js/evm'; +import { actions, builders, hooks, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -50,19 +50,14 @@ const getAllowance = builders .action(actions.getAllowance(evmPhantom)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmPhantom)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmPhantom)) .action(connect) .action(disconnect) .action(canEagerConnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-phantom/src/provider.ts b/wallets/provider-phantom/src/provider.ts index 3a8c9f3cd6..38df366551 100644 --- a/wallets/provider-phantom/src/provider.ts +++ b/wallets/provider-phantom/src/provider.ts @@ -1,3 +1,5 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; @@ -5,8 +7,9 @@ import { evm } from './namespaces/evm.js'; import { solana } from './namespaces/solana.js'; import { phantom as phantomInstance } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -19,5 +22,6 @@ const buildProvider = () => .add('solana', solana) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-phantom/src/signer.ts b/wallets/provider-phantom/src/signer.ts index 1f90765f6e..c63026c7dd 100644 --- a/wallets/provider-phantom/src/signer.ts +++ b/wallets/provider-phantom/src/signer.ts @@ -1,30 +1,21 @@ import type { Provider } from './utils.js'; import type { SignerFactory } from 'rango-types'; -import { - EVM_NAMESPACE, - SOLANA_NAMESPACE, - UTXO_NAMESPACE, -} from '@hub3js/namespaces'; +import { SOLANA_NAMESPACE, UTXO_NAMESPACE } from '@hub3js/namespaces'; import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; export default async function getSigners( provider: Provider ): Promise { const solProvider = provider.get(SOLANA_NAMESPACE); - const evmProvider = provider.get(EVM_NAMESPACE); const bitcoinInstance = provider.get(UTXO_NAMESPACE); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); const { DefaultSolanaSigner } = await import('@rango-dev/signer-solana'); const { BTCSigner } = await import('./signers/utxoSigner.js'); const signers = new DefaultSignerFactory(); if (!!solProvider) { signers.registerSigner(TxType.SOLANA, new DefaultSolanaSigner(solProvider)); } - if (!!evmProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(evmProvider)); - } if (!!bitcoinInstance) { signers.registerSigner(TxType.TRANSFER, new BTCSigner(bitcoinInstance)); } diff --git a/wallets/provider-rabby/package.json b/wallets/provider-rabby/package.json index 4dbbb7269e..6462c2dae0 100644 --- a/wallets/provider-rabby/package.json +++ b/wallets/provider-rabby/package.json @@ -22,19 +22,18 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "rango-types": "^0.6.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-rabby/src/constants.ts b/wallets/provider-rabby/src/constants.ts index d7f557afee..4ebd6ca24c 100644 --- a/wallets/provider-rabby/src/constants.ts +++ b/wallets/provider-rabby/src/constants.ts @@ -2,9 +2,6 @@ import type { ProviderMetadata } from '@hub3js/core'; import { isEvmNamespace } from '@hub3js/evm'; -import getSigners from './signer.js'; -import { getInstanceOrThrow } from './utils.js'; - export const WALLET_ID = 'rabby'; export const metadata: ProviderMetadata = { @@ -33,9 +30,5 @@ export const metadata: ProviderMetadata = { ], }, }, - { - name: 'signers', - value: { getSigners: async () => getSigners(getInstanceOrThrow()) }, - }, ], }; diff --git a/wallets/provider-rabby/src/namespaces/evm.ts b/wallets/provider-rabby/src/namespaces/evm.ts index 73d692a2ff..8084a1ec1c 100644 --- a/wallets/provider-rabby/src/namespaces/evm.ts +++ b/wallets/provider-rabby/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, hooks } from '@hub3js/evm'; +import { actions, builders, hooks, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -44,19 +44,14 @@ const getAllowance = builders .action(actions.getAllowance(evmRabby)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmRabby)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmRabby)) .action(connect) .action(disconnect) .action(canEagerConnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-rabby/src/provider.ts b/wallets/provider-rabby/src/provider.ts index 2b3bd56073..656861dc09 100644 --- a/wallets/provider-rabby/src/provider.ts +++ b/wallets/provider-rabby/src/provider.ts @@ -1,11 +1,14 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; import { evm } from './namespaces/evm.js'; import { rabby as rabbyInstance } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); if (rabbyInstance()) { @@ -16,5 +19,6 @@ const buildProvider = () => .config('metadata', metadata) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-rabby/src/signer.ts b/wallets/provider-rabby/src/signer.ts deleted file mode 100644 index e8cde811ef..0000000000 --- a/wallets/provider-rabby/src/signer.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { Provider } from './utils.js'; -import type { SignerFactory } from 'rango-types'; - -import { EVM_NAMESPACE } from '@hub3js/namespaces'; -import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; - -export default async function getSigners( - provider: Provider -): Promise { - const evmProvider = provider.get(EVM_NAMESPACE); - const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); - if (!!evmProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(evmProvider)); - } - return signers; -} diff --git a/wallets/provider-rabby/src/utils.ts b/wallets/provider-rabby/src/utils.ts index 2d10100ec2..7834e181b7 100644 --- a/wallets/provider-rabby/src/utils.ts +++ b/wallets/provider-rabby/src/utils.ts @@ -27,16 +27,6 @@ export function rabby(): Provider | null { return instances; } -export function getInstanceOrThrow(): Provider { - const instances = rabby(); - - if (!instances) { - throw new Error('Rabby is not injected. Please check your wallet.'); - } - - return instances; -} - export function evmRabby(): EvmProviderApi { const instances = rabby(); diff --git a/wallets/provider-ready/package.json b/wallets/provider-ready/package.json index b98fedd343..8fa53e2002 100644 --- a/wallets/provider-ready/package.json +++ b/wallets/provider-ready/package.json @@ -27,13 +27,13 @@ }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/starknet": "^0.6.0", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/starknet": "^0.6.0", "@hub3js/std": "^0.6.0" }, diff --git a/wallets/provider-ready/src/provider.ts b/wallets/provider-ready/src/provider.ts index d7e6698c41..6c832751e4 100644 --- a/wallets/provider-ready/src/provider.ts +++ b/wallets/provider-ready/src/provider.ts @@ -1,10 +1,13 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; import { starknet } from './namespaces/starknet.js'; import { ready } from './utils.js'; -const buildProvider = () => +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); diff --git a/wallets/provider-safe/package.json b/wallets/provider-safe/package.json index ddc7a8d2ac..38b74aa7f6 100644 --- a/wallets/provider-safe/package.json +++ b/wallets/provider-safe/package.json @@ -22,20 +22,19 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "@safe-global/safe-apps-provider": "^0.18.6", - "@safe-global/safe-apps-sdk": "^9.1.0", - "ethers": "^6.13.2", - "rango-types": "^0.6.0" + "@safe-global/safe-apps-sdk": "^9.1.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-safe/src/constants.ts b/wallets/provider-safe/src/constants.ts index 70a723815d..61c1e76dcd 100644 --- a/wallets/provider-safe/src/constants.ts +++ b/wallets/provider-safe/src/constants.ts @@ -2,9 +2,6 @@ import type { ProviderMetadata } from '@hub3js/core'; import { isEvmNamespace } from '@hub3js/evm'; -import getSigners from './signer.js'; -import { evmSafe } from './utils.js'; - export const WALLET_ID = 'safe'; export const metadata: ProviderMetadata = { @@ -32,9 +29,5 @@ export const metadata: ProviderMetadata = { name: 'details', value: { isContractWallet: true }, }, - { - name: 'signers', - value: { getSigners: async () => getSigners(evmSafe()) }, - }, ], }; diff --git a/wallets/provider-safe/src/namespaces/evm.test.ts b/wallets/provider-safe/src/namespaces/evm.test.ts new file mode 100644 index 0000000000..01890b8254 --- /dev/null +++ b/wallets/provider-safe/src/namespaces/evm.test.ts @@ -0,0 +1,49 @@ +import { beforeEach, describe, expect, test, vi } from 'vitest'; + +const SAFE_SIGNATURE = '0x5afe'; +const ACCOUNT = '0x1111111111111111111111111111111111111111'; + +const safeSdk = vi.hoisted(() => ({ + txs: { signMessage: vi.fn() }, +})); +const walletRequest = vi.hoisted(() => vi.fn()); + +vi.mock('../safe.js', () => ({ sdk: safeSdk })); +vi.mock('../utils.js', () => ({ + evmSafe: () => ({ request: walletRequest }), + getSafeAccounts: vi.fn(), +})); + +const { evm } = await import('./evm.js'); + +describe('Safe EVM namespace', () => { + beforeEach(() => { + vi.clearAllMocks(); + safeSdk.txs.signMessage.mockResolvedValue({ signature: SAFE_SIGNATURE }); + }); + + /* + * viemWalletAdapter registers a `signMessage` too, which would sign through + * the wallet's EIP-1193 `personal_sign`. Safe's own action is registered + * after the adapter, so it has to win. + */ + test("signs messages with Safe's own action, not the viem adapter's", async () => { + const signature = await evm.signMessage({ + account: ACCOUNT, + message: 'hello', + }); + + expect(signature).toBe(SAFE_SIGNATURE); + expect(safeSdk.txs.signMessage).toHaveBeenCalledWith('hello'); + expect(walletRequest).not.toHaveBeenCalled(); + }); + + test("keeps viem's wallet actions that Safe doesn't define", async () => { + walletRequest.mockResolvedValue('0x10'); + + await expect(evm.getBlockNumber()).resolves.toBe(BigInt('0x10')); + expect(walletRequest).toHaveBeenCalledWith( + expect.objectContaining({ method: 'eth_blockNumber' }) + ); + }); +}); diff --git a/wallets/provider-safe/src/namespaces/evm.ts b/wallets/provider-safe/src/namespaces/evm.ts index 73cd13e099..6020532de1 100644 --- a/wallets/provider-safe/src/namespaces/evm.ts +++ b/wallets/provider-safe/src/namespaces/evm.ts @@ -1,11 +1,15 @@ +import type { Context, FunctionWithContext } from '@hub3js/core'; import type { EvmActions } from '@hub3js/evm'; +import type { OffChainSignMessageResponse } from '@safe-global/safe-apps-sdk'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, hooks } from '@hub3js/evm'; +import { actions, builders, hooks, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; import { WALLET_ID } from '../constants.js'; +import { sdk } from '../safe.js'; +import { resolveTransactionHash } from '../transactionHash.js'; import { evmSafe, getSafeAccounts } from '../utils.js'; const [changeAccountSubscriber, changeAccountCleanup] = @@ -44,19 +48,44 @@ const getAllowance = builders .action(actions.getAllowance(evmSafe)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmSafe)) - .build(); +// Safe signs messages off-chain through its SDK. +const signMessage: FunctionWithContext< + EvmActions['signMessage'], + Context +> = async (_context, params) => { + const message = params?.message; + if (typeof message !== 'string') { + throw new Error('Safe can only sign text messages.'); + } + const { signature } = (await sdk.txs.signMessage( + message + )) as OffChainSignMessageResponse & { signature: `0x${string}` }; + return signature; +}; + +/* + * Safe's `sendTransaction` returns a safeTxHash. This extra action, which + * queue-manager looks up by name, maps it to the on-chain hash. + */ +const RESOLVE_TRANSACTION_HASH = 'resolveTransactionHash' as keyof EvmActions; +const resolveTransactionHashAction = (async ( + _context: Context, + hash: string +) => resolveTransactionHash(hash)) as unknown as FunctionWithContext< + EvmActions[keyof EvmActions], + Context +>; const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmSafe)) .action(connect) .action(disconnect) .action(canEagerConnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) + .action('signMessage', signMessage) + .action(RESOLVE_TRANSACTION_HASH, resolveTransactionHashAction) .build(); export { evm }; diff --git a/wallets/provider-safe/src/provider.ts b/wallets/provider-safe/src/provider.ts index 0581f7b145..7fe9fe9284 100644 --- a/wallets/provider-safe/src/provider.ts +++ b/wallets/provider-safe/src/provider.ts @@ -1,11 +1,14 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; import { evm } from './namespaces/evm.js'; import { initSafe } from './safe.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -26,5 +29,6 @@ const buildProvider = () => .config('metadata', metadata) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-safe/src/signer.ts b/wallets/provider-safe/src/signer.ts deleted file mode 100644 index 7b152e56fc..0000000000 --- a/wallets/provider-safe/src/signer.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ProviderAPI } from '@hub3js/evm'; -import type { SignerFactory } from 'rango-types'; - -import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; - -export default async function getSigners( - provider: ProviderAPI -): Promise { - const signers = new DefaultSignerFactory(); - const { CustomEvmSigner } = await import('./signers/evm.js'); - signers.registerSigner(TxType.EVM, new CustomEvmSigner(provider)); - - return signers; -} diff --git a/wallets/provider-safe/src/signers/evm.ts b/wallets/provider-safe/src/signers/evm.ts deleted file mode 100644 index fa9402b42a..0000000000 --- a/wallets/provider-safe/src/signers/evm.ts +++ /dev/null @@ -1,101 +0,0 @@ -import type { ProviderAPI } from '@hub3js/evm'; -import type { OffChainSignMessageResponse } from '@safe-global/safe-apps-sdk'; -import type { TransactionResponse } from 'ethers'; -import type { GenericSigner } from 'rango-types'; -import type { EvmTransaction } from 'rango-types/mainApi'; - -import { DefaultEvmSigner, waitMs } from '@rango-dev/signer-evm'; -import { TransactionStatus } from '@safe-global/safe-apps-sdk'; - -import { sdk } from '../safe.ts'; - -type SafeTransactionResponse = Partial & { - hashRequiringUpdate: boolean; -}; - -export async function getTxHash(safeHash: string): Promise<{ txHash: string }> { - let txHash; - const timeout = 5_000; - - while (!txHash) { - try { - /** The SDK will be pinged until a txHash is available and the txStatus is in an end-state */ - const queued = await sdk.txs.getBySafeTxHash(safeHash); - if ( - queued.txStatus === TransactionStatus.AWAITING_CONFIRMATIONS || - queued.txStatus === TransactionStatus.AWAITING_EXECUTION - ) { - /** Mimic a status watcher by checking once every 5 seconds */ - await waitMs(timeout); - } else if (queued.txHash) { - /** The txStatus is in an end-state (e.g. success) so we probably have a valid, on chain txHash*/ - txHash = queued.txHash; - } - } catch { - txHash = safeHash; - } - } - return { txHash }; -} - -export class CustomEvmSigner implements GenericSigner { - private signer; - - constructor(provider: ProviderAPI) { - this.signer = new DefaultEvmSigner(provider); - } - - async signMessage(msg: string): Promise { - const { signature } = (await sdk.txs.signMessage( - msg - )) as OffChainSignMessageResponse & { signature: string }; - - return signature; - } - - async signAndSendTx( - tx: EvmTransaction, - address: string, - chainId: string | null - ): Promise<{ hash: string; response: SafeTransactionResponse }> { - const { hash, response } = await this.signer.signAndSendTx( - tx, - address, - chainId - ); - return { - hash, - response: { ...response, hashRequiringUpdate: true }, - }; - } - - async wait( - safeHash: string, - chainId: string, - response: SafeTransactionResponse - ): Promise<{ - hash: string; - response: SafeTransactionResponse; - chainId: string; - }> { - /* - * `wait` is called on every status poll. On the first poll `safeHash` is the - * safeTxHash, which `getTxHash` maps to the on-chain hash; the queue then - * updates `executedTransactionId` to that on-chain hash. From the next poll - * onwards `wait` receives the on-chain hash, and querying the Safe gateway - * with it 404s (the gateway resolves by safeTxHash, not the on-chain hash), - * which makes Safe{Wallet} log a harmless `Code 901`. Once the hash no longer - * requires updating we already have the final hash, so skip the lookup. - */ - if (response && !response.hashRequiringUpdate) { - return { hash: safeHash, response, chainId }; - } - - const { txHash: hash } = await getTxHash(safeHash); - return { - hash, - response: { ...response, hashRequiringUpdate: false }, - chainId, - }; - } -} diff --git a/wallets/provider-safe/src/transactionHash.ts b/wallets/provider-safe/src/transactionHash.ts new file mode 100644 index 0000000000..dba5e2a4b1 --- /dev/null +++ b/wallets/provider-safe/src/transactionHash.ts @@ -0,0 +1,50 @@ +import { TransactionStatus } from '@safe-global/safe-apps-sdk'; + +import { sdk } from './safe.js'; + +const POLL_INTERVAL = 5_000; + +const waitMs = async (ms: number) => + new Promise((resolve) => setTimeout(resolve, ms)); + +/** + * On-chain hashes already resolved, so a later lookup with one of them skips + * the Safe gateway: it resolves by safeTxHash, and an on-chain hash makes + * Safe{Wallet} log a harmless `Code 901`. + */ +const resolvedHashes = new Set(); + +/** + * Safe's `eth_sendTransaction` returns a safeTxHash. This waits for the Safe + * transaction to reach an end state and returns its on-chain hash. + */ +export async function resolveTransactionHash( + safeHash: string +): Promise { + if (resolvedHashes.has(safeHash)) { + return safeHash; + } + + let txHash: string | undefined; + while (!txHash) { + try { + /** The SDK will be pinged until a txHash is available and the txStatus is in an end-state */ + const queued = await sdk.txs.getBySafeTxHash(safeHash); + if ( + queued.txStatus === TransactionStatus.AWAITING_CONFIRMATIONS || + queued.txStatus === TransactionStatus.AWAITING_EXECUTION + ) { + /** Mimic a status watcher by checking once every 5 seconds */ + await waitMs(POLL_INTERVAL); + } else if (queued.txHash) { + /** The txStatus is in an end-state (e.g. success) so we probably have a valid, on chain txHash*/ + txHash = queued.txHash; + } + } catch { + txHash = safeHash; + } + } + + resolvedHashes.add(txHash); + return txHash; +} diff --git a/wallets/provider-safepal/package.json b/wallets/provider-safepal/package.json index 7121b924c3..ec0e58b96e 100644 --- a/wallets/provider-safepal/package.json +++ b/wallets/provider-safepal/package.json @@ -22,21 +22,20 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "@rango-dev/signer-solana": "^0.51.1-next.0", "ethers": "^6.13.2", "rango-types": "^0.6.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-safepal/src/constants.ts b/wallets/provider-safepal/src/constants.ts index f20cc21434..0e6e7cae3c 100644 --- a/wallets/provider-safepal/src/constants.ts +++ b/wallets/provider-safepal/src/constants.ts @@ -2,9 +2,6 @@ import type { ProviderMetadata } from '@hub3js/core'; import { isEvmNamespace } from '@hub3js/evm'; -import getSigners from './signer.js'; -import { getInstanceOrThrow } from './utils.js'; - export const WALLET_ID = 'safepal'; export const metadata: ProviderMetadata = { name: 'SafePal', @@ -33,9 +30,5 @@ export const metadata: ProviderMetadata = { ], }, }, - { - name: 'signers', - value: { getSigners: async () => getSigners(getInstanceOrThrow()) }, - }, ], }; diff --git a/wallets/provider-safepal/src/namespaces/evm.ts b/wallets/provider-safepal/src/namespaces/evm.ts index 7d1cad9a63..f8110a67f0 100644 --- a/wallets/provider-safepal/src/namespaces/evm.ts +++ b/wallets/provider-safepal/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { ActionBuilder, NamespaceBuilder } from '@hub3js/core'; -import { actions, builders } from '@hub3js/evm'; +import { actions, builders, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { connectAndUpdateStateForMultiNetworks, @@ -61,18 +61,13 @@ const getAllowance = builders .action(actions.getAllowance(evmSafepal)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmSafepal)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmSafepal)) .action(connect) .action(disconnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-safepal/src/provider.ts b/wallets/provider-safepal/src/provider.ts index 329d18dea5..cadd4359e4 100644 --- a/wallets/provider-safepal/src/provider.ts +++ b/wallets/provider-safepal/src/provider.ts @@ -1,3 +1,5 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; @@ -5,8 +7,9 @@ import { evm } from './namespaces/evm.js'; import { safepal as safepalInstance } from './utils.js'; const WAIT_TO_LOAD_INSTANCE_DELAY = 1000; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { setTimeout(() => { if (safepalInstance()) { @@ -20,5 +23,6 @@ const buildProvider = () => .config('metadata', metadata) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-safepal/src/signer.ts b/wallets/provider-safepal/src/signer.ts deleted file mode 100644 index eb60bb881c..0000000000 --- a/wallets/provider-safepal/src/signer.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { Provider } from './utils.js'; -import type { SignerFactory } from 'rango-types'; - -import { EVM_NAMESPACE } from '@hub3js/namespaces'; -import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; - -export default async function getSigners( - provider: Provider -): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); - const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); - if (!!ethProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(ethProvider)); - } - return signers; -} diff --git a/wallets/provider-safepal/src/utils.ts b/wallets/provider-safepal/src/utils.ts index af93bdb280..42e9de86e3 100644 --- a/wallets/provider-safepal/src/utils.ts +++ b/wallets/provider-safepal/src/utils.ts @@ -31,15 +31,6 @@ export function evmSafepal(): EvmProviderApi { } return evmInstance; } -export function getInstanceOrThrow(): Provider { - const instances = safepal(); - - if (!instances) { - throw new Error('Trust Wallet is not injected. Please check your wallet.'); - } - - return instances; -} /** * Return true if address is a valid EVM address. * Accepts: diff --git a/wallets/provider-slush/package.json b/wallets/provider-slush/package.json index 6dd972fd2a..a71782c33e 100644 --- a/wallets/provider-slush/package.json +++ b/wallets/provider-slush/package.json @@ -29,11 +29,13 @@ }, "devDependencies": { "@hub3js/core": "^0.64.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0", "@hub3js/sui": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0", "@hub3js/sui": "^0.6.0" }, diff --git a/wallets/provider-slush/src/provider.ts b/wallets/provider-slush/src/provider.ts index bb0c11df63..83aea28399 100644 --- a/wallets/provider-slush/src/provider.ts +++ b/wallets/provider-slush/src/provider.ts @@ -1,10 +1,13 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; import { sui } from './namespaces/sui.js'; import { suiWalletInstance } from './utils.js'; -const buildProvider = () => +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); diff --git a/wallets/provider-solflare/package.json b/wallets/provider-solflare/package.json index 4ea4493404..a06befa2c6 100644 --- a/wallets/provider-solflare/package.json +++ b/wallets/provider-solflare/package.json @@ -29,13 +29,13 @@ }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, diff --git a/wallets/provider-solflare/src/provider.ts b/wallets/provider-solflare/src/provider.ts index e0b6087b6f..9da60249a7 100644 --- a/wallets/provider-solflare/src/provider.ts +++ b/wallets/provider-solflare/src/provider.ts @@ -1,10 +1,13 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, SOLFLARE_INJECTION_DELAY, WALLET_ID } from './constants.js'; import { solana } from './namespaces/solana.js'; import { solflare } from './utils.js'; -const buildProvider = () => +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); diff --git a/wallets/provider-taho/package.json b/wallets/provider-taho/package.json index d32fa61751..2f78b37793 100644 --- a/wallets/provider-taho/package.json +++ b/wallets/provider-taho/package.json @@ -22,19 +22,18 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "rango-types": "^0.6.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-taho/src/constants.ts b/wallets/provider-taho/src/constants.ts index 487d3815d9..295ec1c93b 100644 --- a/wallets/provider-taho/src/constants.ts +++ b/wallets/provider-taho/src/constants.ts @@ -11,9 +11,6 @@ import { } from '@hub3js/evm'; import { getChainIdFromCaip2ChainId } from '@hub3js/std/utils'; -import getSigners from './signer.js'; -import { getInstanceOrThrow } from './utils.js'; - export const TAHO_WALLET_SUPPORTED_EVM_CHAINS = [ CAIP_ETHEREUM_CHAIN_ID, CAIP_POLYGON_CHAIN_ID, @@ -53,9 +50,5 @@ export const metadata: ProviderMetadata = { ], }, }, - { - name: 'signers', - value: { getSigners: async () => getSigners(getInstanceOrThrow()) }, - }, ], }; diff --git a/wallets/provider-taho/src/namespaces/evm.ts b/wallets/provider-taho/src/namespaces/evm.ts index fe598b1aca..12e0fa219e 100644 --- a/wallets/provider-taho/src/namespaces/evm.ts +++ b/wallets/provider-taho/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, hooks } from '@hub3js/evm'; +import { actions, builders, hooks, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -43,19 +43,14 @@ const getAllowance = builders .action(actions.getAllowance(evmTaho)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmTaho)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmTaho)) .action(connect) .action(disconnect) .action(canEagerConnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-taho/src/provider.ts b/wallets/provider-taho/src/provider.ts index f1442810e5..64f9a334a8 100644 --- a/wallets/provider-taho/src/provider.ts +++ b/wallets/provider-taho/src/provider.ts @@ -1,11 +1,14 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; import { evm } from './namespaces/evm.js'; import { taho } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -17,5 +20,6 @@ const buildProvider = () => .config('metadata', metadata) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-taho/src/signer.ts b/wallets/provider-taho/src/signer.ts deleted file mode 100644 index 767e5ff5f0..0000000000 --- a/wallets/provider-taho/src/signer.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { Provider } from './types.js'; -import type { SignerFactory } from 'rango-types'; - -import { EVM_NAMESPACE } from '@hub3js/namespaces'; -import { DefaultSignerFactory, TransactionType } from 'rango-types'; - -export default async function getSigners( - provider: Provider -): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); - const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); - if (!!ethProvider) { - signers.registerSigner( - TransactionType.EVM, - new DefaultEvmSigner(ethProvider) - ); - } - return signers; -} diff --git a/wallets/provider-taho/src/utils.ts b/wallets/provider-taho/src/utils.ts index 8b9efd42da..6dc1e910e4 100644 --- a/wallets/provider-taho/src/utils.ts +++ b/wallets/provider-taho/src/utils.ts @@ -14,16 +14,6 @@ export function taho(): Provider | null { return instances; } -export function getInstanceOrThrow(): Provider { - const instances = taho(); - - if (!instances) { - throw new Error('Taho Wallet is not injected. Please check your wallet.'); - } - - return instances; -} - export function evmTaho(): EvmProviderApi { const instances = taho(); diff --git a/wallets/provider-tokenpocket/package.json b/wallets/provider-tokenpocket/package.json index 59a3157fa0..3c4fb6b148 100644 --- a/wallets/provider-tokenpocket/package.json +++ b/wallets/provider-tokenpocket/package.json @@ -22,19 +22,18 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "rango-types": "^0.6.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-tokenpocket/src/constants.ts b/wallets/provider-tokenpocket/src/constants.ts index 404fcfd1ab..d499fc4132 100644 --- a/wallets/provider-tokenpocket/src/constants.ts +++ b/wallets/provider-tokenpocket/src/constants.ts @@ -2,9 +2,6 @@ import type { ProviderMetadata } from '@hub3js/core'; import { isEvmNamespace } from '@hub3js/evm'; -import getSigners from './signer.js'; -import { getInstanceOrThrow } from './utils.js'; - export const WALLET_ID = 'token-pocket'; export const metadata: ProviderMetadata = { name: 'Token Pocket', @@ -31,9 +28,5 @@ export const metadata: ProviderMetadata = { ], }, }, - { - name: 'signers', - value: { getSigners: async () => getSigners(getInstanceOrThrow()) }, - }, ], }; diff --git a/wallets/provider-tokenpocket/src/namespaces/evm.ts b/wallets/provider-tokenpocket/src/namespaces/evm.ts index f6b3e610d6..536de4b882 100644 --- a/wallets/provider-tokenpocket/src/namespaces/evm.ts +++ b/wallets/provider-tokenpocket/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, hooks } from '@hub3js/evm'; +import { actions, builders, hooks, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -43,19 +43,14 @@ const getAllowance = builders .action(actions.getAllowance(evmTokenPocket)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmTokenPocket)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmTokenPocket)) .action(connect) .action(disconnect) .action(canEagerConnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-tokenpocket/src/provider.ts b/wallets/provider-tokenpocket/src/provider.ts index 58d0f1b3f8..3923c32c68 100644 --- a/wallets/provider-tokenpocket/src/provider.ts +++ b/wallets/provider-tokenpocket/src/provider.ts @@ -1,11 +1,14 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; import { evm } from './namespaces/evm.js'; import { tokenPocket } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -17,5 +20,6 @@ const buildProvider = () => .config('metadata', metadata) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-tokenpocket/src/signer.ts b/wallets/provider-tokenpocket/src/signer.ts deleted file mode 100644 index 767e5ff5f0..0000000000 --- a/wallets/provider-tokenpocket/src/signer.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { Provider } from './types.js'; -import type { SignerFactory } from 'rango-types'; - -import { EVM_NAMESPACE } from '@hub3js/namespaces'; -import { DefaultSignerFactory, TransactionType } from 'rango-types'; - -export default async function getSigners( - provider: Provider -): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); - const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); - if (!!ethProvider) { - signers.registerSigner( - TransactionType.EVM, - new DefaultEvmSigner(ethProvider) - ); - } - return signers; -} diff --git a/wallets/provider-tokenpocket/src/utils.ts b/wallets/provider-tokenpocket/src/utils.ts index a13014559b..7fce638f80 100644 --- a/wallets/provider-tokenpocket/src/utils.ts +++ b/wallets/provider-tokenpocket/src/utils.ts @@ -15,18 +15,6 @@ export function tokenPocket(): Provider | null { return instances; } -export function getInstanceOrThrow(): Provider { - const instances = tokenPocket(); - - if (!instances) { - throw new Error( - 'TokenPocket Wallet is not injected. Please check your wallet.' - ); - } - - return instances; -} - export function evmTokenPocket(): ProviderAPI { const instances = tokenPocket(); diff --git a/wallets/provider-tomo/package.json b/wallets/provider-tomo/package.json index 49d72fcdb1..5735f64779 100644 --- a/wallets/provider-tomo/package.json +++ b/wallets/provider-tomo/package.json @@ -22,19 +22,18 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "rango-types": "^0.6.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-tomo/src/constants.ts b/wallets/provider-tomo/src/constants.ts index 8a51a3cd6a..9ca59fbf28 100644 --- a/wallets/provider-tomo/src/constants.ts +++ b/wallets/provider-tomo/src/constants.ts @@ -2,9 +2,6 @@ import type { ProviderMetadata } from '@hub3js/core'; import { isEvmNamespace } from '@hub3js/evm'; -import getSigners from './signer.js'; -import { getInstanceOrThrow } from './utils.js'; - export const WALLET_ID = 'tomo'; export const TOMO_INJECTION_DELAY = 1000; export const metadata: ProviderMetadata = { @@ -32,11 +29,5 @@ export const metadata: ProviderMetadata = { ], }, }, - { - name: 'signers', - value: { - getSigners: async () => getSigners(getInstanceOrThrow()), - }, - }, ], }; diff --git a/wallets/provider-tomo/src/namespaces/evm.ts b/wallets/provider-tomo/src/namespaces/evm.ts index 9074644dd9..7284765a43 100644 --- a/wallets/provider-tomo/src/namespaces/evm.ts +++ b/wallets/provider-tomo/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { ActionBuilder, NamespaceBuilder } from '@hub3js/core'; -import { actions, builders } from '@hub3js/evm'; +import { actions, builders, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { connectAndUpdateStateForMultiNetworks, @@ -63,19 +63,14 @@ const getAllowance = builders .action(actions.getAllowance(evmTomo)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmTomo)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmTomo)) .action(connect) .action(disconnect) .action(canSwitchNetwork) .action(canEagerConnect) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-tomo/src/provider.ts b/wallets/provider-tomo/src/provider.ts index 9c2d1684d7..3eebb86c49 100644 --- a/wallets/provider-tomo/src/provider.ts +++ b/wallets/provider-tomo/src/provider.ts @@ -1,11 +1,14 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, TOMO_INJECTION_DELAY, WALLET_ID } from './constants.js'; import { evm } from './namespaces/evm.js'; import { tomo } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -19,5 +22,6 @@ const buildProvider = () => .config('metadata', metadata) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-tomo/src/signer.ts b/wallets/provider-tomo/src/signer.ts deleted file mode 100644 index d78f485552..0000000000 --- a/wallets/provider-tomo/src/signer.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { Provider } from './types.js'; -import type { SignerFactory } from 'rango-types'; - -import { EVM_NAMESPACE } from '@hub3js/namespaces'; -import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; - -export default async function getSigners( - provider: Provider -): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); - const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); - if (!!ethProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(ethProvider)); - } - return signers; -} diff --git a/wallets/provider-tomo/src/utils.ts b/wallets/provider-tomo/src/utils.ts index 042793681e..1dd0c90e94 100644 --- a/wallets/provider-tomo/src/utils.ts +++ b/wallets/provider-tomo/src/utils.ts @@ -1,4 +1,3 @@ -import type { Provider } from './types.js'; import type { ProviderAPI as EvmProviderApi } from '@hub3js/evm'; import { EVM_NAMESPACE } from '@hub3js/namespaces'; @@ -17,16 +16,6 @@ export function tomo() { return instances; } -export function getInstanceOrThrow(): Provider { - const instances = tomo(); - - if (!instances) { - throw new Error('Tomo is not injected. Please check your wallet.'); - } - - return instances; -} - export function evmTomo(): EvmProviderApi { const instances = tomo(); const evmInstance = instances?.get(EVM_NAMESPACE); diff --git a/wallets/provider-tonconnect/package.json b/wallets/provider-tonconnect/package.json index 8674c39959..f039c8884a 100644 --- a/wallets/provider-tonconnect/package.json +++ b/wallets/provider-tonconnect/package.json @@ -30,13 +30,13 @@ }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0", "@hub3js/tvm": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0", "@hub3js/tvm": "^0.6.0" }, diff --git a/wallets/provider-tonconnect/src/provider.ts b/wallets/provider-tonconnect/src/provider.ts index dc9652c0ee..7e29a0a03d 100644 --- a/wallets/provider-tonconnect/src/provider.ts +++ b/wallets/provider-tonconnect/src/provider.ts @@ -1,4 +1,5 @@ import type { Environments } from './types.js'; +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; import { ProviderBuilder } from '@hub3js/core'; @@ -6,7 +7,8 @@ import { metadata, WALLET_ID } from './constants.js'; import { ton } from './namespaces/ton.js'; import { tonConnect } from './utils.js'; -const buildProvider = () => +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => new ProviderBuilder(WALLET_ID) .init(function (context, environments: Environments) { const [, setState] = context.state(); diff --git a/wallets/provider-trezor/package.json b/wallets/provider-trezor/package.json index b55895a940..cea0dc707c 100644 --- a/wallets/provider-trezor/package.json +++ b/wallets/provider-trezor/package.json @@ -24,7 +24,6 @@ "dependencies": { "@bitcoinerlab/secp256k1": "^1.2.0", "@rango-dev/internal-blockchains": "^0.3.1-next.1", - "@rango-dev/signer-evm": "^0.47.0", "@trezor/connect-web": "^9.5.0", "bitcoinjs-lib": "^6.1.7", "ethers": "^6.13.2", @@ -33,13 +32,15 @@ "devDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-trezor/src/namespaces/evm.ts b/wallets/provider-trezor/src/namespaces/evm.ts index fe5f7b9a2a..50a41b37b3 100644 --- a/wallets/provider-trezor/src/namespaces/evm.ts +++ b/wallets/provider-trezor/src/namespaces/evm.ts @@ -1,28 +1,32 @@ import type { Context } from '@hub3js/core'; -import type { - AllowanceParams, - EvmActions, - EvmTransactionReceipt, -} from '@hub3js/evm'; +import type { AllowanceParams, EvmActions, EvmRpcUrls } from '@hub3js/evm'; import { Hub3Error, NamespaceBuilder } from '@hub3js/core'; -import { builders, utils } from '@hub3js/evm'; +import { builders, utils, viemPublicAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; -import { Contract, toBeHex } from 'ethers'; import { ETHEREUM_CHAIN_ID, WALLET_ID } from '../constants.js'; import { initTrezor } from '../init.js'; +import { sendTransaction, signMessage } from '../signers/ethereum.js'; import { setDerivationPath } from '../state.js'; import { getEthereumAccounts, - getEvmRpcProvider, getTrezorNormalizedDerivationPath, } from '../utils.js'; const ERC20_ALLOWANCE_ABI = [ - 'function allowance(address owner, address spender) view returns (uint256)', -]; + { + type: 'function', + name: 'allowance', + stateMutability: 'view', + inputs: [ + { name: 'owner', type: 'address' }, + { name: 'spender', type: 'address' }, + ], + outputs: [{ name: '', type: 'uint256' }], + }, +] as const; const connect = builders .connect() @@ -62,58 +66,38 @@ const getChainId = builders .build(); /* - * Trezor injects no EIP-1193 provider, so these read actions talk to the shared - * JSON-RPC provider directly rather than through the default hub3js/evm actions. + * Trezor injects no EIP-1193 provider, so the allowance is read with the public + * client's `readContract`, which `buildEvm` registers. */ const getAllowance = builders .getAllowance() .action( async ( - _context: Context, + context: Context, params: AllowanceParams ): Promise => { - const token = new Contract( - params.token, - ERC20_ALLOWANCE_ABI, - getEvmRpcProvider() - ); - const currentAllowance: bigint = await token.allowance( - params.owner, - params.spender - ); - return currentAllowance.toString(); - } - ) - .build(); - -const getTransactionReceipt = builders - .getTransactionReceipt() - .action( - async ( - _context: Context, - transactionHash: `0x${string}` - ): Promise => { - const receipt = await getEvmRpcProvider().getTransactionReceipt( - transactionHash - ); - if (!receipt) { - return null; - } - return { - status: receipt.status === 1 ? '0x1' : '0x0', - transactionHash: receipt.hash, - blockNumber: toBeHex(receipt.blockNumber), - }; + const allowance = (await context.action('readContract', { + address: params.token, + abi: ERC20_ALLOWANCE_ABI, + functionName: 'allowance', + args: [params.owner, params.spender], + })) as bigint; + return allowance.toString(); } ) .build(); -const evm = new NamespaceBuilder('EVM', WALLET_ID) - .action(connect) - .action(disconnect) - .action(getChainId) - .action(getAllowance) - .action(getTransactionReceipt) - .build(); +const buildEvm = (rpcUrls?: EvmRpcUrls) => + new NamespaceBuilder('EVM', WALLET_ID) + // No wallet RPC, so viem's public actions go to our RPC endpoints. + .action(viemPublicAdapter(rpcUrls)) + .action(connect) + .action(disconnect) + .action(getChainId) + .action(getAllowance) + // Signed on the device, see `signers/ethereum.ts`. + .action('sendTransaction', sendTransaction) + .action('signMessage', signMessage) + .build(); -export { evm }; +export { buildEvm }; diff --git a/wallets/provider-trezor/src/provider.ts b/wallets/provider-trezor/src/provider.ts index 381c697908..3b8d6dd8d5 100644 --- a/wallets/provider-trezor/src/provider.ts +++ b/wallets/provider-trezor/src/provider.ts @@ -1,17 +1,18 @@ import type { Environments } from './types.js'; +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; -import { evm } from './namespaces/evm.js'; +import { buildEvm } from './namespaces/evm.js'; import { utxo } from './namespaces/utxo.js'; let trezorManifest: Environments['manifest']; export const getTrezorManifest = () => trezorManifest; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +const buildProvider = (rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context, environments: Environments) { const [, setState] = context.state(); @@ -24,8 +25,9 @@ const buildProvider = () => console.debug('[trezor] instance detected.', context); }) .config('metadata', metadata) - .add('evm', evm) + .add('evm', buildEvm(rpcURLs?.evm)) .add('utxo', utxo) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-trezor/src/signer.ts b/wallets/provider-trezor/src/signer.ts index 5cc9f2a888..82da303112 100644 --- a/wallets/provider-trezor/src/signer.ts +++ b/wallets/provider-trezor/src/signer.ts @@ -4,9 +4,7 @@ import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; export default async function getSigners(): Promise { const signers = new DefaultSignerFactory(); - const { EthereumSigner } = await import('./signers/ethereum.js'); const { BTCSigner } = await import('./signers/utxo.js'); - signers.registerSigner(TxType.EVM, new EthereumSigner()); signers.registerSigner(TxType.TRANSFER, new BTCSigner()); return signers; } diff --git a/wallets/provider-trezor/src/signers/ethereum.ts b/wallets/provider-trezor/src/signers/ethereum.ts index 1d5e14b094..38b5507dd4 100644 --- a/wallets/provider-trezor/src/signers/ethereum.ts +++ b/wallets/provider-trezor/src/signers/ethereum.ts @@ -1,20 +1,31 @@ -import type { FeeData } from 'ethers'; -import type { EvmTransaction } from 'rango-types/mainApi'; +import type { Context, FunctionWithContext } from '@hub3js/core'; +import type { EvmActions } from '@hub3js/evm'; -import { - cleanEvmError, - getEthereumRpcUrl, - toHexQuantity, -} from '@rango-dev/signer-evm'; -import { JsonRpcProvider, Transaction } from 'ethers'; -import { type GenericSigner } from 'rango-types'; +import { Transaction } from 'ethers'; +import { ETHEREUM_CHAIN_ID } from '../constants.js'; import { getDerivationPath } from '../state.js'; import { getTrezorModule, trezorErrorMessages } from '../utils.js'; -/** Whether a transaction already prices itself under either scheme. */ -function hasGasPricing(tx: EvmTransaction): boolean { - return !!tx.gasPrice || (!!tx.maxFeePerGas && !!tx.maxPriorityFeePerGas); +type Pricing = { + gasPrice: bigint | null; + maxFeePerGas: bigint | null; + maxPriorityFeePerGas: bigint | null; +}; + +const ZERO = BigInt(0); + +const HEXADECIMAL_BASE = 16; + +/** TrezorConnect parses quantities as hex. */ +const toHexQuantity = (value: bigint | number): string => + `0x${value.toString(HEXADECIMAL_BASE)}`; + +function getAddress(account: unknown): `0x${string}` { + if (typeof account === 'string') { + return account as `0x${string}`; + } + return (account as { address: `0x${string}` }).address; } /** @@ -22,23 +33,29 @@ function hasGasPricing(tx: EvmTransaction): boolean { * exclusive in a signed transaction, so EIP-1559 is used wherever the chain * quotes it and a legacy price is the fallback. */ -function pricingFromFeeData(fees: FeeData) { - if (fees.maxFeePerGas && fees.maxPriorityFeePerGas) { +async function getPricingFromNode( + context: Context +): Promise { + try { + const fees = (await context.action('estimateFeesPerGas')) as { + maxFeePerGas: bigint; + maxPriorityFeePerGas: bigint; + }; return { gasPrice: null, - maxFeePerGas: fees.maxFeePerGas.toString(), - maxPriorityFeePerGas: fees.maxPriorityFeePerGas.toString(), + maxFeePerGas: fees.maxFeePerGas, + maxPriorityFeePerGas: fees.maxPriorityFeePerGas, + }; + } catch { + return { + gasPrice: (await context.action('getGasPrice')) as bigint, + maxFeePerGas: null, + maxPriorityFeePerGas: null, }; } - - return { - gasPrice: fees.gasPrice?.toString() ?? null, - maxFeePerGas: null, - maxPriorityFeePerGas: null, - }; } -export function getTrezorErrorMessage(error: unknown) { +function getTrezorErrorMessage(error: unknown) { if ( typeof error === 'object' && error !== null && @@ -51,119 +68,140 @@ export function getTrezorErrorMessage(error: unknown) { */ return new Error(error.shortMessage, { cause: error }); } - return cleanEvmError(error); + return error; } -export class EthereumSigner implements GenericSigner { - async signMessage(msg: string): Promise { +export const signMessage: FunctionWithContext< + EvmActions['signMessage'], + Context +> = async (_context, params) => { + const message = params?.message; + if (typeof message !== 'string') { + throw new Error('Trezor can only sign text messages.'); + } + + const TrezorConnect = await getTrezorModule(); + + const { success, payload } = await TrezorConnect.ethereumSignMessage({ + message, + path: getDerivationPath(), + }); + if (!success) { + throw new Error(payload.error); + } + return payload.signature as `0x${string}`; +}; + +/** + * Trezor has no injected provider: the transaction is completed through the + * namespace's public client, signed on the device, then broadcast. + */ +export const sendTransaction: FunctionWithContext< + EvmActions['sendTransaction'], + Context +> = async (context, request) => { + if (!request) { + throw new Error('A transaction is required.'); + } + const from = getAddress(request.account); + const { to, data, value } = request; + + try { const TrezorConnect = await getTrezorModule(); - const { success, payload } = await TrezorConnect.ethereumSignMessage({ - message: msg, + const nonce = + request.nonce ?? + ((await context.action('getTransactionCount', { + address: from, + })) as number); + + /* + * Trezor signs a raw transaction on-device and does not estimate gas, so + * a limit has to be present. Server-built transactions arrive with one; + * client-built ones - approve prerequisites among them - do not, so it is + * estimated here. Everything else is taken as the transaction sends it. + */ + const gasLimit = + request.gas ?? + ((await context.action('estimateGas', { + account: from, + to, + data, + value, + })) as bigint); + + /* + * Whatever pricing the transaction came with wins - a server-built one + * always carries it, and it is signed with exactly what it was created + * with. Only a client-built transaction, which leaves both schemes null, + * is priced from the node. + */ + const hasPricing = + !!request.gasPrice || + (!!request.maxFeePerGas && !!request.maxPriorityFeePerGas); + const pricing: Pricing = hasPricing + ? { + gasPrice: request.gasPrice ?? null, + maxFeePerGas: request.maxFeePerGas ?? null, + maxPriorityFeePerGas: request.maxPriorityFeePerGas ?? null, + } + : await getPricingFromNode(context); + + const isEIP1559 = !!pricing.maxFeePerGas && !!pricing.maxPriorityFeePerGas; + + if (!isEIP1559 && !pricing.gasPrice) { + throw new Error('Missing gasPrice'); + } + + const additionalFields = isEIP1559 + ? { + maxFeePerGas: toHexQuantity(pricing.maxFeePerGas ?? ZERO), + maxPriorityFeePerGas: toHexQuantity( + pricing.maxPriorityFeePerGas ?? ZERO + ), + } + : { + gasPrice: toHexQuantity(pricing.gasPrice ?? ZERO), + }; + + const transaction = { + to: to ?? null, + data: data ?? '0x', + value: toHexQuantity(value ?? ZERO), + gasLimit: toHexQuantity(gasLimit), + chainId: Number(ETHEREUM_CHAIN_ID), + nonce: toHexQuantity(nonce), + ...additionalFields, + }; + + const { success, payload } = await TrezorConnect.ethereumSignTransaction({ path: getDerivationPath(), + transaction, }); + if (!success) { - throw new Error(payload.error); + const errorMessage = + trezorErrorMessages[payload?.code || ''] || payload.error; + throw new Error(errorMessage); } - return payload.signature; - } - - async signAndSendTx( - tx: EvmTransaction, - fromAddress: string, - chainId: string - ): Promise<{ hash: string }> { - try { - const TrezorConnect = await getTrezorModule(); - const provider = new JsonRpcProvider(getEthereumRpcUrl()); // Provider to broadcast transaction - const transactionCount = await provider.getTransactionCount(fromAddress); // Get nonce + const { r, s, v } = payload; + const serializedTx = Transaction.from({ + ...transaction, + nonce: Number.parseInt(transaction.nonce), /* - * Trezor signs a raw transaction on-device and does not estimate gas, so - * a limit has to be present. Server-built transactions arrive with one; - * client-built ones - approve prerequisites among them - do not, so it is - * estimated here. Everything else is taken as the transaction sends it. + * Type 0: This refers to the legacy transaction type that has been used since Ethereum's inception. + * Type 2: This refers to the new transaction type introduced with the EIP-1559 (Ethereum Improvement Proposal 1559) update, + * which was part of the London hard fork. */ - const gasLimit = - tx.gasLimit ?? - ( - await provider.estimateGas({ - from: fromAddress, - to: tx.to, - data: tx.data ?? undefined, - value: tx.value ?? undefined, - }) - ).toString(); - /* - * Whatever pricing the transaction came with wins - a server-built one - * always carries it, and it is signed with exactly what it was created - * with. Only a client-built transaction, which leaves both schemes null, - * is priced from the node. - */ - const pricing = hasGasPricing(tx) - ? { - gasPrice: tx.gasPrice, - maxFeePerGas: tx.maxFeePerGas, - maxPriorityFeePerGas: tx.maxPriorityFeePerGas, - } - : pricingFromFeeData(await provider.getFeeData()); - - const isEIP1559 = - !!pricing.maxFeePerGas && !!pricing.maxPriorityFeePerGas; - - if (!isEIP1559 && !pricing.gasPrice) { - throw new Error('Missing gasPrice'); - } - - const additionalFields = isEIP1559 - ? { - maxFeePerGas: toHexQuantity(pricing.maxFeePerGas || '0'), - maxPriorityFeePerGas: toHexQuantity( - pricing.maxPriorityFeePerGas || '0' - ), - } - : { - gasPrice: toHexQuantity(pricing.gasPrice || '0'), - }; - - const transaction = { - to: tx.to, - data: tx.data || '0x', - value: toHexQuantity(tx.value?.toString() || '0'), - gasLimit: toHexQuantity(gasLimit), - chainId: Number.parseInt(chainId), - nonce: toHexQuantity(transactionCount.toString()), - ...additionalFields, - }; - - const { success, payload } = await TrezorConnect.ethereumSignTransaction({ - path: getDerivationPath(), - transaction, - }); - - if (!success) { - const errorMessage = - trezorErrorMessages[payload?.code || ''] || payload.error; - throw new Error(errorMessage); - } - const { r, s, v } = payload; - - const serializedTx = Transaction.from({ - ...transaction, - nonce: Number.parseInt(transaction.nonce), - /* - * Type 0: This refers to the legacy transaction type that has been used since Ethereum's inception. - * Type 2: This refers to the new transaction type introduced with the EIP-1559 (Ethereum Improvement Proposal 1559) update, - * which was part of the London hard fork. - */ - type: isEIP1559 ? 2 : 0, - signature: { r, s, v: parseInt(v) }, - }).serialized; - const broadcastResult = await provider.broadcastTransaction(serializedTx); - - return { hash: broadcastResult.hash }; - } catch (error) { - throw getTrezorErrorMessage(error); - } + type: isEIP1559 ? 2 : 0, + signature: { r, s, v: parseInt(v) }, + }).serialized as `0x${string}`; + + return (await context.action('sendRawTransaction', { + serializedTransaction: serializedTx, + })) as `0x${string}`; + } catch (error) { + throw getTrezorErrorMessage(error); } -} +}; diff --git a/wallets/provider-trezor/src/utils.ts b/wallets/provider-trezor/src/utils.ts index 8b0c7ca058..6ad9d0d960 100644 --- a/wallets/provider-trezor/src/utils.ts +++ b/wallets/provider-trezor/src/utils.ts @@ -1,8 +1,6 @@ import type { TrezorConnect } from '@trezor/connect-web'; import { Hub3Error } from '@hub3js/core'; -import { getEthereumRpcUrl } from '@rango-dev/signer-evm'; -import { JsonRpcProvider } from 'ethers'; import { ETHEREUM_CHAIN_ID, @@ -16,23 +14,6 @@ type DeviceAccounts = { derivationPath: string; }; -/** - * Trezor EVM is Ethereum-only today and has no injected provider, so a single - * JSON-RPC provider over the Ethereum endpoint serves both the signer (nonce + - * broadcast) and the read-only namespace actions (allowance, receipt). - * - * NOTE: If Trezor EVM support ever expands beyond Ethereum, this must select - * the RPC per chain instead of the single Ethereum endpoint. - */ -let evmRpcProvider: { url: string; provider: JsonRpcProvider } | undefined; -export function getEvmRpcProvider(): JsonRpcProvider { - const url = getEthereumRpcUrl(); - if (evmRpcProvider?.url !== url) { - evmRpcProvider = { url, provider: new JsonRpcProvider(url) }; - } - return evmRpcProvider.provider; -} - // Trezor resolves a failed connect call instead of throwing; its `code`, not its `error` text, says whether the user cancelled. export function throwTrezorConnectionError(payload: { error: string; diff --git a/wallets/provider-tron-link/package.json b/wallets/provider-tron-link/package.json index e4960533b7..133e36718f 100644 --- a/wallets/provider-tron-link/package.json +++ b/wallets/provider-tron-link/package.json @@ -27,13 +27,13 @@ }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0", "@hub3js/tron": "^0.3.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0", "@hub3js/tron": "^0.3.0" }, diff --git a/wallets/provider-tron-link/src/provider.ts b/wallets/provider-tron-link/src/provider.ts index 821d95744e..740112f789 100644 --- a/wallets/provider-tron-link/src/provider.ts +++ b/wallets/provider-tron-link/src/provider.ts @@ -1,10 +1,13 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, TRONLINK_INJECTION_DELAY, WALLET_ID } from './constants.js'; import { tron } from './namespaces/tron.js'; import { tronlink } from './utils.js'; -const buildProvider = () => +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); diff --git a/wallets/provider-trustwallet/package.json b/wallets/provider-trustwallet/package.json index 32a8c746b9..92ad9c9637 100644 --- a/wallets/provider-trustwallet/package.json +++ b/wallets/provider-trustwallet/package.json @@ -22,22 +22,21 @@ "lint": "eslint \"**/*.{ts,tsx}\"" }, "dependencies": { - "@rango-dev/signer-evm": "^0.47.1", "@rango-dev/signer-solana": "^0.51.1-next.0", "bs58": "^5.0.0", "rango-types": "^0.6.0" }, "devDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0" }, diff --git a/wallets/provider-trustwallet/src/namespaces/evm.ts b/wallets/provider-trustwallet/src/namespaces/evm.ts index 2bf96bee03..23f30a7616 100644 --- a/wallets/provider-trustwallet/src/namespaces/evm.ts +++ b/wallets/provider-trustwallet/src/namespaces/evm.ts @@ -1,7 +1,7 @@ import type { EvmActions } from '@hub3js/evm'; import { NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, hooks } from '@hub3js/evm'; +import { actions, builders, hooks, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -41,18 +41,13 @@ const getAllowance = builders .action(actions.getAllowance(evmTrustWallet)) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action(actions.getTransactionReceipt(evmTrustWallet)) - .build(); - const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(evmTrustWallet)) .action(connect) .action(disconnect) .action(canSwitchNetwork) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-trustwallet/src/provider.ts b/wallets/provider-trustwallet/src/provider.ts index 860573aef3..54f38f2f94 100644 --- a/wallets/provider-trustwallet/src/provider.ts +++ b/wallets/provider-trustwallet/src/provider.ts @@ -1,3 +1,5 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; @@ -5,8 +7,9 @@ import { evm } from './namespaces/evm.js'; import { solana } from './namespaces/solana.js'; import { trustWallet as trustwalletInstance } from './utils.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); @@ -19,5 +22,6 @@ const buildProvider = () => .add('evm', evm) .add('solana', solana) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-trustwallet/src/signer.ts b/wallets/provider-trustwallet/src/signer.ts index f1669bbd56..74b254ec86 100644 --- a/wallets/provider-trustwallet/src/signer.ts +++ b/wallets/provider-trustwallet/src/signer.ts @@ -1,22 +1,17 @@ import type { Provider } from './utils.js'; import type { SignerFactory } from 'rango-types'; -import { EVM_NAMESPACE, SOLANA_NAMESPACE } from '@hub3js/namespaces'; +import { SOLANA_NAMESPACE } from '@hub3js/namespaces'; import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; export default async function getSigners( provider: Provider ): Promise { - const ethProvider = provider.get(EVM_NAMESPACE); const solProvider = provider.get(SOLANA_NAMESPACE); const signers = new DefaultSignerFactory(); - const { DefaultEvmSigner } = await import('@rango-dev/signer-evm'); const { CustomSolanaSigner } = await import('./signers/solanaSigner.js'); - if (!!ethProvider) { - signers.registerSigner(TxType.EVM, new DefaultEvmSigner(ethProvider)); - } if (!!solProvider) { signers.registerSigner(TxType.SOLANA, new CustomSolanaSigner(solProvider)); } diff --git a/wallets/provider-unisat/package.json b/wallets/provider-unisat/package.json index c35bf6af2c..c306d70f86 100644 --- a/wallets/provider-unisat/package.json +++ b/wallets/provider-unisat/package.json @@ -30,13 +30,13 @@ "devDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-unisat/src/provider.ts b/wallets/provider-unisat/src/provider.ts index 46ced3f849..3c5a90b2e2 100644 --- a/wallets/provider-unisat/src/provider.ts +++ b/wallets/provider-unisat/src/provider.ts @@ -1,10 +1,13 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID } from './constants.js'; import { utxo } from './namespaces/utxo.js'; import { unisat as unisatInstance } from './utils.js'; -const buildProvider = () => +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); diff --git a/wallets/provider-vultisig/package.json b/wallets/provider-vultisig/package.json index 5904c40f56..79c9fe571b 100644 --- a/wallets/provider-vultisig/package.json +++ b/wallets/provider-vultisig/package.json @@ -28,13 +28,13 @@ "devDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-vultisig/src/provider.ts b/wallets/provider-vultisig/src/provider.ts index 43d476fbc2..5c26020f71 100644 --- a/wallets/provider-vultisig/src/provider.ts +++ b/wallets/provider-vultisig/src/provider.ts @@ -1,10 +1,13 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { info, WALLET_ID } from './constants.js'; import { namespace as utxo } from './namespaces/utxo/namespace.js'; import { vultisig } from './utils.js'; -const buildProvider = () => +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); diff --git a/wallets/provider-walletconnect-2/package.json b/wallets/provider-walletconnect-2/package.json index 05526aad3a..64f4ffa119 100644 --- a/wallets/provider-walletconnect-2/package.json +++ b/wallets/provider-walletconnect-2/package.json @@ -25,8 +25,7 @@ "@bitcoinerlab/secp256k1": "^1.2.0", "@rango-dev/internal-blockchains": "^0.3.1-next.1", "@rango-dev/logging-core": "^0.16.1-next.1", - "@rango-dev/signer-evm": "^0.47.0", - "@reown/appkit": "1.8.20", + "@reown/appkit": "1.8.24", "@walletconnect/encoding": "^1.0.2", "@walletconnect/sign-client": "2.23.7", "@walletconnect/universal-provider": "2.23.7", @@ -40,14 +39,16 @@ "devDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0", "@walletconnect/types": "2.23.7" }, "peerDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-walletconnect-2/src/adapter/adapter.ts b/wallets/provider-walletconnect-2/src/adapter/adapter.ts index 4114806149..7041ec6eb6 100644 --- a/wallets/provider-walletconnect-2/src/adapter/adapter.ts +++ b/wallets/provider-walletconnect-2/src/adapter/adapter.ts @@ -1,16 +1,12 @@ import type { WalletConnectNamespace } from '../types.js'; -import type { - AllowanceParams, - Chain, - EvmTransactionReceipt, -} from '@hub3js/evm'; +import type { AllowanceParams, Chain, ProviderAPI } from '@hub3js/evm'; import type { SessionTypes } from '@walletconnect/types'; import type UniversalProvider from '@walletconnect/universal-provider'; import type { BlockchainMeta } from 'rango-types'; import { utils } from '@hub3js/evm'; import { debug } from '@rango-dev/logging-core'; -import { JsonRpcProvider, toBeHex } from 'ethers'; +import { JsonRpcProvider } from 'ethers'; import { ensureConnectedToChain as ensureConnectedToChainHelper, @@ -58,6 +54,29 @@ export interface WalletConnectAdapterConfig { modalZIndex?: number; } +/** + * Attaches the session's namespaces and peer metadata, and the wallet's error + * code, to an error a relayed request failed with. + */ +function withSessionContext(error: unknown, session: SessionTypes.Struct) { + const wrapped = + error instanceof Error + ? error + : Object.assign( + new Error( + (error as { message?: string } | null)?.message ?? String(error) + ), + { code: (error as { code?: unknown } | null)?.code } + ); + return Object.assign(wrapped, { + context: { + namespaces: session.namespaces, + peering: session.peer?.metadata, + code: (error as { code?: unknown } | null)?.code, + }, + }); +} + export class WalletConnectAdapter { readonly #projectId: string; readonly #disableModalLink?: string; @@ -147,21 +166,57 @@ export class WalletConnectAdapter { return BigInt(result === '0x' ? 0 : result).toString(); } - /** Reads a transaction receipt from the active chain's node. */ - async getTransactionReceipt( - txHash: `0x${string}` - ): Promise { - const provider = await this.#getRpcProvider(); - const receipt = await provider.getTransactionReceipt(txHash); - if (!receipt) { - return null; - } + /** + * An EIP-1193 view of the EVM session, for viem and hub3's EVM actions. + * + * The methods the session negotiated go to the wallet over the relay, on the + * session's active chain. Everything else (reads such as + * `eth_getTransactionReceipt`) goes to a node for that chain, for the reasons + * given on `#getRpcProvider`. + */ + getEip1193Provider(): ProviderAPI { + const request = async ({ + method, + params, + }: { + method: string; + params?: unknown; + }): Promise => { + const session = this.getSession('evm'); + const negotiatedMethods = + session?.namespaces[NAMESPACES.ETHEREUM]?.methods; + + if (session && negotiatedMethods?.includes(method)) { + const reference = await this.resolveActiveChainReference(); + if (!reference) { + throw new Error( + 'Unable to determine EVM chain id from WalletConnect session.' + ); + } + + try { + return await ( + await this.getClient() + ).request({ + topic: session.topic, + chainId: `${NAMESPACES.ETHEREUM}:${reference}`, + request: { method, params }, + }); + } catch (error) { + /* + * Tells the logs which wallet app the session is with. queue-manager + * passes it on as the signer error's context. + */ + throw withSessionContext(error, session); + } + } - return { - status: receipt.status === 1 ? '0x1' : '0x0', - transactionHash: receipt.hash, - blockNumber: toBeHex(receipt.blockNumber), + const provider = await this.#getRpcProvider(); + return provider.send(method, (params as unknown[] | undefined) ?? []); }; + + // Session events reach the namespace through its own hooks, not this view. + return { request } as unknown as ProviderAPI; } getSession(namespace: WalletConnectNamespace): SessionTypes.Struct | null { diff --git a/wallets/provider-walletconnect-2/src/constants.ts b/wallets/provider-walletconnect-2/src/constants.ts index 598e2b2918..51ac3d696c 100644 --- a/wallets/provider-walletconnect-2/src/constants.ts +++ b/wallets/provider-walletconnect-2/src/constants.ts @@ -4,8 +4,6 @@ import { EIP1193_USER_REJECTED_REQUEST } from '@hub3js/core'; import { isEvmNamespace } from '@hub3js/evm'; import { getSdkError } from '@walletconnect/utils'; -import getSigners from './signer.js'; - export const WALLET_ID = 'wallet-connect-2'; // The documented codes a wallet answers a session proposal with when the user rejects it, plus the EIP-1193 code some wallets answer with instead. @@ -36,10 +34,6 @@ export const metadata: ProviderMetadata = { ], }, }, - { - name: 'signers', - value: { getSigners: async () => getSigners() }, - }, { name: 'details', value: { diff --git a/wallets/provider-walletconnect-2/src/namespaces/evm/namespace.ts b/wallets/provider-walletconnect-2/src/namespaces/evm/namespace.ts index fe1d94c087..4d505e2df3 100644 --- a/wallets/provider-walletconnect-2/src/namespaces/evm/namespace.ts +++ b/wallets/provider-walletconnect-2/src/namespaces/evm/namespace.ts @@ -1,12 +1,8 @@ import type { Context } from '@hub3js/core'; -import type { - AllowanceParams, - EvmActions, - EvmTransactionReceipt, -} from '@hub3js/evm'; +import type { AllowanceParams, EvmActions } from '@hub3js/evm'; import { getErrorMessage, Hub3Error, NamespaceBuilder } from '@hub3js/core'; -import { actions, builders, utils } from '@hub3js/evm'; +import { actions, builders, utils, viemWalletAdapter } from '@hub3js/evm'; import * as commonBuilders from '@hub3js/std/builders'; import { standardizeAndThrowError } from '@hub3js/std/operators'; @@ -126,25 +122,16 @@ const getAllowance = builders ) .build(); -const getTransactionReceipt = builders - .getTransactionReceipt() - .action( - async ( - _context: Context, - txHash: `0x${string}` - ): Promise => - getAdapter().getTransactionReceipt(txHash) - ) - .build(); +const getEip1193Provider = () => getAdapter().getEip1193Provider(); const evm = new NamespaceBuilder('EVM', WALLET_ID) + .action(viemWalletAdapter(getEip1193Provider)) .action(connect) .action(canEagerConnect) .action(canSwitchNetwork) .action(disconnect) .action(getChainId) .action(getAllowance) - .action(getTransactionReceipt) .build(); export { evm }; diff --git a/wallets/provider-walletconnect-2/src/provider.ts b/wallets/provider-walletconnect-2/src/provider.ts index 74b0a003ef..a35392ca43 100644 --- a/wallets/provider-walletconnect-2/src/provider.ts +++ b/wallets/provider-walletconnect-2/src/provider.ts @@ -1,4 +1,5 @@ import type { Environments } from './types.js'; +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; import { ProviderBuilder } from '@hub3js/core'; @@ -7,8 +8,9 @@ import { setAdapter } from './adapter/registry.js'; import { metadata, WALLET_ID } from './constants.js'; import { evm } from './namespaces/evm/namespace.js'; -const buildProvider = () => - new ProviderBuilder(WALLET_ID) +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => { + return new ProviderBuilder(WALLET_ID) .init(function (context, environments: Environments) { const [, setState] = context.state(); @@ -31,5 +33,6 @@ const buildProvider = () => .config('metadata', metadata) .add('evm', evm) .build(); +}; export { buildProvider }; diff --git a/wallets/provider-walletconnect-2/src/signer.ts b/wallets/provider-walletconnect-2/src/signer.ts deleted file mode 100644 index ca80e28856..0000000000 --- a/wallets/provider-walletconnect-2/src/signer.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { SignerFactory } from 'rango-types'; - -import { DefaultSignerFactory, TransactionType as TxType } from 'rango-types'; - -import { getAdapter } from './adapter/registry.js'; - -export default async function getSigners(): Promise { - const adapter = getAdapter(); - if (!adapter) { - throw new Error('WalletConnect provider has not been initialized.'); - } - - const client = await adapter.getClient(); - - const signers = new DefaultSignerFactory(); - const EVMSigner = (await import('./signers/evm.js')).default; - signers.registerSigner( - TxType.EVM, - new EVMSigner(client, () => adapter.getSession('evm')) - ); - - return signers; -} diff --git a/wallets/provider-walletconnect-2/src/signers/evm.ts b/wallets/provider-walletconnect-2/src/signers/evm.ts deleted file mode 100644 index 2f4b12b137..0000000000 --- a/wallets/provider-walletconnect-2/src/signers/evm.ts +++ /dev/null @@ -1,221 +0,0 @@ -import type { ISignClient, SessionTypes } from '@walletconnect/types'; -import type { EvmTransaction } from 'rango-types/mainApi'; - -import { cleanEvmError, toHexQuantity } from '@rango-dev/signer-evm'; -import { AccountId, ChainId } from 'caip'; -import { type GenericSigner } from 'rango-types'; - -import { utf8ToHex } from '../utils.js'; -import { EthereumRPCMethods, NAMESPACES } from '../wcConstants.js'; - -const NAMESPACE_NAME = NAMESPACES.ETHEREUM; - -type SessionGetter = () => SessionTypes.Struct | null; - -type WalletConnectEvmTx = { - from?: string; - to?: string; - data: string; - value: string; - gas?: string; - gasPrice?: string; - maxFeePerGas?: string; - maxPriorityFeePerGas?: string; - nonce?: string; -}; - -class EVMSigner implements GenericSigner { - private client: ISignClient; - private getSession: SessionGetter; - - constructor(client: ISignClient, getSession: SessionGetter) { - this.client = client; - this.getSession = getSession; - } - - private get session(): SessionTypes.Struct { - const session = this.getSession(); - if (!session) { - throw new Error('EVM WalletConnect session is not available.'); - } - return session; - } - - /** - * Map Rango's EvmTransaction to WalletConnect eth_sendTransaction params. - * - * Unlike DefaultEvmSigner.buildTx (ethers TransactionRequest with gasLimit + - * decimal fee strings), WC sends params raw over the relay. Wallets like - * Ledger Live parse QUANTITY as hex, so decimal fees get inflated (~40x+). - * - * This builder: - * - uses `gas` (JSON-RPC), not ethers' `gasLimit` - * - hex-encodes gas, fees, value, and nonce - */ - static buildTx(evmTx: EvmTransaction): WalletConnectEvmTx { - const tx: WalletConnectEvmTx = { - data: evmTx.data || '0x', - /* - * Approvals and many contract calls have value=null from the API. - * Some WC wallets reject missing value; send 0x0 explicitly. - */ - value: evmTx.value ? toHexQuantity(evmTx.value) : '0x0', - }; - - if (evmTx.from) { - tx.from = evmTx.from; - } - if (evmTx.to) { - tx.to = evmTx.to; - } - if (evmTx.nonce) { - tx.nonce = toHexQuantity(evmTx.nonce); - } - if (evmTx.gasLimit) { - tx.gas = toHexQuantity(evmTx.gasLimit); - } - if (evmTx.maxFeePerGas && evmTx.maxPriorityFeePerGas) { - tx.maxFeePerGas = toHexQuantity(evmTx.maxFeePerGas); - tx.maxPriorityFeePerGas = toHexQuantity(evmTx.maxPriorityFeePerGas); - } else if (evmTx.gasPrice) { - tx.gasPrice = toHexQuantity(evmTx.gasPrice); - } - - return tx; - } - - public async signMessage( - msg: string, - address: string, - chainId: string | null - ): Promise { - const requestedFor = this.isNetworkAndAccountExistInSession({ - address, - chainId, - }); - - const caipChainId = new ChainId({ - namespace: NAMESPACE_NAME, - reference: requestedFor.chainId, - }); - const hexMsg = utf8ToHex(msg, true); - - const params = [hexMsg, address]; - - let signature: string; - try { - // Send message to wallet (using relayer) - signature = await this.client.request({ - topic: this.session.topic, - chainId: caipChainId.toString(), - request: { - method: EthereumRPCMethods.PERSONAL_SIGN, - params, - }, - }); - } catch (error) { - throw cleanEvmError(error); - } - - /* - * TODO: We can also verify the signature here - * Check web-examples: dapps/react-dapp-v2/src/contexts/JsonRpcContext.tsx - */ - - return signature; - } - - async signAndSendTx( - tx: EvmTransaction, - address: string, - chainId: string | null - ): Promise<{ hash: string }> { - try { - const requestedFor = this.isNetworkAndAccountExistInSession({ - address, - chainId, - }); - const transaction = EVMSigner.buildTx(tx); - const hash: string = await this.client.request({ - topic: this.session.topic, - chainId: requestedFor.caipChainId, - request: { - method: EthereumRPCMethods.SEND_TRANSACTION, - params: [transaction], - }, - }); - // Some wallets e.g. Rainbow wallet are returning invalid hash (e.g. 'null') in case of the rejection - if (!hash?.startsWith('0x')) { - throw new Error( - `Received an invalid hash on signing the transaction. (hash=${hash})` - ); - } - - return { - hash, - }; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } catch (error: any) { - const modifiedError = cleanEvmError(error); - const session = this.session; - const context = { - namspaces: session?.namespaces, - peering: session?.peer?.metadata, - code: error?.code, - }; - modifiedError.context = context; - throw modifiedError; - } - } - - private isNetworkAndAccountExistInSession(requestedFor: { - address: string; - chainId: string | null; - }) { - const { address, chainId } = requestedFor; - - if (!chainId) { - throw new Error( - 'You need to set your chain for signing message/transaction.' - ); - } - - /* - * TODO: We need to make sure we are using a single format for chain ids, it should be hex or number. - * This is a quick fix for evm. - */ - const chainIdNumber = chainId.startsWith('0x') - ? String(parseInt(chainId)) - : chainId; - - const caipAddress = new AccountId({ - chainId: { - namespace: NAMESPACE_NAME, - reference: chainIdNumber, - }, - address, - }); - const addresses = this.session.namespaces[NAMESPACE_NAME]?.accounts.map( - (address) => address.toLowerCase() - ); - - if (!addresses || !addresses.includes(caipAddress.toString())) { - throw new Error( - `Your requested address doesn't exist on your wallect connect session. Please reconnect your wallet.` - ); - } - - const caipChainId = new ChainId({ - namespace: NAMESPACE_NAME, - reference: chainIdNumber, - }); - - return { - chainId: chainIdNumber, - address, - caipChainId: caipChainId.toString(), - }; - } -} - -export default EVMSigner; diff --git a/wallets/provider-walletconnect-2/src/utils.ts b/wallets/provider-walletconnect-2/src/utils.ts index eebc749b43..1da8ff258e 100644 --- a/wallets/provider-walletconnect-2/src/utils.ts +++ b/wallets/provider-walletconnect-2/src/utils.ts @@ -23,14 +23,6 @@ export async function timeout( return Promise.race([forPromise, timeoutPromise]); } -export function utf8ToHex(value: string, prefixed = false): string { - const hex = Array.from(new TextEncoder().encode(value)) - .map((byte) => byte.toString(HEX_RADIX).padStart(2, '0')) - .join(''); - - return prefixed ? `0x${hex}` : hex; -} - /** Normalizes hub chain input (hex, decimal, or AddEthereumChainParameter) to a decimal reference. */ export function parseChainReference( chain?: string | Chain diff --git a/wallets/provider-xverse/package.json b/wallets/provider-xverse/package.json index 65a635959b..a21b2f93aa 100644 --- a/wallets/provider-xverse/package.json +++ b/wallets/provider-xverse/package.json @@ -28,13 +28,13 @@ "devDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "peerDependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/std": "^0.6.0" }, "publishConfig": { diff --git a/wallets/provider-xverse/src/provider.ts b/wallets/provider-xverse/src/provider.ts index 977ffad2c2..4286416737 100644 --- a/wallets/provider-xverse/src/provider.ts +++ b/wallets/provider-xverse/src/provider.ts @@ -1,10 +1,13 @@ +import type { NamespacesRPCUrls } from '@hub3js/namespaces'; + import { ProviderBuilder } from '@hub3js/core'; import { metadata, WALLET_ID, XVERSE_INJECTION_DELAY_MS } from './constants.js'; import { utxo } from './namespaces/utxo.js'; import { xverse as unisatInstance } from './utils.js'; -const buildProvider = () => +// RPC URLs are accepted for every namespace, so any of them can start using one. +const buildProvider = (_rpcURLs?: NamespacesRPCUrls) => new ProviderBuilder(WALLET_ID) .init(function (context) { const [, setState] = context.state(); diff --git a/wallets/react/package.json b/wallets/react/package.json index aae1688064..02f16f94fd 100644 --- a/wallets/react/package.json +++ b/wallets/react/package.json @@ -33,8 +33,8 @@ "dependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/std": "^0.6.0", "@hub3js/sui": "^0.6.0", diff --git a/wallets/react/src/hub/useHubAdapter.ts b/wallets/react/src/hub/useHubAdapter.ts index 655e904b7d..b928a12aff 100644 --- a/wallets/react/src/hub/useHubAdapter.ts +++ b/wallets/react/src/hub/useHubAdapter.ts @@ -34,7 +34,6 @@ import { LastConnectedWalletsFromStorage } from './lastConnectedWallets.js'; import { useAutoConnect } from './useAutoConnect.js'; import { useHubRefs } from './useHubRefs.js'; import { - findProviderByType, isEvmNamespace, isSolanaNamespace, isUtxoNamespace, @@ -562,7 +561,12 @@ export function useHubAdapter(params: UseAdapterParams): ProviderContext { ); }, hubProvider(type) { - const provider = findProviderByType(params.providers, type); + /* + * Return the instance registered in the hub, which holds the store. A + * provider list can be rebuilt with the same ids, and the hub keeps the + * instances it registered first, so a rebuilt one would have no store. + */ + const provider = getHub().get(type); if (!provider) { throw new Error( diff --git a/wallets/readme.md b/wallets/readme.md index 5b86cc69c8..82323d8f8f 100644 --- a/wallets/readme.md +++ b/wallets/readme.md @@ -35,9 +35,14 @@ After adding the dependencies, you can use them. Using all supported wallets (`p ```js import { Provider } from '@rango-dev/wallets-react'; -import { allProviders } from '@rango-dev/provider-all'; +import { allProviders, toNamespacesRPCUrls } from '@rango-dev/provider-all'; -const providers = allProviders().map((build) => build()); +// Optional. Wallets without an RPC of their own (Ledger, Trezor) read each EVM +// chain through these urls, keyed by chain id. No url is built in. +const rpcURLs = toNamespacesRPCUrls({ + evm: { 1: ['https://your-ethereum-rpc'], 56: ['https://your-bsc-rpc'] }, +}); +const providers = allProviders().map((build) => build(rpcURLs)); export function App() { const blockchains = [...] // An array of blockchains @@ -56,8 +61,16 @@ or some specific wallets: import { Provider } from '@rango-dev/wallets-react'; import { buildProvider as metamask } from '@rango-dev/provider-metamask'; import { buildProvider as phantom } from '@rango-dev/provider-phantom'; - -const providers = [metamask(), phantom()]; +import { mainnet } from 'viem/chains'; + +// RPC endpoints per namespace, shared by every provider. They're optional: +// wallets with their own RPC (e.g. MetaMask) don't need them, while wallets +// without one (Ledger, Trezor) read from them and reject reads on chains +// without urls. +const rpcURLs = { + evm: [{ chain: mainnet, rpcUrls: ['https://your-ethereum-rpc'] }], +}; +const providers = [metamask(rpcURLs), phantom()]; export function App() { const blockchains = [...] // An array of blockchains diff --git a/widget/app/src/App.tsx b/widget/app/src/App.tsx index fca2fdbcc3..f6b5f4263e 100644 --- a/widget/app/src/App.tsx +++ b/widget/app/src/App.tsx @@ -5,6 +5,7 @@ import React, { useRef } from 'react'; import { Route, Routes, useSearchParams } from 'react-router-dom'; import { + RPC_URLS, TON_CONNECT_MANIFEST_URL, TREZOR_MANIFEST, WC_PROJECT_ID, @@ -41,6 +42,7 @@ export function App() { walletConnectProjectId: WC_PROJECT_ID, trezorManifest: TREZOR_MANIFEST, tonConnect: { manifestUrl: TON_CONNECT_MANIFEST_URL }, + rpcUrls: RPC_URLS, }; } if (!!config) { diff --git a/widget/app/src/constants.ts b/widget/app/src/constants.ts index 02a20ef1ea..bd4ea19715 100644 --- a/widget/app/src/constants.ts +++ b/widget/app/src/constants.ts @@ -5,3 +5,11 @@ export const TREZOR_MANIFEST = { }; export const TON_CONNECT_MANIFEST_URL = 'https://raw.githubusercontent.com/rango-exchange/assets/refs/heads/main/manifests/tonconnect/manifest.json'; + +/** + * RPC urls for wallets that can't read the chain through themselves, such as + * Ledger and Trezor. Only Ethereum is configured here, on a public node. + */ +export const RPC_URLS = { + evm: { 1: ['https://ethereum-rpc.publicnode.com'] }, +}; diff --git a/widget/embedded/package.json b/widget/embedded/package.json index 7fe96946e2..51d57e40c0 100644 --- a/widget/embedded/package.json +++ b/widget/embedded/package.json @@ -25,8 +25,8 @@ "dependencies": { "@hub3js/bip122": "^0.4.0", "@hub3js/core": "^0.64.0", - "@hub3js/evm": "^0.8.0", - "@hub3js/namespaces": "^0.8.0", + "@hub3js/evm": "0.8.1-next.2", + "@hub3js/namespaces": "0.8.1-next.1", "@hub3js/solana": "^0.7.0", "@hub3js/starknet": "^0.6.0", "@hub3js/std": "^0.6.0", @@ -43,7 +43,6 @@ "@rango-dev/queue-manager-core": "^0.36.1-next.0", "@rango-dev/queue-manager-rango-preset": "^0.66.1-next.1", "@rango-dev/queue-manager-react": "^0.36.1-next.0", - "@rango-dev/signer-evm": "^0.47.1", "@rango-dev/signer-solana": "^0.51.1-next.0", "@rango-dev/ui": "^0.67.1-next.1", "@rango-dev/wallets-react": "^0.50.1-next.1", diff --git a/widget/embedded/src/containers/WidgetProvider/WidgetProvider.tsx b/widget/embedded/src/containers/WidgetProvider/WidgetProvider.tsx index 0ab52631d1..35c8566f72 100644 --- a/widget/embedded/src/containers/WidgetProvider/WidgetProvider.tsx +++ b/widget/embedded/src/containers/WidgetProvider/WidgetProvider.tsx @@ -1,7 +1,6 @@ import type { PropTypes } from './WidgetProvider.types'; import type { PropsWithChildren } from 'react'; -import { setEvmSignerConfig } from '@rango-dev/signer-evm'; import { setSolanaSignerConfig } from '@rango-dev/signer-solana'; import React, { useEffect, useMemo } from 'react'; @@ -54,12 +53,6 @@ export function WidgetProvider(props: PropsWithChildren) { } }, [props.config?.signers?.customSolanaRPC]); - useEffect(() => { - if (props.config?.signers?.customEthereumRPC) { - setEvmSignerConfig('customRPC', props.config.signers.customEthereumRPC); - } - }, [props.config?.signers?.customEthereumRPC]); - return ( [0]) => + rpcURLsFromConfig(config).evm?.map(({ chain, rpcUrls }) => [ + chain.id, + rpcUrls, + ]); + +describe('rpcURLsFromConfig', () => { + test('falls back to the default node on Ethereum when nothing is configured', () => { + expect(urlsByChain({ apiKey: '' })).toEqual([ + [1, [DEFAULT_ETHEREUM_RPC_URL]], + ]); + }); + + test('takes EVM urls per chain from rpcUrls', () => { + expect( + urlsByChain({ + apiKey: '', + rpcUrls: { evm: { [BSC_CHAIN_ID]: ['https://bsc.example'] } }, + }) + ).toEqual([ + [1, [DEFAULT_ETHEREUM_RPC_URL]], + [BSC_CHAIN_ID, ['https://bsc.example']], + ]); + }); + + test("doesn't add the default node when Ethereum has urls", () => { + expect( + urlsByChain({ + apiKey: '', + rpcUrls: { evm: { 1: ['https://eth.example'] } }, + }) + ).toEqual([[1, ['https://eth.example']]]); + }); + + test('tries customEthereumRPC first on Ethereum', () => { + expect( + urlsByChain({ + apiKey: '', + signers: { customEthereumRPC: 'https://custom.eth' }, + rpcUrls: { evm: { 1: ['https://eth.example'] } }, + }) + ).toEqual([[1, ['https://custom.eth', 'https://eth.example']]]); + + expect( + urlsByChain({ + apiKey: '', + signers: { customEthereumRPC: 'https://custom.eth' }, + }) + ).toEqual([[1, ['https://custom.eth']]]); + }); +}); diff --git a/widget/embedded/src/store/slices/config.ts b/widget/embedded/src/store/slices/config.ts index 136207dd00..2126130d85 100644 --- a/widget/embedded/src/store/slices/config.ts +++ b/widget/embedded/src/store/slices/config.ts @@ -9,6 +9,7 @@ import type { Provider } from '@hub3js/core'; import { allProviders as getAllProviders, + toNamespacesRPCUrls, WalletTypes, } from '@rango-dev/provider-all'; @@ -19,6 +20,8 @@ import { } from '../../utils/providers'; import { matchTokensFromConfigWithMeta } from '../utils'; +const ETHEREUM_CHAIN_ID = 1; + function makeProvidersOptionsFromConfig( config: WidgetConfig ): ProvidersOptions { @@ -82,11 +85,42 @@ export interface ConfigSlice { getAvailableProviders: () => Provider[]; } +/** + * The public Ethereum node wallets without an RPC of their own (Ledger, Trezor) + * read through when the dapp configures none, the same node the EVM signer + * used. It keeps them working for dapps that predate `rpcUrls`. + */ +export const DEFAULT_ETHEREUM_RPC_URL = 'https://ethereum-rpc.publicnode.com'; + +/** + * The RPC urls from the config, with `signers.customEthereumRPC` tried first on + * Ethereum. Providers get them when they're built. Ethereum falls back to + * `DEFAULT_ETHEREUM_RPC_URL` when nothing is configured for it; other chains + * only get the urls the dapp configures. + */ +export function rpcURLsFromConfig(config: WidgetConfigWithoutLegacyProviders) { + const evm = { ...config.rpcUrls?.evm }; + const customEthereumRPC = config.signers?.customEthereumRPC; + + if (customEthereumRPC) { + evm[ETHEREUM_CHAIN_ID] = [ + customEthereumRPC, + ...(evm[ETHEREUM_CHAIN_ID] ?? []), + ]; + } + if (!evm[ETHEREUM_CHAIN_ID]?.length) { + evm[ETHEREUM_CHAIN_ID] = [DEFAULT_ETHEREUM_RPC_URL]; + } + + return toNamespacesRPCUrls({ ...config.rpcUrls, evm }); +} + function generateProviders( config: WidgetConfigWithoutLegacyProviders ): Provider[] { const allProviders = getAllProviders(); - const allBuiltProviders = allProviders.map((build) => build()); + const rpcURLs = rpcURLsFromConfig(config); + const allBuiltProviders = allProviders.map((build) => build(rpcURLs)); return allBuiltProviders.filter((provider) => hasRequiredConfig(provider.id, config) diff --git a/widget/embedded/src/types/config.ts b/widget/embedded/src/types/config.ts index e9be5b99b8..6f4b14c16f 100644 --- a/widget/embedded/src/types/config.ts +++ b/widget/embedded/src/types/config.ts @@ -1,4 +1,5 @@ import type { Provider, WalletType } from '@hub3js/core'; +import type { RpcUrlsConfig } from '@rango-dev/provider-all'; import type { Language, theme } from '@rango-dev/ui'; import type { ProviderInterface } from '@rango-dev/wallets-react'; import type { Asset } from 'rango-sdk'; @@ -114,6 +115,7 @@ export type BlockchainAndTokenConfig = { * * @property {string | string[]} customSolanaRPC - This is an optional property that can be used to set custom Solana RPCs. * @property {string} customEthereumRPC - This is an optional property that can be used to set a custom Ethereum RPC. + * It's tried first for chain 1, before any url in `rpcUrls.evm`. */ export type SignersConfig = { customSolanaRPC?: string | string[]; @@ -258,6 +260,11 @@ export type LedgerWalletConfig = { * - 'avoidNativeFee': If you want to exclude swappers that have native tokens as fee, for example when you are using an AA account, you could set this parameter. * - 'experimental': Use this parameter to enable experimental routes. This settings shouldn't be used in your production environment. * - 'enableCentralizedSwappers': If you want to enable routing from the centralized protocols like XO Swap, you could set this parameter. + * @property {RpcUrlsConfig} rpcUrls - Optional RPC urls that wallets without an RPC of their own + * (e.g. Ledger and Trezor) read the chain through. EVM urls are keyed by chain id, e.g. + * `{ evm: { 1: ['https://…'], 56: ['https://…'] } }`. `signers.customEthereumRPC`, if set, is tried + * first for chain 1. Without any url for chain 1, a public Ethereum node is used, as before `rpcUrls` existed. + * Reads on any other chain without urls fail. * @property {WidgetVariant} variant * If it is expanded, multiple routes will show up on the home page; * If it is full-expanded, multiple routes will show up on the home page with full routes; @@ -292,6 +299,7 @@ export type WidgetConfig = { features?: Features; variant?: WidgetVariant; signers?: SignersConfig; + rpcUrls?: RpcUrlsConfig; // These are likely to change or remove at anytime. Please use with a caution. __UNSTABLE_OR_INTERNAL__?: { walletConnectListedDesktopWalletLink?: string; diff --git a/widget/playground/src/containers/FunctionalLayout/FunctionalLayout.utils.ts b/widget/playground/src/containers/FunctionalLayout/FunctionalLayout.utils.ts index 77de8fd5d8..f94771bf33 100644 --- a/widget/playground/src/containers/FunctionalLayout/FunctionalLayout.utils.ts +++ b/widget/playground/src/containers/FunctionalLayout/FunctionalLayout.utils.ts @@ -13,6 +13,7 @@ export function getWalletsList( blockchains: BlockchainMeta[] ): MapSupportedList[] { const allProviders = getAllProviders(); + // Built only to read each wallet's info, so no RPC urls are needed. const allBuiltProviders = allProviders.map((build) => build()); const walletsList: MapSupportedList[] = []; allBuiltProviders.forEach((provider: Provider) => { diff --git a/widget/playground/src/store/config.ts b/widget/playground/src/store/config.ts index 343ff01e97..9b63a27478 100644 --- a/widget/playground/src/store/config.ts +++ b/widget/playground/src/store/config.ts @@ -15,6 +15,7 @@ import { immer } from 'zustand/middleware/immer'; import { DEFAULT_THEME_COLORS } from '../constants'; import { getConfig, + RPC_URLS, TON_CONNECT_MANIFEST_URL, TREZOR_MANIFEST, } from '../utils/configs'; @@ -81,6 +82,7 @@ export const initialConfig: WidgetConfig = { walletConnectProjectId: getConfig('WC_PROJECT_ID'), trezorManifest: TREZOR_MANIFEST, tonConnect: { manifestUrl: TON_CONNECT_MANIFEST_URL }, + rpcUrls: RPC_URLS, amount: undefined, externalWallets: false, variant: 'default', diff --git a/widget/playground/src/utils/configs.ts b/widget/playground/src/utils/configs.ts index 305a212915..86054ee6fc 100644 --- a/widget/playground/src/utils/configs.ts +++ b/widget/playground/src/utils/configs.ts @@ -55,3 +55,11 @@ export const isConfigChanged = (widgetConfig: WidgetConfig) => { filterConfig(widgetConfig, initialConfig)?.filteredConfigForExport ); }; + +/** + * RPC urls for wallets that can't read the chain through themselves, such as + * Ledger and Trezor. Only Ethereum is configured here, on a public node. + */ +export const RPC_URLS = { + evm: { 1: ['https://ethereum-rpc.publicnode.com'] }, +}; diff --git a/yarn.lock b/yarn.lock index d12f362352..caaca46022 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2927,22 +2927,23 @@ rango-types "^0.6.0" zustand "^4.5.2" -"@hub3js/evm@^0.8.0": - version "0.8.0" - resolved "https://registry.yarnpkg.com/@hub3js/evm/-/evm-0.8.0.tgz#609fb53a75983679bb53c577f05361931407548e" - integrity sha512-QcvCTcd8AMUpSYA6dsJhc8Nw6MyLwOBCoFHSvL4UoBpqi7ICs8z7BkhbPcbmdBb5x3MxdQJ2OfsAjrZvx23bfw== +"@hub3js/evm@0.8.1-next.2", "@hub3js/evm@^0.8.1-next.1": + version "0.8.1-next.2" + resolved "https://registry.yarnpkg.com/@hub3js/evm/-/evm-0.8.1-next.2.tgz#dfe14be111fed84fcb6bb18736a561dd1382e828" + integrity sha512-Eu7DPQleA6xvUYGmcRV98nyj5B6nZNwTUaDy0R/AwDzOg1fy/LQDvyHfEef7mOo2VB3z5+eluR60crgipza/Ng== dependencies: "@hub3js/std" "^0.6.0" caip "^1.1.1" rango-types "^0.6.0" + viem "^2.56.8" -"@hub3js/namespaces@^0.8.0": - version "0.8.0" - resolved "https://registry.yarnpkg.com/@hub3js/namespaces/-/namespaces-0.8.0.tgz#e4441871203f043d8ed2fe91b710c77ff9d3729b" - integrity sha512-cMXTgRIAeBBnMXlNBoz/BPfD5ouIBa1PCM3g6a5srFFbx0D21pQhGliox/waDCk0sYn6A0B/bMdiOh0w6rrTnA== +"@hub3js/namespaces@0.8.1-next.1": + version "0.8.1-next.1" + resolved "https://registry.yarnpkg.com/@hub3js/namespaces/-/namespaces-0.8.1-next.1.tgz#94bf15efa7ac57e5d87b8902c5c27ab9389d9a99" + integrity sha512-mnd/zARrhBdySL8QI+twBoZGcQCccGQ5BDtdebUn3PISMMn2x6MXzAMS696S08Ls3EEdbmnhtLB3/j8tyD+1Yg== dependencies: "@hub3js/bip122" "^0.4.0" - "@hub3js/evm" "^0.8.0" + "@hub3js/evm" "^0.8.1-next.1" "@hub3js/solana" "^0.7.0" "@hub3js/starknet" "^0.6.0" "@hub3js/stellar" "^0.6.0" @@ -5374,118 +5375,118 @@ resolved "https://registry.yarnpkg.com/@remix-run/router/-/router-1.13.0.tgz#7e29c4ee85176d9c08cb0f4456bff74d092c5065" integrity sha512-5dMOnVnefRsl4uRnAdoWjtVTdh8e6aZqgM4puy9nmEADH72ck+uXwzpJLEKE9Q6F8ZljNewLgmTfkxUrBdv4WA== -"@reown/appkit-common@1.8.20": - version "1.8.20" - resolved "https://registry.yarnpkg.com/@reown/appkit-common/-/appkit-common-1.8.20.tgz#53657077c18eac6509ff89a3b308e7b8a7225cc1" - integrity sha512-x6Yc8FaZZaEnsRCu6crYD/s1MA+Ffk35rJNZpug8I26iAJgi+o3rar/0lwZ70dl/QA9ytnwFUFWzhXqkT3O7Og== +"@reown/appkit-common@1.8.24": + version "1.8.24" + resolved "https://registry.yarnpkg.com/@reown/appkit-common/-/appkit-common-1.8.24.tgz#c7bb6fd9b0505e6de93f1d9a9de86693c8d25543" + integrity sha512-BoAGwKwGm4WJ4nkOPk4OsIVGf9NmdINbk5QaCo50j6QJIaIAcL7GVnsV322NBiSuBxobmwbZ3lIezsZCd3G45A== dependencies: big.js "6.2.2" dayjs "1.11.13" - viem ">=2.45.0" + viem ">=2.55.13" -"@reown/appkit-controllers@1.8.20": - version "1.8.20" - resolved "https://registry.yarnpkg.com/@reown/appkit-controllers/-/appkit-controllers-1.8.20.tgz#83d7190e18489448fbad870db0303f13ca0563aa" - integrity sha512-2Gdi/ScftfBK3MwfAJcf/bGRByHgHzaAK8rCzKrYYUqLjbRFR9I/uq7gd6D+w4Xm+NRCpdiKFJY/0zPSfq+gpw== +"@reown/appkit-controllers@1.8.24": + version "1.8.24" + resolved "https://registry.yarnpkg.com/@reown/appkit-controllers/-/appkit-controllers-1.8.24.tgz#fcfd20ec8c2e73814719b0fd82294d36e509b33e" + integrity sha512-ZEB17sTYfNSMGO5lkWWGn4Q53N0tOSFAqHZt4f5Sxj8certjFXNAcKNjf0Z+bxNgU4Pjv3tisZ+6S4ShOxe6Zw== dependencies: - "@reown/appkit-common" "1.8.20" - "@reown/appkit-wallet" "1.8.20" + "@reown/appkit-common" "1.8.24" + "@reown/appkit-wallet" "1.8.24" "@walletconnect/universal-provider" "2.23.7" valtio "2.1.7" - viem ">=2.45.0" + viem ">=2.55.13" -"@reown/appkit-pay@1.8.20": - version "1.8.20" - resolved "https://registry.yarnpkg.com/@reown/appkit-pay/-/appkit-pay-1.8.20.tgz#322a7a86b6b903bef7d9efda5a9d5eab58a0dfe6" - integrity sha512-JEoTVetCWNFJnbkYGtwvdWa7ZW7xF0uOH+jmJvnAbYSXTR+Bd8HdQOMn/AoWulSu6qmjKjNpZQmNjkIUf5yiUw== +"@reown/appkit-pay@1.8.24": + version "1.8.24" + resolved "https://registry.yarnpkg.com/@reown/appkit-pay/-/appkit-pay-1.8.24.tgz#5f0b63cd1aaf4e69f31e634b3b90ebf04149df57" + integrity sha512-/djGjg2xfSLDxI9Bk0DGxplgzg9npFCa5bY+OUTXaSCBPDNFKMBD8e/EAq+UL43fv/wfJewuK0F4FiLnlVDR8w== dependencies: - "@reown/appkit-common" "1.8.20" - "@reown/appkit-controllers" "1.8.20" - "@reown/appkit-ui" "1.8.20" - "@reown/appkit-utils" "1.8.20" + "@reown/appkit-common" "1.8.24" + "@reown/appkit-controllers" "1.8.24" + "@reown/appkit-ui" "1.8.24" + "@reown/appkit-utils" "1.8.24" lit "3.3.0" valtio "2.1.7" -"@reown/appkit-polyfills@1.8.20": - version "1.8.20" - resolved "https://registry.yarnpkg.com/@reown/appkit-polyfills/-/appkit-polyfills-1.8.20.tgz#2cdb91b4cd18298416320a2153cf610e453633d7" - integrity sha512-88qJedSBYkhCZxeyODcQhqKt45OkS28VbZGNsay6t7FexvPcoibYMtkHaP79ojE8OuhV7k3FlrssrjPES3OFCw== +"@reown/appkit-polyfills@1.8.24": + version "1.8.24" + resolved "https://registry.yarnpkg.com/@reown/appkit-polyfills/-/appkit-polyfills-1.8.24.tgz#efe948ed07a86154a04248190d46490e9394a36f" + integrity sha512-HQr6p5lvx73Q+NHSNQpw9IHuxkpT9ri+z5Hpa/W3hrFsA+Z20x5+H3oQoUivEqQGV2LVVQ75v6h7dfWBnRKy1g== dependencies: buffer "6.0.3" -"@reown/appkit-scaffold-ui@1.8.20": - version "1.8.20" - resolved "https://registry.yarnpkg.com/@reown/appkit-scaffold-ui/-/appkit-scaffold-ui-1.8.20.tgz#28bb7a3b07068e7c502d931d911abf2f18d17722" - integrity sha512-Vx0qib30UUbcKT8VeNcCcZkkhtaOT28TtClQ8nKC0EdOkLA08Lxt0j32XpEat2c4Fl6xzAIIOuZO7HRBTxMfzA== - dependencies: - "@reown/appkit-common" "1.8.20" - "@reown/appkit-controllers" "1.8.20" - "@reown/appkit-pay" "1.8.20" - "@reown/appkit-ui" "1.8.20" - "@reown/appkit-utils" "1.8.20" - "@reown/appkit-wallet" "1.8.20" +"@reown/appkit-scaffold-ui@1.8.24": + version "1.8.24" + resolved "https://registry.yarnpkg.com/@reown/appkit-scaffold-ui/-/appkit-scaffold-ui-1.8.24.tgz#04f61814b5a42fc56b3d47e3fa5cea8a4ddf5bee" + integrity sha512-bA5fJQAYAejwWeNUvOQM3luGE1mK9jfzvixx/tNZnatBOavUX07793hXrXksi82QpxOM/H9notgwGGeryDK00w== + dependencies: + "@reown/appkit-common" "1.8.24" + "@reown/appkit-controllers" "1.8.24" + "@reown/appkit-pay" "1.8.24" + "@reown/appkit-ui" "1.8.24" + "@reown/appkit-utils" "1.8.24" + "@reown/appkit-wallet" "1.8.24" lit "3.3.0" -"@reown/appkit-ui@1.8.20": - version "1.8.20" - resolved "https://registry.yarnpkg.com/@reown/appkit-ui/-/appkit-ui-1.8.20.tgz#95c8d7ac21100674b58e2a4f234f0f68b885e4ce" - integrity sha512-ObWhgu+4capnVhxtEG0VMRtGHwr6bso9VUcxDIfUDpjNAMi1HQBvXiBJ/R098Gvjmjz0QLwNe8YNVe50KaCTVw== +"@reown/appkit-ui@1.8.24": + version "1.8.24" + resolved "https://registry.yarnpkg.com/@reown/appkit-ui/-/appkit-ui-1.8.24.tgz#9017ac7e08a916d37c98f00cf0ae2417c72ebbb1" + integrity sha512-Ex4/s9TtFZfrj0vjNBeH3uy23bIkZbOikcfJ3rInjGAN2ujyrb0ed9ZUWaiNTveVh06hjglYdgQ7B6nYDTBxSw== dependencies: "@phosphor-icons/webcomponents" "2.1.5" - "@reown/appkit-common" "1.8.20" - "@reown/appkit-controllers" "1.8.20" - "@reown/appkit-wallet" "1.8.20" + "@reown/appkit-common" "1.8.24" + "@reown/appkit-controllers" "1.8.24" + "@reown/appkit-wallet" "1.8.24" lit "3.3.0" qrcode "1.5.3" -"@reown/appkit-utils@1.8.20": - version "1.8.20" - resolved "https://registry.yarnpkg.com/@reown/appkit-utils/-/appkit-utils-1.8.20.tgz#8c20c8f501680dc88f1ce598a058ada9fa403b6a" - integrity sha512-ZVPUhZm/8TbR5MI1GzhazpUShrjVhZCC8Fyc7m+VXSPVZkPiW7K2AtTDAqhfYeStvBSJIvC6jbKwhlaWGR1TDQ== +"@reown/appkit-utils@1.8.24": + version "1.8.24" + resolved "https://registry.yarnpkg.com/@reown/appkit-utils/-/appkit-utils-1.8.24.tgz#dd90e205d930f5e235930b72d7ae95dc9079e1d9" + integrity sha512-HsGAgbWg4SPlZJJGNaKeynrtRZwa9iDPIXQ3iSi/Rc4g0IxZ6ahIGciZzLR/t1QM2Ehmx2MhM6LXVHa4PGbC3A== dependencies: - "@reown/appkit-common" "1.8.20" - "@reown/appkit-controllers" "1.8.20" - "@reown/appkit-polyfills" "1.8.20" - "@reown/appkit-wallet" "1.8.20" + "@reown/appkit-common" "1.8.24" + "@reown/appkit-controllers" "1.8.24" + "@reown/appkit-polyfills" "1.8.24" + "@reown/appkit-wallet" "1.8.24" "@wallet-standard/wallet" "1.1.0" "@walletconnect/logger" "3.0.2" "@walletconnect/universal-provider" "2.23.7" valtio "2.1.7" - viem ">=2.45.0" + viem ">=2.55.13" optionalDependencies: "@base-org/account" "2.4.0" "@coinbase/wallet-sdk" "4.3.6" "@safe-global/safe-apps-provider" "0.18.6" "@safe-global/safe-apps-sdk" "9.1.0" -"@reown/appkit-wallet@1.8.20": - version "1.8.20" - resolved "https://registry.yarnpkg.com/@reown/appkit-wallet/-/appkit-wallet-1.8.20.tgz#a439e7e6063a734ff0a0438ec6f28e270744d463" - integrity sha512-fEYnCQTQFSi8qtGfdQp7BHAVD8yiijPgjXhel0jFLKTX5leufGKjrERtnn2vABoUHQucwQzI+Q958Bnx/lHE2w== +"@reown/appkit-wallet@1.8.24": + version "1.8.24" + resolved "https://registry.yarnpkg.com/@reown/appkit-wallet/-/appkit-wallet-1.8.24.tgz#59bb9f9512b8ed8313b2fe9c2e5c8382c210a7c3" + integrity sha512-MgJ5H25m7PgHwPzzv5nKnzdrMI6F+9zU3oIYsIWT/I/h4EfnN2COt+WuI7uX2Z2J2pWyHi0uDrysRgHU7DPAOw== dependencies: - "@reown/appkit-common" "1.8.20" - "@reown/appkit-polyfills" "1.8.20" + "@reown/appkit-common" "1.8.24" + "@reown/appkit-polyfills" "1.8.24" "@walletconnect/logger" "3.0.2" zod "3.22.4" -"@reown/appkit@1.8.20": - version "1.8.20" - resolved "https://registry.yarnpkg.com/@reown/appkit/-/appkit-1.8.20.tgz#ca6216e76da79493054e285c015c8b6bdbd83004" - integrity sha512-+OI1TWg3XcMRhZ5RGVF0+AjkUvTPpODP6HFIgmxsV8HCf6bfE+jaYYE+JJcaz05TYJJ2TCXSYDyRfRvjSUzMzg== - dependencies: - "@reown/appkit-common" "1.8.20" - "@reown/appkit-controllers" "1.8.20" - "@reown/appkit-pay" "1.8.20" - "@reown/appkit-polyfills" "1.8.20" - "@reown/appkit-scaffold-ui" "1.8.20" - "@reown/appkit-ui" "1.8.20" - "@reown/appkit-utils" "1.8.20" - "@reown/appkit-wallet" "1.8.20" +"@reown/appkit@1.8.24": + version "1.8.24" + resolved "https://registry.yarnpkg.com/@reown/appkit/-/appkit-1.8.24.tgz#5bf85af4f45ada612cf4507d947fa4b7da2e399a" + integrity sha512-FXxZk+H/1PMABskdaMo+iuzr/9Oi6EYUw75PxeqzvGFVdB5YLAv9HIlIEc/nQiYv8SPoRy6y19TAae9ndiHmqA== + dependencies: + "@reown/appkit-common" "1.8.24" + "@reown/appkit-controllers" "1.8.24" + "@reown/appkit-pay" "1.8.24" + "@reown/appkit-polyfills" "1.8.24" + "@reown/appkit-scaffold-ui" "1.8.24" + "@reown/appkit-ui" "1.8.24" + "@reown/appkit-utils" "1.8.24" + "@reown/appkit-wallet" "1.8.24" "@walletconnect/universal-provider" "2.23.7" bs58 "6.0.0" semver "7.7.2" valtio "2.1.7" - viem ">=2.45.0" + viem ">=2.55.13" optionalDependencies: "@lit/react" "1.0.8" @@ -15074,10 +15075,10 @@ own-keys@^1.0.1: object-keys "^1.1.1" safe-push-apply "^1.0.0" -ox@0.14.30: - version "0.14.30" - resolved "https://registry.yarnpkg.com/ox/-/ox-0.14.30.tgz#aee7e72c8f179d8666a7f14e1ae7e28a0fcbea98" - integrity sha512-LI11uu+8iiM1B3CLckgd++YF1a0A2k5wDoM9ZeQMiL21BOzQs6L//BLS6hb1HSEKCyycdDIQLsVQx9MjpcC0hA== +ox@0.14.63: + version "0.14.63" + resolved "https://registry.yarnpkg.com/ox/-/ox-0.14.63.tgz#5d8136d832d885c53cc16814899af1c8ab465cb7" + integrity sha512-TSKYN151boL1Aq/vsFrd8Buvd7v+oTQr8V7z4f4QQTSMB+ohD8cbNbHCtKRLI0Gs8LuYKirf5qvElTKVIFe2jw== dependencies: "@adraffy/ens-normalize" "^1.11.0" "@noble/ciphers" "^1.3.0" @@ -18004,10 +18005,10 @@ varuint-bitcoin@^1.1.2: dependencies: safe-buffer "^5.1.1" -viem@>=2.45.0, viem@^2.27.2, viem@^2.31.7, viem@^2.47.0: - version "2.54.6" - resolved "https://registry.yarnpkg.com/viem/-/viem-2.54.6.tgz#df97b26ebf4ca67cc1f9ebf49c07076d6edb9b87" - integrity sha512-OfybECKJYVmhiNqz+SHhed+O2h6niQ+0Wjg9J0b4bV+/QrvLgjxhfKO7hZqsuK1YtZ/0BErBKy708Zp+cU5T0Q== +viem@>=2.55.13, viem@^2.27.2, viem@^2.31.7, viem@^2.47.0, viem@^2.56.8: + version "2.57.17" + resolved "https://registry.yarnpkg.com/viem/-/viem-2.57.17.tgz#9fd4060ade0f09cdc8a9d73910867f0929efe7ed" + integrity sha512-yIMqNoKoVAMwX+zVbqkxfqq7qbGHmKXZidh/xfVpiPTJlAbbDDdDIMH5dDQWxhZcj56L8tPOwsIIxF618P+TOg== dependencies: "@noble/curves" "1.9.1" "@noble/hashes" "1.8.0" @@ -18015,7 +18016,7 @@ viem@>=2.45.0, viem@^2.27.2, viem@^2.31.7, viem@^2.47.0: "@scure/bip39" "1.6.0" abitype "1.2.3" isows "1.0.7" - ox "0.14.30" + ox "0.14.63" ws "8.21.0" viem@^2.1.1: